text
stringlengths
13
6.01M
using AutoMapper; using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using XH.Commands.Enterprises; using XH.Commands.Enterprises.Base; using XH.Domain.Enterprises; using XH.Domain.Exceptions; using XH.Infrastructure.Command; using XH.Infrastructure.Domain.Repositories; using XH.Infrastructure.Extensions; using XH.Infrastructure.Tree; namespace XH.Command.Handlers { public class EnterpriseCommandHandler : ICommandHandler<CreateEnterpriseManagementCategoryCommand>, ICommandHandler<UpdateEnterpriseManagementCategoryCommand>, ICommandHandler<DeleteEnterpriseManagementCategoryCommand>, ICommandHandler<CreateEnterpriseCommand>, ICommandHandler<UpdateEnterpriseCommand>, ICommandHandler<DeleteEnterpriseCommand>, ICommandHandler<CreateEnterpriseTypeCommand>, ICommandHandler<UpdateEnterpriseTypeCommand>, ICommandHandler<DeleteEnterpriseTypeCommand> { private readonly IMapper _mapper; private readonly IRepository<EnterpriseManagementCategory> _enterpriseManagementCategoryRepository; private readonly IRepository<Enterprise> _enterpriseRepository; private readonly IRepository<EnterpriseType> _enterpriseTypeRepository; public EnterpriseCommandHandler( IRepository<EnterpriseManagementCategory> enterpriseManagementCategoryRepository, IRepository<Enterprise> enterpriseRepository, IRepository<EnterpriseType> enterpriseTypeRepository, IMapper mapper) { _enterpriseManagementCategoryRepository = enterpriseManagementCategoryRepository; _enterpriseRepository = enterpriseRepository; _enterpriseTypeRepository = enterpriseTypeRepository; _mapper = mapper; } public void Handle(CreateEnterpriseTypeCommand command) { CheckCreateOrUpdateRegionCommand(command); if (!command.DisplayOrder.HasValue) { // Genenrate display order command.DisplayOrder = _enterpriseTypeRepository.Count(it => it.ParentId == command.ParentId) + 1; } var entity = _mapper.Map<EnterpriseType>(command); _enterpriseTypeRepository.Insert(entity); StandardizingEnterpriseTypes(); } public void StandardizingEnterpriseTypes() { var allTypes = _enterpriseTypeRepository.GetAll().ToList(); TreeHelper.StandardizingTreeNodes(allTypes, null); _enterpriseTypeRepository.UpdateMany(allTypes); } public void Handle(UpdateEnterpriseTypeCommand command) { CheckCreateOrUpdateRegionCommand(command); var entity = _enterpriseTypeRepository.Get(command.Id); DomainException.ThrowIf<EntityNotFoundException>(entity == null, $"指定企业不存在"); _mapper.Map(command, entity); _enterpriseTypeRepository.Update(entity); StandardizingEnterpriseTypes(); } private void CheckCreateOrUpdateRegionCommand(CreateOrUpdateEnterpriseTypeCommand command) { if (command.ParentId.IsNotNullOrEmpty()) { var parentEntity = _enterpriseTypeRepository.Get(command.ParentId); if (parentEntity == null) { throw new EntityNotFoundException("指定父级类型不存在"); } } } public void Handle(DeleteEnterpriseTypeCommand command) { var isExist = _enterpriseTypeRepository.Count(it => it.Id == command.Id) > 0; DomainException.ThrowIf<EntityNotFoundException>(!isExist, $"指定企业不存在"); var allTypes = _enterpriseTypeRepository.GetAll().ToList(); var descendantIds = GetDescendantEnterpriseTypeIds(command.Id, allTypes).ToList(); descendantIds.Insert(0, command.Id); _enterpriseTypeRepository.Delete(it => descendantIds.Contains(it.Id)); } /// <summary> /// /// </summary> /// <returns></returns> private IEnumerable<string> GetDescendantEnterpriseTypeIds(string nodeId, IEnumerable<EnterpriseType> allNodes) { var ids = new List<string>(); var childNodeIds = allNodes.Where(it => it.ParentId == nodeId).Select(it => it.Id).ToList(); childNodeIds = childNodeIds ?? new List<string>(); if (childNodeIds == null || !childNodeIds.Any()) { return ids; } ids.AddRange(childNodeIds); foreach (var childNodeId in childNodeIds) { var tempNodeIds = GetDescendantEnterpriseTypeIds(childNodeId, allNodes); ids.AddRange(tempNodeIds); } return ids; } public void Handle(CreateEnterpriseCommand command) { var entity = _mapper.Map<Enterprise>(command); _enterpriseRepository.Insert(entity); } public void Handle(UpdateEnterpriseCommand command) { var entity = _enterpriseRepository.Get(command.Id); DomainException.ThrowIf<EntityNotFoundException>(entity == null, $"指定企业不存在"); _mapper.Map(command, entity); _enterpriseRepository.Update(entity); } public void Handle(DeleteEnterpriseCommand command) { var isExist = _enterpriseRepository.Count(it => it.Id == command.Id) > 0; DomainException.ThrowIf<EntityNotFoundException>(!isExist, $"指定企业不存在"); _enterpriseRepository.Delete(command.Id); } public void Handle(CreateEnterpriseManagementCategoryCommand command) { var entity = _mapper.Map<EnterpriseManagementCategory>(command); entity.Id = Guid.NewGuid().ToString(); entity.DisplayOrder = _enterpriseManagementCategoryRepository.Count() > 0 ? _enterpriseManagementCategoryRepository.GetAll().Max(it => it.DisplayOrder) + 1 : 1; // check unqiue code and slug _enterpriseManagementCategoryRepository.Insert(entity); } public void Handle(UpdateEnterpriseManagementCategoryCommand command) { var entity = _enterpriseManagementCategoryRepository.Get(command.Id); Contract.Assert(entity != null); entity = _mapper.Map(command, entity); _enterpriseManagementCategoryRepository.Update(entity); } public void Handle(DeleteEnterpriseManagementCategoryCommand command) { _enterpriseManagementCategoryRepository.Delete(command.Id); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using DataAccess; using DataAccess.Model; using DataAccess.Repository; using KioskClient.Domain; using KioskClient.Properties; using KioskClient.View; namespace KioskClient.ViewModel { // Yeah. Dear diary. TOday my life was on on hair(on last opportynity). My friend was knocking on a random // guy's window. A guy has ran at us. He said that his child woke up and he was gonna kill us. He has put his // knife to Vova's neck. And and to Bruns's neck. Bruns said 'Come on, do it, cut me off.' but the guy said // 'Go with peace guys. Go with peace.'. That was really strange. // Looked like he was drunk but it felt like he wasn't. Unless we was. That's strange. Im drunk. public class AuditoriumMapPageViewModel : ViewModelBase, INotifyPropertyChanged { private readonly TicketRepository repository; private readonly List<AuditoriumSeat> seats; private readonly Showtime showtime; public AuditoriumMapPageViewModel(AuditoriumMapPage view, TicketRepository repository, Showtime showtime) { this.view = view; this.repository = repository; this.showtime = showtime; seats = new List<AuditoriumSeat>(); var occupiedSeats = repository.GetOccupiedSeats(showtime.Id).ToList(); Auditorium = new AuditoriumView(showtime.Auditorium, occupiedSeats); Auditorium.PropertyChanged += SelectionChanged; Total = "0"; } public AuditoriumView Auditorium { get; set; } public string Total { get; set; } public string SeatsString { get; set; } public bool CanCheckout { get; set; } public event PropertyChangedEventHandler PropertyChanged; private void SelectionChanged(object sender, PropertyChangedEventArgs propertyChangedEventArgs) { var changedSeat = (AuditoriumSeat) sender; if (changedSeat.IsSelected) { seats.Add(changedSeat); } else { seats.Remove(changedSeat); } SeatsString = BuildSelectedSeatsString(); Total = (showtime.Price * seats.Count).ToString(); CanCheckout = seats.Count != 0; OnPropertyChanged("Total"); OnPropertyChanged("SeatsString"); OnPropertyChanged("CanCheckout"); } private string BuildSelectedSeatsString() { if (seats.Count == 0) return string.Empty; if (seats.Count > 3) { var caseService = new NumericCaseService( Resources.SeatsTextSingle, Resources.SeatsTextCouple, Resources.SeatsTextMany); return caseService.GetCaseString(seats.Count); } var seatsString = ""; seats.ForEach(seat => { seatsString += seat.SeatString + Environment.NewLine; }); return seatsString; } public void GoBack() { Window.NavigateBack(); } [DataAccess.Annotations.NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } public void GoToCheckoutPage() { var selectedSeats = seats.Where(seat => seat.IsSelected); Window.NavigateToCheckoutPage(showtime, selectedSeats); } } }
using System.Collections.Generic; using Agora.EventStore.Eventing; namespace Agora.EventStore.EventStore { public interface IEventStore { void CreateStream(string streamName); void AppendToStream(string streamName, IEvent eventData); IEnumerable<IEvent> ReadFromStream(string streamName); } }
namespace WebStore.DomainNew.ViewModels { public enum BreadCrumbType { None = 0, Category = 1, Brand = 2, Item = 3 } }
using IDI.Core.Common; using IDI.Digiccy.Common.Enums; using IDI.Digiccy.Models.Transaction; namespace IDI.Digiccy.Domain.Transaction.Services { public interface ITransactionService { bool Running { get; } void Start(); void Stop(); Result Bid(int uid, decimal price, decimal size); Result Ask(int uid, decimal price, decimal size); Result<KLine> GetKLine(KLineRange range); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace SalesManagementDemo.Controllers { public class OrdersPageController : Controller { // GET: OrderPage public ActionResult Index() { return View(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestCameraScript : MonoBehaviour { public Transform target; private float xRot; private float yRot; public float ms = 2.0f; public Vector2 distance = new Vector2(3,1); public Vector2 angle = new Vector2(-15,45); // Use this for initialization void Start () { transform.position = target.position - transform.forward * distance.x + transform.up * distance.y; } // Update is called once per frame void Update () { yRot += Input.GetAxis ("Mouse X") * ms; xRot -= Input.GetAxis ("Mouse Y") * ms; xRot = Mathf.Clamp (xRot, angle.x, angle.y); } void LateUpdate(){ transform.rotation = Quaternion.Euler (xRot, yRot, 0.0f); transform.position = target.position - transform.forward * distance.x + transform.up * distance.y; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace Engine { public class EndScreenComp:BaseComponent { public TextRendererOnScreen TextRendererOnScreen; public string Score { get; set; } public override void Update() { if (GameState.KeyboardState.IsKeyDown(Keys.Space)) TUAGameState.CurrentGame.Exit(); TextRendererOnScreen.Text = Score; base.Update(); } public override void Start() { TextRendererOnScreen = GameObject.GetComponent<TextRendererOnScreen>(); TextRendererOnScreen.Position = new Vector2(680, 146); TextRendererOnScreen.Color = Color.Black; Score = string.Empty; base.Start(); } } }
using Microsoft.AspNetCore.Http; using System; using System.Threading.Tasks; namespace gView.Server.Middleware { public class XForwardedMiddleware { private readonly RequestDelegate _next; public XForwardedMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { var xproto = context.Request.Headers["X-Forwarded-Proto"].ToString(); if (xproto != null && xproto.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { context.Request.Scheme = "https"; } await _next(context); } } }
using UnityEngine; using System.Collections; public class BackGround : MonoBehaviour { //public GameObject back; private Vector2 initMousePos; //sdfsfsd public float minY=8,maxY=23,minX,maxX; void setPos(int i) { this.transform.position = new Vector2 (0, 23); minY = i; } void OnMouseDown() { if(Time.timeScale !=0) initMousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition); } void OnMouseDrag() { if(Time.timeScale !=0) { Vector2 worldpoint; worldpoint = Camera.main.ScreenToWorldPoint (Input.mousePosition); Vector2 diffPos = worldpoint - initMousePos; initMousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition); transform.position = new Vector2 (Mathf.Clamp ((transform.position.x + diffPos.x),minX,maxX),Mathf.Clamp ((transform.position.y + diffPos.y),minY,maxY)); } } }
using Microsoft.Extensions.Logging; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; namespace Accenture.DataSaver.Processors { public class MessageConsumer { MessageExtractor _extractor; private IModel _channel; private readonly ILogger<MessageConsumer> _logger; public MessageConsumer(MessageExtractor extractor, ILogger<MessageConsumer> logger) { _logger=logger; _extractor = extractor; } public void Register(ConnectionFactory factory) { if(!string.IsNullOrEmpty(System.Environment.GetEnvironmentVariable("RABBIT_MQ_URI"))) factory.Uri = new Uri(System.Environment.GetEnvironmentVariable("RABBIT_MQ_URI")); Console.WriteLine("Connecting to RabbitMQ : " + factory.Uri.ToString()); var connection = factory.CreateConnection(); _channel = connection.CreateModel(); _channel.ExchangeDeclare("configuration", type: "topic", durable: true); _channel.QueueDeclare("dataSaver"); _channel.QueueBind("dataSaver", "configuration", "*.*"); _channel.ConfirmSelect(); _channel.BasicAcks += ChannelBasicAck; var consumer = new EventingBasicConsumer(_channel); consumer.Received += (consumerModel, ea) => { try { _extractor.ConsumeMessage(ea, factory); } catch (Exception ex) { Console.WriteLine($"Error {ex}"); } }; _channel.BasicQos(0, 10000, false); _channel.BasicConsume("dataSaver", true, consumer: consumer); } public void DeRegister(ConnectionFactory factory) { if (_channel != null) _channel.Close(); } private void ChannelBasicAck(object sender, BasicAckEventArgs e) { Console.WriteLine($"Received Acknowledgement {e.DeliveryTag}"); } } }
using CoreGraphics; namespace ResidentAppCross.iOS { public interface ISoftKeyboardEventsListener { void DidShowKeyboard(); void DidHideKeyboard(); void WillShowKeyboard(ref CGRect overrideDefaultScroll); void WillHideKeyboard(ref CGRect overrideDefaultScroll); } }
using ND.FluentTaskScheduling.Domain.interfacelayer; using ND.FluentTaskScheduling.Model; using ND.FluentTaskScheduling.Model.enums; using ND.FluentTaskScheduling.Model.request; using ND.FluentTaskScheduling.Model.response; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; namespace ND.FluentTaskScheduling.WebApi.Controllers { [RoutePrefix("api/performance")] public class PerformanceController : BaseController { public IPerformanceRepository performancerepository; public ITaskRepository taskrep; public INodeRepository noderep; public INodePerformanceRepository nodeperformanceRep; public INodeMonitorRepository nodemonitorRep; public PerformanceController(INodeMonitorRepository nodemonitorRepostory,INodeRepository noderepostory, INodePerformanceRepository nodeperformanceRepostory,IPerformanceRepository rep, ITaskRepository taskrepostory, INodeRepository nodeRep, IUserRepository userRep) : base(nodeRep, userRep) { performancerepository = rep; taskrep=taskrepostory; nodeperformanceRep = nodeperformanceRepostory; noderep = noderepository; nodemonitorRep = nodemonitorRepostory; } #region 添加任务性能 /// <summary> /// 载入命令列表 /// </summary> /// <param name="req">载入命令列表请求类</param> /// <remarks>命令列表</remarks> /// <returns></returns> // [SignAuthorize] [ResponseType(typeof(ResponseBase<EmptyResponse>))] [HttpPost, Route("addperformance")] public ResponseBase<EmptyResponse> AddPerformance(AddPerformanceRequest req) { try { int nodeId = req.NodeId; if (nodeId > 0) { var node = noderepository.FindSingle(x => x.id == nodeId); if (node == null) { return ResponseToClient<EmptyResponse>(ResponesStatus.Failed, "当前节点" + req.NodeId + "不存在库中!"); } } performancerepository.Add(new tb_performance() { cpu = double.Parse(req.Cpu), installdirsize = double.Parse(req.InstallDirsize), lastupdatetime=Convert.ToDateTime(req.Lastupdatetime), memory = double.Parse(req.Memory), nodeid=req.NodeId, taskid=req.TaskId }); return ResponseToClient<EmptyResponse>(ResponesStatus.Success, ""); } catch (Exception ex) { return ResponseToClient<EmptyResponse>(ResponesStatus.Exception, JsonConvert.SerializeObject(ex)); } } #endregion #region 获取任务的性能列表 /// <summary> /// 载入命令列表 /// </summary> /// <param name="req">载入命令列表请求类</param> /// <remarks>命令列表</remarks> /// <returns></returns> // [SignAuthorize] [ResponseType(typeof(ResponseBase<PageInfoResponse<LoadPerformancelistResponse>>))] [HttpPost, Route("loadperformancelist")] public ResponseBase<PageInfoResponse<LoadPerformancelistResponse>> LoadPerformancelist(LoadPerformancelistRequest req) { try { int pageIndex = (req.iDisplayStart / req.iDisplayLength) + 1; int totalCount = 0; LoadPerformancelistResponse performanceDetail = new LoadPerformancelistResponse(); List<int> taskidlist = taskrep.LoadTaskPageList(out totalCount, new LoadTaskListRequest() { iDisplayLength = req.iDisplayLength, sEcho = req.sEcho, iDisplayStart = req.iDisplayStart }).Select(x=>x.Task.id).Distinct().ToList(); taskidlist.ForEach(m => { var performancelist = performancerepository.Find(x => m == x.taskid && x.taskid == (req.TaskId <= 0 ? x.taskid : req.TaskId) && x.nodeid == (req.NodeId <= 0 ? x.nodeid : req.NodeId)).OrderByDescending(x => x.lastupdatetime).Take(15).ToList().OrderBy(x => x.lastupdatetime).ToList(); performancelist.ForEach(x => { if (performanceDetail.TaskPerfomance.ContainsKey(x.taskid.ToString())) { performanceDetail.TaskPerfomance[x.taskid.ToString()].Add(x); } else { performanceDetail.TaskPerfomance.Add(x.taskid.ToString(), new List<tb_performance>() { x }); } }); }); return ResponseToClient<PageInfoResponse<LoadPerformancelistResponse>>(ResponesStatus.Success, "", new PageInfoResponse<LoadPerformancelistResponse>() { aaData = performanceDetail,iTotalDisplayRecords=totalCount,iTotalRecords=totalCount,sEcho= req.sEcho }); } catch (Exception ex) { return ResponseToClient<PageInfoResponse<LoadPerformancelistResponse>>(ResponesStatus.Exception, JsonConvert.SerializeObject(ex)); } } #endregion #region 添加节点所在机子性能 /// <summary> /// 载入命令列表 /// </summary> /// <param name="req">添加节点所在机子性能请求类</param> /// <returns></returns> // [SignAuthorize] [ResponseType(typeof(ResponseBase<EmptyResponse>))] [HttpPost, Route("addnodeperformance")] public ResponseBase<EmptyResponse> AddNodePerformance(AddNodePerformanceRequest req) { try { req.NodePerformance.lastupdatetime = DateTime.Now; nodeperformanceRep.Add(req.NodePerformance); if (!string.IsNullOrEmpty(req.MonitorClassName)) { var nodemonitor = nodemonitorRep.FindSingle(x => x.nodeid == req.NodePerformance.nodeid && x.classname == req.MonitorClassName); if (nodemonitor != null) { Dictionary<string, string> dic = new Dictionary<string, string>() { { "lastmonitortime", DateTime.Now.AddSeconds(10).ToString("yyyy-MM-dd HH:mm:ss") }, { "monitorstatus", ((int)MonitorStatus.Monitoring).ToString() } }; nodemonitorRep.UpdateById(new List<int>() { nodemonitor.id }, dic); } } return ResponseToClient<EmptyResponse>(ResponesStatus.Success, ""); } catch (Exception ex) { return ResponseToClient<EmptyResponse>(ResponesStatus.Exception, JsonConvert.SerializeObject(ex)); } } #endregion #region 获取节点的性能列表 /// <summary> /// 载入命令列表 /// </summary> /// <param name="req">载入命令列表请求类</param> /// <remarks>命令列表</remarks> /// <returns></returns> // [SignAuthorize] [ResponseType(typeof(ResponseBase<PageInfoResponse<LoadNodePerformancelistResponse>>))] [HttpPost, Route("loadnodeperformancelist")] public ResponseBase<PageInfoResponse<LoadNodePerformancelistResponse>> LoadNodePerformancelist(LoadNodePerformancelistRequest req) { try { int pageIndex = (req.iDisplayStart / req.iDisplayLength) + 1; int totalCount = 0; LoadNodePerformancelistResponse performanceDetail = new LoadNodePerformancelistResponse(); List<int> nodeidlist= noderep.Find(out totalCount, pageIndex, req.iDisplayLength, m => m.id.ToString(), x =>x.nodestatus ==(req.NodeRunStatus<=0?x.nodestatus:req.NodeRunStatus) &&x.id ==(req.NodeId <= 0?x.id:req.NodeId)).Select(k=>k.id).ToList(); nodeidlist.ForEach(m => { var performancelist = nodeperformanceRep.Find(x => m==x.nodeid && x.nodeid == (req.NodeId<=0?x.nodeid:req.NodeId)).OrderByDescending(x => x.lastupdatetime).Take(15).ToList().OrderBy(x => x.lastupdatetime).ToList(); performancelist.ForEach(x => { if (performanceDetail.NodePerfomance.ContainsKey(x.nodeid.ToString())) { performanceDetail.NodePerfomance[x.nodeid.ToString()].Add(x); } else { performanceDetail.NodePerfomance.Add(x.nodeid.ToString(), new List<tb_nodeperformance>() { x }); } }); }); return ResponseToClient<PageInfoResponse<LoadNodePerformancelistResponse>>(ResponesStatus.Success, "", new PageInfoResponse<LoadNodePerformancelistResponse>() { aaData = performanceDetail, iTotalDisplayRecords = totalCount, iTotalRecords = totalCount, sEcho = req.sEcho }); } catch (Exception ex) { return ResponseToClient<PageInfoResponse<LoadNodePerformancelistResponse>>(ResponesStatus.Exception, JsonConvert.SerializeObject(ex)); } } #endregion } }
using System; using System.Collections.Generic; namespace GradConnect.Models { public class Job { public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } public double Salary { get; set; } public string Location { get; set; } public string ContractType { get; set; } public string ContractedHours { get; set; } public DateTime? DatePosted { get; set; } //Naviagtional properties public IEnumerable<JobSkill> JobSkills { get; set; } public Job() { JobSkills = new List<JobSkill>(); } } }
using System; using System.Net.Http; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace ACNADailyPrayer { class Program { static void Main(string[] args) { /* ACNADailyPrayer.Service testService = new Service(Service.Office.EveningPrayer, "Monday January 1 1900"); Console.Write("Please enter a date in the format Weekday MonthName DD YYYY: "); string dateToTest = Console.ReadLine(); Console.Write("Please specify Morning or Evening Prayer with M or E: "); string serviceTypeIn = Console.ReadLine(); switch (serviceTypeIn) { case "M": testService = new Service(Service.Office.MorningPrayer, dateToTest); break; case "E": testService = new Service(Service.Office.EveningPrayer, dateToTest); break; default: System.Console.Clear(); Main(null); break; } //Console.Write(ACNADailyPrayer.Service.GetReading("Psalm 5")); Console.Write(string.Join("\n", testService.serviceText.ToArray()));*/ //Console.WriteLine(readBCP2019Psalms(150)); Console.Write("Enter year and I will give you the date of Easter: "); DateTime easterDateCalculated = Service.dateOfEaster(int.Parse(Console.ReadLine())); Console.WriteLine("\n Date is " + easterDateCalculated.ToString()); ; Console.WriteLine("\n"); Console.WriteLine("Press any key to continue..."); Console.Read(); } static string readBCP2019Psalms(int psalmNumber) { System.IO.StreamReader sReader = new System.IO.StreamReader("lectionary/2019bcppsalter"); string currentLine = ""; string psalmToReturn = ""; while (!sReader.EndOfStream) { // Find a Psalm (any line containing the word 'Psalm' exactly) currentLine = sReader.ReadLine(); // Stop and read the Psalm in if we hit the line we're looking for if (currentLine.Contains("Psalm" + " " + psalmNumber.ToString())) { psalmToReturn += currentLine += "\n" + "\n"; currentLine = sReader.ReadLine(); // Read up to the next line that we hit that contains 'Psalm' while (!currentLine.Contains("Psalm") && (!sReader.EndOfStream)) { psalmToReturn += currentLine + "\n"; currentLine = sReader.ReadLine(); } return psalmToReturn + "\n" + "\n"; } } return "Unable to read Psalm"; } } }
using Android.Content; using Barebone.Common; using Barebone.Common.Services.Interfaces; using Barebone.Droid.Services; using MvvmCross.Core.ViewModels; using MvvmCross.Droid.Platform; using MvvmCross.Droid.Views; using MvvmCross.Platform; using MvvmCross.Platform.Platform; using System.Collections.Generic; using System.Reflection; namespace Barebone.Droid { public class Setup : MvxAndroidSetup { public Setup(Context applicationContext) : base(applicationContext) { } protected override IMvxApplication CreateApp() => new App(); protected override IMvxTrace CreateDebugTrace() => new DebugTrace(); protected override IMvxAndroidViewPresenter CreateViewPresenter() { var mvxFragmentsPresenter = new DroidPresenter(AndroidViewAssemblies); Mvx.RegisterSingleton<IMvxAndroidViewPresenter>(mvxFragmentsPresenter); return mvxFragmentsPresenter; } protected override void InitializeIoC() { base.InitializeIoC(); Mvx.ConstructAndRegisterSingleton<IUserInteractionService, UserInteractionService>(); } protected override IEnumerable<Assembly> AndroidViewAssemblies => new List<Assembly>(base.AndroidViewAssemblies) { typeof(Android.Support.V4.Widget.DrawerLayout).Assembly, typeof(Android.Support.V7.Widget.RecyclerView).Assembly, typeof(Android.Support.Design.Widget.AppBarLayout).Assembly, typeof(FFImageLoading.Cross.MvxCachedImageView).Assembly }; protected override IEnumerable<string> ViewNamespaces => new List<string>(base.ViewNamespaces) { typeof(Android.Support.V4.Widget.DrawerLayout).Namespace.ToString(), typeof(Android.Support.V7.Widget.RecyclerView).Namespace.ToString(), typeof(Android.Support.Design.Widget.AppBarLayout).Namespace.ToString(), typeof(FFImageLoading.Cross.MvxCachedImageView).Namespace.ToString() }; } }
using System; using System.Net; using System.Text.RegularExpressions; using System.Diagnostics; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Management; using System.Net.NetworkInformation; namespace Media_Project_C_Sharp { public partial class Form1 : Form { Process start = new Process(); private string main_dir = ""; string curServer = "none"; public Form1() { InitializeComponent(); } private bool HDLS(ref string directory) {/*Pre: None *Post: String becomes HDLS directory location. * If not installed or dir does not exist the users is * prompted to locate/Install it. Directory then written to dir. */ Directory.SetCurrentDirectory(main_dir); if (System.IO.File.Exists("dir")) { directory = readFile("dir",main_dir); return true; } else { MessageBox.Show("HDLS update tool must first be installed or located."); OpenFileDialog fDialog = new OpenFileDialog(); fDialog.Title = "Open HdlsUpdateTool.exe"; fDialog.Filter = "EXE Files|*.exe"; fDialog.InitialDirectory = @"C:\Program Files\Valve\HLServer"; if (fDialog.ShowDialog() == DialogResult.OK) { directory = fDialog.FileName.ToString(); if (directory != "") writeFile(directory,"dir",main_dir); } else { File.Delete("dir"); OutputBox.Visible = true; OutputBox.Text = "Error Locating HDLS update tool" + "\r" + "\n" + OutputBox.Text; CloseOutputBox.Visible = true; } return false; } } private bool installServer(string install, string saveDir) { string installDir = ""; string dir = ""; string temp = ""; string verify = " -verify_all -retry"; if (HDLS(ref dir)) { temp = getDirectory(); if (temp == "") return false; writeFile(temp, saveDir, main_dir); installDir = "\"" + temp + "\""; writeFile("\""+dir+"\""+install+"\""+temp+ "\"" + verify, "install.bat", main_dir); Process run = new Process(); run.StartInfo.FileName = "install.bat"; run.Start(); //run.WaitForExit(); File.Delete(main_dir + "install.bat"); return true; } else return false; } private void writeFile(string data, string filename, string location) { if (System.IO.File.Exists(location + "/" + filename)) File.Delete(location + "/" + filename); TextWriter tw = new StreamWriter(location + "/" + filename); tw.WriteLine(data); tw.Close(); tw.Dispose(); } private string readFile(string filename, string location) { string dir = ""; if(System.IO.File.Exists(location + "/" + filename)) { TextReader tw = new StreamReader(location + "/" + filename); dir = tw.ReadLine(); tw.Close(); tw.Dispose(); return dir; } return null; } private string MyText { get { return this.OutputBox.Text; } set { this.OutputBox.Text = value + "\r" + "\n" + this.OutputBox.Text; } } private void loadSettings() { string temp = ""; Directory.SetCurrentDirectory(main_dir); if (System.IO.File.Exists(main_dir + "/custom_settings")) { TextReader settings = new StreamReader(main_dir + "/custom_settings"); temp = settings.ReadLine(); if (temp != null) { Bitmap bit = new Bitmap(temp); this.BackgroundImage = bit; } settings.Close(); } } private void saveSettings(string str) { Directory.SetCurrentDirectory(main_dir); File.Delete(main_dir + "/images/custom_settings"); TextWriter settings = new StreamWriter(main_dir + "/custom_settings"); settings.WriteLine(str); settings.Close(); settings.Dispose(); } private string getDirectory() { string directory = ""; folderBrowserDialog1.ShowDialog(); directory = folderBrowserDialog1.SelectedPath; return directory; } private void viewServer(bool viewBool) { Cfg.Items.Clear(); statusBar.Text = ""; start_stop.Visible = viewBool; cfgButton.Visible = viewBool; commandBox.Visible = viewBool; enter.Visible = viewBool; Cfg.Visible = false; } private void Form1_Load(object sender, EventArgs e) { main_dir = Path.GetDirectoryName(Application.ExecutablePath); loadSettings(); //getProcess(); } private void installServerToolStripMenuItem_Click(object sender, EventArgs e) { } private void teamFortress2ToolStripMenuItem_Click(object sender, EventArgs e) { } private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } private void team4TressToolStripMenuItem_Click(object sender, EventArgs e) { Bitmap bit = (Bitmap)Image.FromFile(main_dir + "/Images/team_4tress.jpg"); this.BackgroundImage = bit; saveSettings(main_dir + "/Images/team_4tress.jpg"); } private void tf2CakeToolStripMenuItem1_Click(object sender, EventArgs e) { Bitmap bit = (Bitmap)Image.FromFile(main_dir + "/Images/tf2cake.jpg"); this.BackgroundImage = bit; saveSettings(main_dir + "/Images/tf2cake.jpg"); } private void portalCakeToolStripMenuItem_Click(object sender, EventArgs e) { Bitmap bit = (Bitmap)Image.FromFile(main_dir + "/Images/portalcake.jpg"); this.BackgroundImage = bit; saveSettings(main_dir + "/Images/portalcake.jpg"); } private void spyPyroToolStripMenuItem_Click(object sender, EventArgs e) { Bitmap bit = (Bitmap)Image.FromFile(main_dir + "/Images/spyro.jpg"); this.BackgroundImage = bit; saveSettings(main_dir + "/Images/spyro.jpg"); } private void hLDSEToolStripMenuItem_Click(object sender, EventArgs e) { Directory.SetCurrentDirectory(main_dir); Process hldsHelpFile = new Process(); hldsHelpFile.StartInfo.FileName = "notepad.exe"; hldsHelpFile.StartInfo.Arguments = main_dir + "/help files/hlds_error"; hldsHelpFile.Start(); } private void exitToolStripMenuItem1_Click(object sender, EventArgs e) { Close(); } private void updateServerToolStripMenuItem1_Click(object sender, EventArgs e) { } private void installServerToolStripMenuItem1_Click(object sender, EventArgs e) { } private void hLDSUpdateToolToolStripMenuItem_Click(object sender, EventArgs e) { string dir = ""; Process hdls = new Process(); hdls.StartInfo.FileName = main_dir + "/Tools/hldsupdatetool.exe"; hdls.Start(); hdls.WaitForExit(); if (HDLS(ref dir)) MessageBox.Show("HDLS location is updated"); } private void left4DeadToolStripMenuItem2_Click(object sender, EventArgs e) { if (!(installServer(" -command update -game l4d_full -dir ", "l4d_dir"))) { OutputBox.Visible = true; OutputBox.Text = "Error installing Left 4 Dead" + "\r" + "\n" + OutputBox.Text; CloseOutputBox.Visible = true; } } static void show() { } private void teamFortress2ToolStripMenuItem2_Click(object sender, EventArgs e) { if (!(installServer(" -command update -game tf -dir ", "tf2_dir"))) { OutputBox.Visible = true; OutputBox.Text = "Error installing Team Fortress 2" + "\r" + "\n" + OutputBox.Text; CloseOutputBox.Visible = true; } } private void OutputBox_TextChanged(object sender, EventArgs e) { } private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e) { } private void outputBoxToolStripMenuItem_Click(object sender, EventArgs e) { if (OutputBox.Visible) OutputBox.Visible = false; else OutputBox.Visible = true; } private void notepadToolStripMenuItem_Click(object sender, EventArgs e) { Process notepad = new Process(); notepad.StartInfo.FileName = "notepad.exe"; notepad.Start(); } /// <summary> /// Install Servers w/out command prompt. Current issue = 5 second time out/crash. /// </summary> /// <param name="install">install command must be passed.</param> /// <returns>true upon success, needs to evaluate integraty. False upon failure</returns> private bool InstallServer(string install) { string installDir = ""; string dir = ""; string output = ""; string temp = ""; if (HDLS(ref dir)) { temp = getDirectory(); if (temp == "") return false; installDir = "\"" + temp + "\""; dir = "\"" + dir + "\""; System.Diagnostics.ProcessStartInfo Install = new System.Diagnostics.ProcessStartInfo("cmd.exe"); Install.RedirectStandardInput = true; Install.RedirectStandardOutput = true; Install.RedirectStandardError = true; Install.UseShellExecute = false; //Install.CreateNoWindow = true; Install.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; System.Diagnostics.Process console = System.Diagnostics.Process.Start(Install); OutputBox.Visible = true; console.StandardInput.WriteLine(@dir + install + installDir); OutputBox.Refresh(); // re-paint a form do { output = console.StandardOutput.ReadLine(); MyText = output; OutputBox.Refresh(); // re-paint a form } while (output != null); //console.StandardInput.WriteLine("/c"); console.WaitForExit(); //wait for exit OutputBox.Visible = false; return true; } else return false; } private void customToolStripMenuItem_Click(object sender, EventArgs e) { string source = ""; string fileName = ""; string destination = ""; OpenFileDialog bgrdDialog = new OpenFileDialog(); bgrdDialog.Title = "Open Custom Background"; bgrdDialog.InitialDirectory = @"C:\"; if (bgrdDialog.ShowDialog() == DialogResult.OK) { source = bgrdDialog.FileName.ToString(); fileName = System.IO.Path.GetFileName(source); destination = main_dir + "/Images/" + fileName; File.Delete(destination); File.Copy(source, destination, true); bgrdDialog.Dispose(); Bitmap bit = (Bitmap)Image.FromFile(destination); this.BackgroundImage = bit; saveSettings(destination); } else MessageBox.Show("No file selected / does not exist"); } private void Cfg_SelectedIndexChanged(object sender, EventArgs e) { } public void OnDoubleClick(object sender, MouseEventArgs e) { string Value= ""; Value = Cfg.Items[Cfg.SelectedIndex].ToString(); CfgSelExe(Value); } private void startServerToolStripMenuItem_Click(object sender, EventArgs e) { } private void CfgSelExe(string value) { switch (value) { case "Admin Password": break; case "All Talk": break; case "Download Settings": break; case "Party Mode": break; case "Player Management": break; case "Round/Game Timbers": break; case "Security": break; case "Team Balancing": break; } } private void teamFortress2ToolStripMenuItem3_Click_1(object sender, EventArgs e) { //Start tf2 Server if (readFile("tf2_dir", main_dir) != null) { viewServer(true); //curServer = ServerType.tf2; curServer = "tf2"; statusBar.Text = "Team Fortress 2"; //Add Items To Listbox "Cfg" Cfg.Items.Add("Admin Password"); Cfg.Items.Add("All Talk"); Cfg.Items.Add("Download Settings"); Cfg.Items.Add("Party Mode"); Cfg.Items.Add("Player Management"); Cfg.Items.Add("Round/Game Timers"); Cfg.Items.Add("Security"); Cfg.Items.Add("Team Balancing"); //Add Items to Combobox "commandBox" commandBox.Items.Add("Start"); } else { OutputBox.Visible = true; CloseOutputBox.Visible = true; OutputBox.Text = "You must first install the Team Fortress 2 Server"; } } private void start_stop_Click(object sender, EventArgs e) { } private void left4DeadToolStripMenuItem3_Click(object sender, EventArgs e) { //Start l4d Server if (readFile("l4d_dir", main_dir) != null) { viewServer(true); statusBar.Text = "Left 4 Dead"; } else { OutputBox.Visible = true; CloseOutputBox.Visible = true; OutputBox.Text = "You must first install the Left 4 Dead Server"; } } private void cfgButton_Click(object sender, EventArgs e) { if (Cfg.Visible) Cfg.Visible = false; else Cfg.Visible = true; } private void start_stop_Click_1(object sender, EventArgs e) { string data =""; string map = ""; string maxPlayers = ""; string argu = ""; Process tf2 = new Process(); Process l4d = new Process(); bool tf2Running = false; bool l4dRunning = false; if (start_stop.Text == "Start") { data = "\"" + readFile(curServer + "_dir", main_dir + "/"); switch (curServer) { //orangebox\srcds.exe -console -game tf +map ctf_2fort +maxplayers 24 case "tf2": data += "/orangebox/srcds.exe\""; argu = " -console -game tf +map " + map + " +maxplayers " + maxPlayers; map = "ctf_2fort"; maxPlayers = "24"; //Process tf2 = new Process(); tf2.StartInfo.FileName = data; tf2.StartInfo.Arguments = argu; tf2.StartInfo.UseShellExecute = false; tf2.Start(); break; case "l4d": data += "/l4d/srcds.exe\" -console -game l4d +map "; data += map + " +maxplayers " + maxPlayers; //Process l4d = new Process(); l4d.StartInfo.FileName = data; l4d.StartInfo.Arguments = argu; l4d.StartInfo.UseShellExecute = false; l4d.Start(); l4dRunning = true; break; } //start.StartInfo.RedirectStandardInput = true; //start.OutputDataReceived //start.StartInfo.RedirectStandardOutput = true; //start.StartInfo.RedirectStandardError = true; //Process temp = new Process(); //start here //temp.StartInfo = start.StartInfo; //temp.Start(); //temp.StandardInput.AutoFlush = true ; /* writeFile(data, curServer + "_start.bat", main_dir); Process start = new Process(); start.StartInfo.FileName = main_dir + "/" + curServer + "_start.bat"; start.Start(); start.Close(); start.Dispose(); */ start_stop.Text = "Stop"; } else { switch(curServer) { case "tf2": if (tf2Running) { tf2.Kill(); tf2Running = false; } break; case "l4d": if (l4dRunning) { l4d.Kill(); l4dRunning = false; } break; } start_stop.Text = "Start"; } } private void noneToolStripMenuItem_Click(object sender, EventArgs e) { viewServer(false); OutputBox.Visible = false; CloseOutputBox.Visible = false; } private void commandBox_SelectedIndexChanged(object sender, EventArgs e) { } private void Enter_Click(object sender, EventArgs e) { string command = ""; Object selectedItem = new Object(); selectedItem = commandBox.SelectedItem; if ((selectedItem != null) && (start_stop.Text != "Start")) { command = selectedItem.ToString(); Process.EnterDebugMode(); start.BeginOutputReadLine(); start.StandardInput.WriteLine(@command); //commandBox.GetItemText(command); //MessageBox.Show(command); } } private void OnEnter(object sender, EventArgs e) { //Enter_Click(sender,e); } private void CloseOutputBox_Click(object sender, EventArgs e) { CloseOutputBox.Visible = false; OutputBox.Visible = false; OutputBox.Text = ""; } private void commandPromptToolStripMenuItem_Click(object sender, EventArgs e) { Process cmd = new Process(); cmd.StartInfo.FileName = "cmd.exe"; cmd.Start(); } private string getExternalIp() { try { string whatIsMyIp = "http://www.whatismyip.com/automation/n09230945.asp"; WebClient wc = new WebClient(); UTF8Encoding utf8 = new UTF8Encoding(); string requestHtml = ""; requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp)); IPAddress externalIp = null; externalIp = IPAddress.Parse(requestHtml); return externalIp.ToString(); } catch { return ""; } } private string getLocalIp() { string strHostName = Dns.GetHostName(); IPHostEntry ipEntry = Dns.GetHostEntry(strHostName); IPAddress[] addr = ipEntry.AddressList; return addr[0].ToString(); //Console.WriteLine(addr[0]); //Console.ReadKey(); } private string getGatewayIp() { string _GatewayID = string.Empty; NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in adapters) { IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); GatewayIPAddressInformationCollection addresses = adapterProperties.GatewayAddresses; if (addresses.Count > 0) { foreach (GatewayIPAddressInformation address in addresses) { if (string.IsNullOrEmpty(_GatewayID)) _GatewayID += address.Address.ToString(); else _GatewayID += address.Address.ToString() + "\r\n"; } } } return _GatewayID; } private void iPAddressToolStripMenuItem_Click(object sender, EventArgs e) { OutputBox.Visible = true; CloseOutputBox.Visible = true; OutputBox.Text = "External IP: " + getExternalIp() + "\r" + "\n"; OutputBox.Text += "IP Address: " + getLocalIp() + "\r" + "\n"; OutputBox.Text += "Default Gateway: "+ getGatewayIp() + "\r" + "\n"; } private void statusBarToolStripMenuItem_Click(object sender, EventArgs e) { if (statusStrip1.Visible == true) statusStrip1.Visible = false; else statusStrip1.Visible = true; } private void statusStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { } private void getProcess() { Process[] processlist = Process.GetProcesses(); foreach (Process theprocess in processlist) { //string output = ""; if (theprocess.ProcessName == "srcds") start_stop.Text = "Stop"; //MessageBox.Show("Hmm"); if (theprocess.ProcessName == "cmd") { } //output = theprocess.ReadLine(); //MessageBox.Show(output); OutputBox.Visible = true; OutputBox.Text += "Process: {0} ID: {1} " + theprocess.ProcessName + theprocess.Id; OutputBox.Text += "\r" + "\n"; //Console.WriteLine("Process: {0} ID: {1}", theprocess.ProcessName, theprocess.Id); } } } }
using System; using System.Data.Common; using System.Linq; using DataAccessLayer.EfStructures.Context; using DataAccessLayer.EfStructures.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Storage; using Xunit; namespace DataAccessLayerTests.C_PersistChanges.B_Transactions { public class TransactionTests : IDisposable { private readonly AdventureWorksContext _context; public TransactionTests() { _context = new AdventureWorksContext(); } public void Dispose() { _context.Dispose(); } [Fact] public void ShouldRollbackFailedImplicitTransaction() { var count = _context.Product.Count(); var product1 = TestHelpers.CreateProduct("1"); _context.Product.Add(product1); //this one should fail as it is not a complete product var product2 = new Product { ProductId = 2 }; _context.Product.Add(product2); try { _context.SaveChanges(); } catch (Exception ex) { //todo IRL handle exception properly Console.WriteLine(ex); } Assert.Equal(count, _context.Product.Count()); } [Fact] public void ShouldExecuteInAnExplictTransaction() { using (var transaction = _context.Database.BeginTransaction()) { var count = _context.Product.Count(); var product1 = TestHelpers.CreateProduct("1"); _context.Product.Add(product1); var product2 = TestHelpers.CreateProduct("2"); _context.Product.Add(product2); try { _context.SaveChanges(); //You would normally do your commit like this, but not for test //transaction.Commit(); } catch (Exception ex) { //todo IRL handle exception properly Console.WriteLine(ex); //Normally you would do your rollback here, but not for test //transaction.Rollback(); } //rollback for the test Assert.Equal(count + 2, _context.Product.Count()); transaction.Rollback(); Assert.Equal(count, _context.Product.Count()); } } [Fact] public void ShouldExecuteInATransactionAcrossMultipleContexts() { using (var transaction = _context.Database.BeginTransaction()) { var count = _context.Product.Count(); var product = TestHelpers.CreateProduct("1"); _context.Product.Add(product); using(var context2 = CreateContext( _context.Database.GetDbConnection())) { context2.Database.UseTransaction(transaction.GetDbTransaction()); var product2 = TestHelpers.CreateProduct("2"); _context.Product.Add(product2); context2.SaveChanges(); //This should have added one but it is not - EF 2.1 change??? //Assert.Equal(count + 1, context2.Product.Count()); Assert.Equal(count, context2.Product.Count()); } _context.SaveChanges(); Assert.Equal(count + 2, _context.Product.Count()); //this will rollback for both contexts transaction.Rollback(); Assert.Equal(count, _context.Product.Count()); } } internal AdventureWorksContext CreateContext(DbConnection connection) { var optionsBuilder = new DbContextOptionsBuilder<AdventureWorksContext>(); optionsBuilder //.UseLoggerFactory(AdventureWorksContext.AppLoggerFactory) .UseSqlServer(connection) .ConfigureWarnings(warnings => { warnings.Throw(RelationalEventId.QueryClientEvaluationWarning); }); return new AdventureWorksContext(optionsBuilder.Options); } } }
using System.Collections.Generic; using NFluent; using NSubstitute; using NUnit.Framework; namespace BootcampTwitterKata.Tests { public class Part_7_Query { private ITwitterQuery twitterQuery; private IBus bus; private CountProjection countProjection; private LikeCountProjection likeCountProjection; private ListProjection listProjection; [SetUp] public void Setup() { var injecter = new Injecter(); bus = Substitute.For<IBus>(); countProjection = new CountProjection { Count = 2 }; likeCountProjection = new LikeCountProjection { Count = 1 }; listProjection = new ListProjection { Tweets = new List<Tweet>{ new Tweet { Title = "Tweet 1" } , new Tweet { Title = "Tweet 2" } } }; injecter .Bind<CountProjection>(countProjection) .Bind<LikeCountProjection>(likeCountProjection) .Bind<ListProjection>(listProjection) .Bind<IBus>(bus) .Bind<ITwitterQuery, TwitterQuery>(); this.twitterQuery = injecter.Get<ITwitterQuery>(); } [Test] public void Should_projection_tweets_count_When_query_counts() { var count = this.twitterQuery.CountAll(); Check.That(count).IsEqualTo(2); } [Test] public void Should_projection_tweets_like_count_When_query_like_counts() { var count = this.twitterQuery.CountLike(); Check.That(count).IsEqualTo(1); } [Test] public void Should_projection_all_tweets_When_query_all_tweets() { var count = this.twitterQuery.GetAll(); Check.That(count.Extracting("Title")).ContainsExactly("Tweet 1", "Tweet 2"); } [Test] public void Should_subscribe_to_count_projection_receiver_When_create_twitter_query() { this.bus.Received(1).Subcribe(this.countProjection.Received); } [Test] public void Should_subscribe_to_count_like_projection_receiver_When_create_twitter_query() { this.bus.Received(1).Subcribe(this.likeCountProjection.Received); } [Test] public void Should_subscribe_to_list_projection_receiver_When_create_twitter_query() { this.bus.Received(1).Subcribe(this.listProjection.Received); } } }
namespace pleasework.Enums { public enum Role { admin, manager, developer, tester, designer } public enum Priority { low, medium, high, criticaaal } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace ObservableTune { public static class Utils { public static Chronometre CreateCronometer() { return new Chronometre(); } } public class Chronometre { public Chronometre() { _sw = new Stopwatch(); _sw.Start(); } private Stopwatch _sw; public string TimeToString() { return _sw.ElapsedMilliseconds.ToString(); } } }
using EAN.GPD.Domain.Entities; using EAN.GPD.Domain.Models; using EAN.GPD.Domain.Repositories; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace EAN.GPD.Server.Controllers.V1 { [Route("v1/indicador")] public class IndicadorController : BaseController<IndicadorModel, IndicadorEntity> { public IndicadorController(IHttpContextAccessor accessor, IIndicadorRepository indicadorRepository) : base(accessor, indicadorRepository) { } } }
using Xunit; using Pobs.Domain.Utils; namespace Pobs.Tests.Unit { public class UnixTimeTests { [Fact] public void HandlesNull() { Assert.Null((null as long?).ToUnixDateTime()); } [Fact] public void ConvertsMillisecondsCorrectly() { long? value = 1541500846000; Assert.Equal("2018-11-06T10:40:46.0000000", value.ToUnixDateTime().Value.ToString("o")); } } }
namespace MatchFullName { using System; using System.Text.RegularExpressions; public class StartUp { public static void Main() { var names = Console.ReadLine(); var pattern = @"\b[A-Z][a-z]+ [A-Z][a-z]+\b"; var validNames = Regex.Matches(names, pattern); foreach (Match name in validNames) { Console.Write($"{name.Value} "); } Console.WriteLine(); } } }
using System; using Microsoft.AspNetCore.Identity; namespace FR.IdentityServer.Models { public class ApplicationUser : IdentityUser { public string Name { get; set; } public string CompanyName { get; set; } public string PictureUrl { get; set; } } }
using gView.Core.Framework.Exceptions; using gView.Framework.system; using gView.Framework.Carto; using gView.Framework.IO; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Collections.Concurrent; namespace gView.MapServer { public class ServiceRequestContext : IServiceRequestContext { private IMapServer _mapServer = null; private IServiceRequestInterpreter _interpreter = null; private ServiceRequest _request = null; private ServiceRequestContext(IMapServer mapServer, IServiceRequestInterpreter interpreter, ServiceRequest request) { _mapServer = mapServer; _interpreter = interpreter; _request = request; if (ContextVariables.UseMetrics) { this.Metrics = new ConcurrentDictionary<string, double>(); } } async static public Task<IServiceRequestContext> TryCreate(IMapServer mapServer, IServiceRequestInterpreter interpreter, ServiceRequest request, bool checkSecurity = true) { var context = new ServiceRequestContext(mapServer, interpreter, request); if (checkSecurity == true) { var mapService = mapServer?.GetMapService(request?.Service, request?.Folder); if (mapService == null) { throw new MapServerException("Unknown service"); } await mapService.CheckAccess(context); } return context; } #region IServiceRequestContext Member public IMapServer MapServer { get { return _mapServer; } } public IServiceRequestInterpreter ServiceRequestInterpreter { get { return _interpreter; } } public ServiceRequest ServiceRequest { get { return _request; } } public IDictionary<string, double> Metrics { get; } async public Task<IServiceMap> CreateServiceMapInstance() { var serviceMap = await _mapServer?.GetServiceMapAsync(this); if (serviceMap == null) { throw new MapServerException($"Unable to load service {_request.Folder}/{_request.Service}: Check error log for details"); } return serviceMap; } async public Task<IMetadataProvider> GetMetadtaProviderAsync(Guid metadataProviderId) { return await _mapServer?.GetMetadtaProviderAsync(this, metadataProviderId); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IRAPShared; namespace IRAP.Entity.FVS { public class AndonRspEventInfo : AndonEventInfo { /// <summary> /// 安灯事件隶属关系: /// 0-通知了别人,但我可响应; /// 1-通知我的,还未响应; /// 2-别人已响应,但追加呼叫我的 /// </summary> public int AndonEventOwnership { get; set; } [IRAPORMMap(ORMMap = false)] public bool Choice { get; set; } public new AndonRspEventInfo Clone() { AndonRspEventInfo rlt = MemberwiseClone() as AndonRspEventInfo; return rlt; } public override string ToString() { return EventDescription; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Day2CSharpAssignment { class AreaMainClass { static void Main() { Area area = new Area(); area.CalculateArea(6.1f); area.CalculateArea(10, 22); area.CalculateArea(5.1); Console.ReadKey(); } } }
using Reactive.Flowable.Subscriber; using System.Collections.Generic; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; namespace Reactive.Flowable { public abstract class SubscriptionBase<T> : ISubscription { private readonly CancellationTokenSource cancelSource; private readonly ISubscriber<T> subscriber; private IEnumerable<Task> readerTasks; private ChannelWriter<T> writer; private Task writerTask; private int demand = 0; protected SubscriptionBase(ISubscriber<T> subscriber, BoundedChannelOptions options) { cancelSource = new CancellationTokenSource(); demand = options.Capacity; Channel<T> channel = Channel.CreateBounded<T>(options); writer = channel.Writer; readerTasks = channel.Subscribe(x => subscriber.OnNext(x), cancelSource.Token, options.Capacity); writerTask = Task.Factory.StartNew(ProcessRequestAsync); Request(options.Capacity); this.subscriber = subscriber; } public void Cancel() { cancelSource.Cancel(); writer.Complete(); subscriber.OnComplete(); } public void Request(int n) { Interlocked.Add(ref demand, n); } protected virtual async Task ProcessRequestAsync() { while (true) { int n = Interlocked.Exchange(ref demand, 0); for (int i = 0; i < n; i++) { if (AdvanceRead()) { await writer.WriteAsync(GetCurrent()); } else { Cancel(); return; } } } } protected abstract bool AdvanceRead(); protected abstract T GetCurrent(); #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { cancelSource.Cancel(); Task.WhenAll(readerTasks).Wait(); } disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { Dispose(true); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WhatNEXT { class TaskTextParser: ITaskParser { private string[] timeSeparatorKeyWords = {"before", "after", "at"}; private TaskItem taskItem = new TaskItem(); //after 20 mins //before --- public TaskItem Parse(string taskDetails) { taskItem.ID = DateTime.Now.ToFileTimeUtc(); int indexTaskSplitter = taskDetails.IndexOf("after"); if(indexTaskSplitter != -1) { taskItem.Details = taskDetails.Substring(0, indexTaskSplitter).Trim(); taskItem.TimeReminder = Convert.ToInt32(taskDetails.Substring(indexTaskSplitter + "after".Length).Trim().TrimEnd('s'))*1000; } return taskItem; } } }
using FrbaOfertas.Model; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace FrbaOfertas.Helpers { public static class SqlHelper { public static String getColumns(List<String> list){ String returned = ""; foreach (String value in list) { returned += "[" + value + "],"; } return returned.Remove(returned.Length - 1); } public static String getLikeFilter(Dictionary<String,String> filtros) { if (filtros.Count() == 0) return ""; String returned = " "; foreach (KeyValuePair<string, string> value in filtros) { returned += "[" + value.Key + "] LIKE ('%"+value.Value+"%') AND"; } return returned.Remove(returned.Length - 3); } public static String getExactFilter(Dictionary<String, Object> filtros) { if (filtros.Count() == 0) return ""; String returned = " "; foreach (KeyValuePair<string, Object> value in filtros) { returned += "[" + value.Key + "]=@" + value.Key + ","; } return returned.Remove(returned.Length - 1); } public static String getValues(List<String> list) { String returned = ""; foreach (String value in list) { returned += "@" + value + ","; } return returned.Remove(returned.Length - 1); } public static String getUpdate(List<String> list) { String returned = ""; foreach (String value in list) { if (value != "usu_contrasenia") returned += "[" + value + "]=@" + value + ","; else returned += "[" + value + "]=HASHBYTES('SHA2_256',@" + value + "),"; } return returned.Remove(returned.Length - 1); } public static List<String> getValuesList(List<String> list) { List<String> returned = new List<string>(); foreach (String value in list) { returned.Add("@" + value); } return returned; } public static object setearAtributos(SqlDataReader reader, List<String> atributes, object objeto) { foreach (String atribute in atributes) { try { if (!reader.IsDBNull(reader.GetOrdinal(atribute))) { var param = objeto.GetType().GetProperty(atribute); if (param.PropertyType == typeof(String)) param.SetValue(objeto, (String)reader.GetValue(reader.GetOrdinal(atribute))); else if (param.PropertyType == typeof(Int32)) { try { param.SetValue(objeto, reader.GetInt32(reader.GetOrdinal(atribute))); } catch { param.SetValue(objeto, (Int32)reader.GetDecimal(reader.GetOrdinal(atribute))); } } else if (param.PropertyType == typeof(Int32?)) param.SetValue(objeto, (Int32?)reader.GetValue(reader.GetOrdinal(atribute))); else if (param.PropertyType == typeof(DateTime)) param.SetValue(objeto, reader.GetDateTime(reader.GetOrdinal(atribute))); else if (objeto.GetType().GetProperty(atribute).PropertyType == typeof(Double)) param.SetValue(objeto, (Double)reader.GetDecimal(reader.GetOrdinal(atribute))); else if (objeto.GetType().GetProperty(atribute).PropertyType == typeof(Boolean)) param.SetValue(objeto, (Boolean)reader.GetValue(reader.GetOrdinal(atribute))); } } catch { } } return objeto; } public static string CalculateMD5Hash(string input) { // step 1, calculate MD5 hash from input MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input); byte[] hash = md5.ComputeHash(inputBytes); // step 2, convert byte array to hex string StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HW1.DAL; using Npgsql; namespace HW1.Models { class User { public String id { get; set; } public String userName { get; set; } public DateTime dataJoined { get; set; } public double latitude { get; set; } public double longitude { get; set; } public int reviewCount { get; set; } public int fans { get; set; } public double average_stars { get; set; } public int funny { get; set; } public int useful { get; set; } public int cool { get; set; } } }
using FluentValidation; using Galeri.Entities.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Galeri.Business.ValidationTool { public class FotografValidator:AbstractValidator<Fotograf> { public FotografValidator() { RuleFor(c => c.FotografAdi).NotNull().WithMessage("Fotograf adı boş geçilemez."); RuleFor(c => c.TasitId).NotNull().WithMessage("Fotoğrafın ait olduğu taşıt alanı(plaka) boş geçilemez."); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestEvent1 : BaseScriptedEvent { public GameObject enemy; public AudioClip voice; public void BattleTest() { //GameManager.instance.activeQuests.Add(GetQuest(1)); /*AddItem(0, 2); AddItem(1, 5); AddItem(2); //key item AddEquipment(0); AddEquipment(1); AddEquipment(2); AddEquipment(3); AddEquipment(4); AddEquipment(5); AddEquipment(6); AddEquipment(7); StartCoroutine(ShowMessage("Here you go dude!", voice, true, true));*/ CallBattle(0, "Battle Test"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Query.DTO { /// <summary> /// 货架信息,用来组织 货架树 /// </summary> public class ShelfInfoDto { // 货架 public int Id { get; set; } public int StoreId { get; set; } public string Code { get; set; } public int Number { get; set; } public string Name { get; set; } // 货架层 /// <summary> /// 层Id /// </summary> public int LayerId { get; set; } public int ShelfId { get; set; } public int ShelfLayerNumber { get; set; } /// <summary> /// 货架码 /// </summary> public string ShelfLayerCode { get; set; } //货架商品 /// <summary> /// 货架商品Id /// </summary> public int ShelfLayerProductId { get; set; } public int ShelfLayerId { get; set; } public string ShelfLayerProductCode { get; set; } public int ShelfLayerProductNumber { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ChatBot.Domain.Configuration { public static class QnaMakerServiceConfiguration { public const string QnaKey = "FrequentlyAskedQuestions"; } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using WxShop.Model.Base; namespace WxShop.Model { /// <summary> /// 商品类型 /// </summary> [Table("ws_ProductType")] public class ProductTypeModel : EntityBase { /// <summary> /// 商品类型名称 /// </summary> [StringLength(maximumLength: 10, ErrorMessage = "商品类型名称不能超过10个字符")] public string Name { get; set; } /// <summary> /// 父类型ID /// </summary> public int ParentID { get; set; } } }
namespace Krafteq.ElsterModel { using System.Collections.Generic; using LanguageExt; using static LanguageExt.Prelude; public class KzFieldsFormBuilder { readonly List<KzFieldMeta> fields = new List<KzFieldMeta>(); readonly List<KzFieldValidationRules> validationRules = new List<KzFieldValidationRules>(); public KzFieldsForm Build() { return new KzFieldsForm(toList(this.fields), toList(this.validationRules)); } protected void F(int number, KzFieldType type, string description) { this.fields.Add(new KzFieldMeta(number, type, description)); } protected void ValidationRules(int number, params KzFieldValidationRule[] rules) { this.validationRules.Add(new KzFieldValidationRules(number, toList(rules))); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; using System.Web.Mvc; namespace WhereToEatApp.Controllers { public class HomeController : Controller { // // GET: /Home/ // [OutputCache(Duration = 864000, VaryByParam = "none")] public ActionResult Index() { Uri uri = new Uri("http://www.dianping.com/search/category/1/10"); HttpWebRequest http_request = (HttpWebRequest)WebRequest.Create(uri); http_request.Method = "GET"; http_request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0"; HttpWebResponse http_response = (HttpWebResponse)http_request.GetResponse(); string html = new StreamReader(http_response.GetResponseStream(), Encoding.UTF8).ReadToEnd(); HtmlAgilityPack.HtmlDocument html_doc = new HtmlAgilityPack.HtmlDocument(); html_doc.LoadHtml(html); HtmlAgilityPack.HtmlNodeCollection classfy_nodes = html_doc.DocumentNode.SelectNodes("//html/body//div[@id='classfy']/a"); HtmlAgilityPack.HtmlNodeCollection region_nodes = html_doc.DocumentNode.SelectNodes("//html/body//div[@id='region-nav']/a"); ViewBag.Classes = new Dictionary<int, string>(); ViewBag.Regions = new Dictionary<int, string>(); foreach (var item in classfy_nodes) { string url = item.Attributes["href"].Value; string num = url.Substring(23); int key = Int32.Parse(num); string value = item.InnerText; ViewBag.Classes.Add(key, value); } foreach (var item in region_nodes) { string url = item.Attributes["href"].Value; string[] split = url.Split('#'); string num = split[0].Substring(23); int key = Int32.Parse(num); string value = item.InnerText; ViewBag.Regions.Add(key, value); } return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DocGen.ObjectModel; using Word = DocumentFormat.OpenXml.Wordprocessing; using DocumentFormat.OpenXml; namespace DocGen.OOXML { /// <summary> /// Responsible for converting a given MultiColumnSection object to formatted OpenXML objects. /// </summary> public class MultiColumnSectionFormatter { public static DocumentFormat.OpenXml.OpenXmlElement[] GetFormattedSection(MultiColumnSection section) { List<DocumentFormat.OpenXml.OpenXmlElement> formattedSection = new List<DocumentFormat.OpenXml.OpenXmlElement>(); Element[] elements = section.SubElements; foreach (var element in elements) { formattedSection.AddRange(ElementFactory.GetElement(element)); } Word.Columns cols = new Word.Columns() { ColumnCount = (Int16Value)section.NumberOfColumns }; Word.SectionProperties secProps = new Word.SectionProperties(cols); Word.ParagraphProperties paraProp = new Word.ParagraphProperties(secProps); Word.Paragraph para = new Word.Paragraph(paraProp); formattedSection.Add(para); return formattedSection.ToArray(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Tomelt.ContentManagement; using Tomelt.ContentManagement.Drivers; using Tomelt.ContentManagement.Handlers; using Tomelt.EasyUIFields.Fields; using Tomelt.EasyUIFields.Settings; using Tomelt.Localization; namespace Tomelt.EasyUIFields.Drivers { public class TextBoxFieldDriver: ContentFieldDriver<TextBoxField> { public ITomeltServices Services { get; set; } public TextBoxFieldDriver(ITomeltServices services) { Services = services; T = NullLocalizer.Instance; } public Localizer T { get; set; } /// <summary> /// 获取前缀 /// </summary> /// <param name="field"></param> /// <param name="part"></param> /// <returns></returns> private static string GetPrefix(ContentField field, ContentPart part) { return part.PartDefinition.Name + "." + field.Name; } private static string GetDifferentiator(TextBoxField field, ContentPart part) { return field.Name; } //显示 protected override DriverResult Display(ContentPart part, TextBoxField field, string displayType, dynamic shapeHelper) { return ContentShape("Fields_TextBox", GetDifferentiator(field, part), () => { var settings = field.PartFieldDefinition.Settings.GetModel<TextBoxFieldSettings>(); return shapeHelper.Fields_TextBox().Settings(settings); }); } protected override DriverResult Editor(ContentPart part, TextBoxField field, dynamic shapeHelper) { return ContentShape("Fields_TextBox_Edit", GetDifferentiator(field, part), () => { if (part.IsNew() && String.IsNullOrEmpty(field.Value)) { var settings = field.PartFieldDefinition.Settings.GetModel<TextBoxFieldSettings>(); field.Value = settings.DefaultValue; } return shapeHelper.EditorTemplate(TemplateName: "Fields/TextBox.Edit", Model: field, Prefix: GetPrefix(field, part)); }); } protected override DriverResult Editor(ContentPart part, TextBoxField field, IUpdateModel updater, dynamic shapeHelper) { if (updater.TryUpdateModel(field, GetPrefix(field, part), null, null)) { var settings = field.PartFieldDefinition.Settings.GetModel<TextBoxFieldSettings>(); if (settings.Required && String.IsNullOrWhiteSpace(field.Value)) { updater.AddModelError(GetPrefix(field, part), T("{0} 此字段必填.", T(field.DisplayName))); } } return Editor(part, field, shapeHelper); } protected override void Importing(ContentPart part, TextBoxField field, ImportContentContext context) { context.ImportAttribute(field.FieldDefinition.Name + "." + field.Name, "Value", v => field.Value = v); } protected override void Exporting(ContentPart part, TextBoxField field, ExportContentContext context) { context.Element(field.FieldDefinition.Name + "." + field.Name).SetAttributeValue("Value", field.Value); } protected override void Describe(DescribeMembersContext context) { context .Member(null, typeof(string), T("值"), T("此字段值.")) .Enumerate<TextBoxField>(() => field => new[] { field.Value }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CalcNumericoUtilCSharp { public static class Function { //Ler uma equação em um vetor public static List<double> readEquation (out List<double> expo, string endCondition = "") { //Lista de valores List<double> eq = new List<double>(); List<double> exp = new List<double>(); //Lista final List<double> eqLido = new List<double>(); List<double> eqSum = new List<double>(); List<double> expSum = new List<double>(); //Info Console.WriteLine("Insira os valores da equação, na seguinte ordem: Ax^b"); Console.WriteLine("Primeiramente o valor A (pressione enter), depois o valor do expoente."); //Ler valores Console.WriteLine("Insira os valores: "); string read = ""; string expRead = ""; while ((read = Console.ReadLine()) != endCondition) { //Ler expRead = Console.ReadLine(); //Adicionar na lista try { eq.Add(Convert.ToDouble(read)); exp.Add(Convert.ToInt32(expRead)); } catch (Exception e) { break; } } //Pular linha Console.WriteLine(); //Somar expoentes iguais foreach(double e in exp) { //Não contem o expoente atual if (!eqLido.Contains(e)) { //Soma double aSum = 0; //Rodar lista de expoentes for (int i = 0; i < exp.Count; i++) { if (e == exp[i]) { aSum += eq[i]; } } //Montar eqSum.Add(aSum); expSum.Add(e); //Adicionar aos lidos eqLido.Add(e); } } //return expo = expSum; return eqSum; } //Calcular public static double calculateEquation(double x, List<double>eq, List<double>exp) { double result = 0; //Ler for (int i = 0; i < eq.Count; i++) { result += (eq[i]) * (Math.Pow(x, exp[i])); } return result; } } }
using Mono.Cecil; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Nailhang.Processing { class DefaultAssemblyResolver : IAssemblyResolver { readonly IEnumerable<string> windowsGACFolders; readonly HashSet<string> folders = new HashSet<string>() { @".\" }; readonly Dictionary<string, AssemblyDefinition> definitions = new Dictionary<string, AssemblyDefinition>(); public DefaultAssemblyResolver() { var windowsFolder = Environment.GetEnvironmentVariable("windir"); if (windowsFolder != null) { windowsGACFolders = new[] { @"assembly\GAC_MSIL", @"assembly\GAC_64", @"assembly\GAC_32", @"Microsoft.NET\assembly\GAC_MSIL", @"Microsoft.NET\assembly\GAC_64", @"Microsoft.NET\assembly\GAC_32", }.Select(q => Path.Combine(windowsFolder, q)) .ToArray(); } else windowsGACFolders = new string[] { }; } public void AddSearchDirectory(string directory) { folders .UnionWith(new[] { directory }); } public AssemblyDefinition Resolve(string fullName) { throw new NotImplementedException(); } public AssemblyDefinition Resolve(AssemblyNameReference name) { return Resolve(name, new ReaderParameters { AssemblyResolver = this }); } string SearchFile(string name) { foreach (var f in folders) if (new FileInfo(Path.Combine(f, name)).Exists) return Path.Combine(f, name); return null; } public AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters) { lock (definitions) { if (definitions.ContainsKey(name.FullName)) return definitions[name.FullName]; var def = _Resolve(name, parameters); definitions[name.FullName] = def; return def; } } public AssemblyDefinition Resolve(string fullName, ReaderParameters parameters) { throw new NotImplementedException(); } IEnumerable<string> GACSearch(string gacFolder, AssemblyNameReference name) { gacFolder = Path.Combine(gacFolder, name.Name); if (Directory.Exists(gacFolder)) { foreach (var dir_name in new[] { name.Version.ToString() + "__" + string.Concat(name.PublicKeyToken.Select(i => i.ToString("x2"))), "v4.0_" + name.Version.ToString() + "__" + string.Concat(name.PublicKeyToken.Select(i => i.ToString("x2"))) }) { var assFolder = Path.Combine(gacFolder, dir_name); if (Directory.Exists(assFolder)) { var assFilePath = Path.Combine(assFolder, name.Name + ".dll"); if (File.Exists(assFilePath)) yield return assFilePath; } } } } AssemblyDefinition _Resolve(AssemblyNameReference name, ReaderParameters parameters) { var filePath = SearchFile(name.Name + ".dll"); if (filePath == null) { if (windowsGACFolders.Any()) { var gacFile = windowsGACFolders.SelectMany(q => GACSearch(q, name)).FirstOrDefault(); if (gacFile != null) return AssemblyDefinition.ReadAssembly(gacFile, parameters); throw new InvalidOperationException($"Can't find: {name.FullName} assembly"); } } return AssemblyDefinition.ReadAssembly(filePath, parameters); } public void Dispose() { definitions.Clear(); } } }
using ApiFipe.Domain.Model; using ApiFipe.Infra.Repository; using ApiFipe.Service.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ApiFipe.Service.Service { public class FipeService : IFipeService { FipeRepository rep = new FipeRepository(); public void Add(Fipe Entity) { try { rep.Add(Entity); } catch (Exception) { throw new ArgumentException("Ocorreu um erro!"); } } public void Delete(int Id) { try { rep.Delete(Id); } catch (Exception) { throw new ArgumentException("Ocorreu um erro!"); } } public Fipe Get(int Id) { try { return rep.Get(Id); } catch (Exception) { throw new ArgumentException("Ocorreu um erro!"); } } public List<Fipe> List() { try { return rep.GetAll(); } catch (Exception) { throw new ArgumentException("Ocorreu um erro!"); } } public void Update(Fipe Entity) { try { rep.Edit(Entity); } catch (Exception) { throw new ArgumentException("Ocorreu um erro!"); } } public List<Fipe> BuscarPorAno(string Ano) { try { return rep.GetPorAno(Ano); } catch (Exception) { throw new ArgumentException("Ocorreu um erro!"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DAL.Contracts { public interface IMovieRepository:IRepository<Movy> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TinhLuongINFO { public class Ouput { private string outputString; private int outputCode; public string OutputString { get { return outputString; } set { outputString = value; } } public int OutputCode { get { return outputCode; } set { outputCode = value; } } } }
using System; using System.Collections.Generic; namespace ControleEstacionamento.Domain.Entities { public class Valores { public int ValorId { get; set; } public DateTime InicioVigencia { get; set; } public DateTime FimVigencia { get; set; } public double ValorHora { get; set; } public double ValorAdicional { get; set; } public virtual ICollection<MovimentacaoVeiculo> ListaMovimentacao { get; set; } public Valores() { ListaMovimentacao = new List<MovimentacaoVeiculo>(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using KartLib; using KartLib.Views; using KartObjects; using System.IO; using FastReport; namespace KartSystem { public partial class SupplierMovementView : KartUserControl { public SupplierMovementView() { InitializeComponent(); ViewObjectType = ObjectType.SupplierMovement; lueSupplier.Properties.DataSource = KartDataDictionary.sSuppliers; } private void sbLoadData_Click(object sender, EventArgs e) { if (lueSupplier.EditValue != null) RefreshView(); else MessageBox.Show(this, "Выберите поставщика", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } public override void RefreshView() { if (lueSupplier.EditValue != null) movementSupplierBindingSource.DataSource = Loader.DbLoad<SupplierMovement>("", 0, lueSupplier.EditValue.ToString()); } public override void SaveSettings() { MovementSupplierViewSettings s = new MovementSupplierViewSettings(); s.IdSupplier = (long?)lueSupplier.EditValue; SaveSettings<MovementSupplierViewSettings>(s); gvMovementSupplier.SaveLayoutToXml(gvSettingsFileName()); } public override void LoadSettings() { MovementSupplierViewSettings s = (MovementSupplierViewSettings)LoadSettings<MovementSupplierViewSettings>(); if (s != null) { lueSupplier.EditValue = s.IdSupplier; } if (File.Exists(gvSettingsFileName())) gvMovementSupplier.SaveLayoutToXml(gvSettingsFileName()); } private void simpleButton1_Click(object sender, EventArgs e) { using (Report report = new Report()) { string _ReportPath = Settings.GetExecPath() + @"\Reports"; if (!File.Exists(_ReportPath + @"\SupplierMovement.frx")) { MessageBox.Show("Не найден файл:\n" + _ReportPath + @"\SupplierMovement.frx"); return; } report.Load(_ReportPath + @"\SupplierMovement.frx"); if (report == null) return; report.RegisterData(movementSupplierBindingSource.DataSource as List<SupplierMovement>, "movementSupplierBindingSource"); report.GetDataSource("movementSupplierBindingSource").Enabled = true; TextObject Supplier = (TextObject)report.FindObject("Supplier"); if (Supplier != null) Supplier.Text = Loader.DbLoadSingle<Supplier>("Id = " + lueSupplier.EditValue.ToString()).Name; if (report.Prepare()) report.ShowPrepared(true); } } } }
public class Solution { public int MaximumGap(int[] nums) { if (nums.Length == 0) return 0; int max = 0, min = int.MaxValue; foreach (var num in nums) { max = Math.Max(max, num); min = Math.Min(min, num); } int size = (max-min) / nums.Length + 1; int cnt = (max-min) / size + 1; int[] bucketMins = new int[cnt]; int[] bucketMaxs = new int[cnt]; for (int i=0; i<cnt; i++) { bucketMins[i] = int.MaxValue; bucketMaxs[i] = -1; } foreach (var num in nums) { int index = (num-min) / size; bucketMins[index] = Math.Min(bucketMins[index], num); bucketMaxs[index] = Math.Max(bucketMaxs[index], num); } for (int i=0; i<cnt; i++) { Console.WriteLine(bucketMaxs[i]); } int res = 0; for (int i=0; i<cnt-1; i++) { if (bucketMaxs[i] != -1) { int j=i+1; while (bucketMins[j] == int.MaxValue) j++; if (j > cnt-1) break; res = Math.Max(res, bucketMins[j] - bucketMaxs[i]); } } return res; } } /* public class Solution { public int MaximumGap(int[] nums) { if (nums.Length <= 1) return 0; int mx = int.MinValue, mn = int.MaxValue; foreach (var num in nums) { mx = Math.Max(mx, num); mn = Math.Min(mn, num); } int bucketSize = (mx-mn) / nums.Length + 1; int bucketCnt = (mx-mn) / bucketSize + 1; int[] bucketMx = Enumerable.Repeat(int.MinValue, bucketCnt).ToArray(); int[] bucketMn = Enumerable.Repeat(int.MaxValue, bucketCnt).ToArray(); foreach (var num in nums) { int bucketIdx = (num - mn) / bucketSize; bucketMx[bucketIdx] = Math.Max(bucketMx[bucketIdx], num); bucketMn[bucketIdx] = Math.Min(bucketMn[bucketIdx], num); } int res = 0; int lastBucketIdx = -1; for(int i=0; i<bucketCnt; i++) { if (bucketMx[i] == int.MinValue) continue; if (lastBucketIdx != -1) { res = Math.Max(bucketMn[i]-bucketMx[lastBucketIdx], res); } lastBucketIdx = i; } return res; } } */
using FeriaVirtual.Domain.Models.Users.Interfaces; using FeriaVirtual.Domain.SeedWork.Commands; using FeriaVirtual.Domain.SeedWork.Events; using FeriaVirtual.Domain.SeedWork.Query; using FeriaVirtual.Infrastructure.Persistence.RelationalRepositories; using FeriaVirtual.Infrastructure.SeedWork; using FeriaVirtual.Infrastructure.SeedWork.Commands; using FeriaVirtual.Infrastructure.SeedWork.Events; using FeriaVirtual.Infrastructure.SeedWork.Events.Oracle; using FeriaVirtual.Infrastructure.SeedWork.Events.RabbitMQ; using FeriaVirtual.Infrastructure.SeedWork.Queries; using Microsoft.Extensions.DependencyInjection; namespace FeriaVirtual.Infrastructure.IOC.Extensions.DependencyInjection { public static class Infrastructure { public static IServiceCollection AddInfrastructure (this IServiceCollection services) { services.AddScoped<IUserRepository, UserRepository>(); services.AddScoped<IEmployeeRepository, EmployeeRepository>(); services.AddScoped<ISessionRepository, SessionRepository>(); services.AddScoped<InMemoryApplicationEventBus, InMemoryApplicationEventBus>(); services.AddScoped<IEventBus, OracleEventBus>(); services.AddScoped<IEventBus, RabbitMqEventBus>(); services.AddScoped<RabbitMqPublisher, RabbitMqPublisher>(); services.AddScoped<DomainEventsInformation, DomainEventsInformation>(); services.AddScoped<DomainEventJsonDeserializer, DomainEventJsonDeserializer>(); services.AddScoped<ICommandBus, InMemoryCommandBus>(); services.AddScoped<IQueryBus, InMemoryQueryBus>(); return services; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model.IntelligenceDiningTable { /// <summary> /// 元素字典 /// </summary> public class E_NutritionElements { /// <summary> /// 元素字典ID /// </summary> public int id { get; set; } /// <summary> /// 元素所属分组 /// </summary> public int nutritionid { get; set; } /// <summary> /// 元素名称 /// </summary> public string elements { get; set; } /// <summary> /// 元素单位 /// </summary> public string company { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace UgyfelNyilvantartas { public partial class form_Reszletek : Form { public form_Reszletek() { InitializeComponent(); } private void button_mentes_Click(object sender, EventArgs e) { Modositasok_mentese(); Modositasok_tiltasa(); this.Close(); Program.form_Fooldal.Show(); } private void button_kilepes_Click(object sender, EventArgs e) { this.Close(); Program.form_Fooldal.Show(); } /*private void form_Reszletek_FormClosing(object sender, FormClosingEventArgs e) { this.Close(); Program.form_Fooldal.Show(); }*/ private void form_Reszletek_Load(object sender, EventArgs e) { DG_Reszletek_megrendeles_Beallitasok(); DG_Reszletek_ugyfel_Beallitasok(); DG_Reszletek_kollega_Beallitasok(); DG_Reszletek_koltsegek_Beallitasok(); textBox_Reszletek_leiras.Clear(); Reszletek_Betoltes(); } private void DG_Reszletek_megrendeles_Beallitasok() { DG_Reszletek_megrendeles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; DG_Reszletek_megrendeles.MultiSelect = false; } private void DG_Reszletek_ugyfel_Beallitasok() { DG_Reszletek_ugyfel.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; } private void DG_Reszletek_kollega_Beallitasok() { DG_Reszletek_kollega.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; } private void DG_Reszletek_koltsegek_Beallitasok() { DG_Reszletek_koltsegek.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; DG_Reszletek_koltsegek.MultiSelect = false; } private void Reszletek_Betoltes() { DG_Reszletek_megrendeles.Rows.Clear(); for (int i = 0; i < Program.megrendelesek.Count; i++) { if (Program.megrendelesek[i].Megrendeles_ID.Equals(Program.kivalasztott.Cells["MunkaID"].Value)) { DG_Reszletek_megrendeles.Rows[0].Cells["FelvetelDatum"].Value = Program.megrendelesek[i].Felvetel; DG_Reszletek_megrendeles.Rows[0].Cells["Hatarido"].Value = Program.megrendelesek[i].Hatarido.ToString("yyyy.MM.dd"); DG_Reszletek_megrendeles.Rows[0].Cells["VeglegesAr"].Value = Program.megrendelesek[i].Vegleges_ar; DG_Reszletek_megrendeles.Rows[0].Cells["EddigFizetve"].Value = Program.megrendelesek[i].Eddig_fizetve; DG_Reszletek_megrendeles.Rows[0].Cells["FizetveDatum"].Value = Program.megrendelesek[i].Eddig_fizetett_datum.ToString("yyyy.MM.dd"); DG_Reszletek_megrendeles.Rows[0].Cells["Peldanyszam"].Value = Program.megrendelesek[i].Peldanyszam; DG_Reszletek_megrendeles.Rows[0].Cells["KiindulasiNyelv"].Value = Program.megrendelesek[i].Kiindulasi_nyelv; DG_Reszletek_megrendeles.Rows[0].Cells["CelNyelv"].Value = Program.megrendelesek[i].Celnyelv; DG_Reszletek_megrendeles.Rows[0].Cells["Statusz"].Value = Program.megrendelesek[i].Statusz; DG_Reszletek_ugyfel.Rows[0].Cells["UgyfelNev"].Value = Program.megrendelesek[i].Ugyfel_nev; DG_Reszletek_ugyfel.Rows[0].Cells["Telefonszam"].Value = Program.megrendelesek[i].Ugyfel_telefon; DG_Reszletek_ugyfel.Rows[0].Cells["EmailCim"].Value = Program.megrendelesek[i].Ugyfel_email; DG_Reszletek_ugyfel.Rows[0].Cells["MasElerhetoseg"].Value = Program.megrendelesek[i].Ugyfel_mas; DG_Reszletek_ugyfel.Rows[0].Cells["Megjegyzes"].Value = Program.megrendelesek[i].Ugyfel_megj; DG_Reszletek_ugyfel.Rows[0].Cells["Kategoria"].Value = Program.megrendelesek[i].Ugyfel_kategoria; DG_Reszletek_kollega.Rows[0].Cells["KollegaNev"].Value = Program.megrendelesek[i].Kollega_nev; textBox_Reszletek_leiras.Text = Program.megrendelesek[i].Leiras; DG_Reszletek_koltsegek.Rows[0].Cells["KollegaDija"].Value = Program.megrendelesek[i].Kollega_dija; DG_Reszletek_koltsegek.Rows[0].Cells["Hitelesites"].Value = Program.megrendelesek[i].Hitelesites; DG_Reszletek_koltsegek.Rows[0].Cells["Futar"].Value = Program.megrendelesek[i].Futar; } } } private void button_modositasEnged_Click(object sender, EventArgs e) { if (DG_Reszletek_megrendeles.ReadOnly == true) { DG_Reszletek_megrendeles.ReadOnly = false; DG_Reszletek_koltsegek.ReadOnly = false; textBox_Reszletek_leiras.ReadOnly = false; } } private void Modositasok_tiltasa() { if (DG_Reszletek_megrendeles.ReadOnly==false) { DG_Reszletek_megrendeles.ReadOnly = true; DG_Reszletek_koltsegek.ReadOnly = true; textBox_Reszletek_leiras.ReadOnly = true; } } private void Modositasok_mentese() { for (int i = 0; i < Program.megrendelesek.Count; i++) { if (Program.kivalasztott.Cells["MunkaID"].Value.Equals(Program.megrendelesek[i].Megrendeles_ID)) { Program.megrendelesek[i].Hatarido = Convert.ToDateTime(DG_Reszletek_megrendeles.Rows[0].Cells["Hatarido"].Value); Program.megrendelesek[i].Vegleges_ar = Convert.ToInt32(DG_Reszletek_megrendeles.Rows[0].Cells["VeglegesAr"].Value); Program.megrendelesek[i].Eddig_fizetve = Convert.ToInt32(DG_Reszletek_megrendeles.Rows[0].Cells["EddigFizetve"].Value); Program.megrendelesek[i].Eddig_fizetett_datum = Convert.ToDateTime(DG_Reszletek_megrendeles.Rows[0].Cells["FizetveDatum"].Value); Program.megrendelesek[i].Peldanyszam = Convert.ToInt32(DG_Reszletek_megrendeles.Rows[0].Cells["Peldanyszam"].Value); Program.megrendelesek[i].Kiindulasi_nyelv = Convert.ToString(DG_Reszletek_megrendeles.Rows[0].Cells["KiindulasiNyelv"].Value); Program.megrendelesek[i].Celnyelv = Convert.ToString(DG_Reszletek_megrendeles.Rows[0].Cells["CelNyelv"].Value); Program.megrendelesek[i].Statusz = Convert.ToString(DG_Reszletek_megrendeles.Rows[0].Cells["Statusz"].Value); Program.megrendelesek[i].Kollega_nev = Convert.ToString(DG_Reszletek_kollega.Rows[0].Cells["KollegaNev"].Value); Program.megrendelesek[i].Leiras = Convert.ToString(textBox_Reszletek_leiras.Text); Program.megrendelesek[i].Kollega_dija = Convert.ToInt32(DG_Reszletek_koltsegek.Rows[0].Cells["KollegaDija"].Value); Program.megrendelesek[i].Hitelesites = Convert.ToInt32(DG_Reszletek_koltsegek.Rows[0].Cells["Hitelesites"].Value); Program.megrendelesek[i].Futar = Convert.ToInt32(DG_Reszletek_koltsegek.Rows[0].Cells["Futar"].Value); } } /* Program.sql.Parameters.Clear(); Program.sql.CommandText = "UPDATE munka, kollega SET munka.felvetel_datuma=@felvetel, munka.hatarido=@hatarido, munka.vegleges_ar=@vegleges_ar, munka.eddig_fizetett=@eddig_fizetett, munka.eddig_fizetett_datuma=@eddig_fizetett_datuma, munka.peldanyszam=@peldanyszam, munka.leiras=@leiras, munka.statusz=@statusz, munka.kiindulasi_nyelv_ID=@kiindulasi_nyelv, munka.celnyelv_ID=@celnyelv, kollega.k_nev=@k_nev, munka.kollega_dija=@kollega_dija, munka.hitelesites=@hitelesites, munka.futar=@futar, munka.elkeszult_datum=@elkeszult_datum"; Program.sql.Parameters.AddWithValue("@munka.felvetel", DG_Reszletek_megrendeles.Rows[0].Cells["FelvetelDatum"].Value); Program.sql.Parameters.AddWithValue("@munka.hatarido", DG_Reszletek_megrendeles.Rows[0].Cells["Hatarido"].Value); Program.sql.Parameters.AddWithValue("@munka.vegleges_ar", DG_Reszletek_megrendeles.Rows[0].Cells["VeglegesAr"].Value); Program.sql.Parameters.AddWithValue("@munka.eddig_fizetett", DG_Reszletek_megrendeles.Rows[0].Cells["EddigFizetve"].Value); Program.sql.Parameters.AddWithValue("@munka.eddig_fizetett_datuma", DG_Reszletek_megrendeles.Rows[0].Cells["FizetveDatum"].Value); Program.sql.Parameters.AddWithValue("@munka.peldanyszam", DG_Reszletek_megrendeles.Rows[0].Cells["Peldanyszam"].Value); Program.sql.Parameters.AddWithValue("@munka.leiras", textBox_leiras.Text); Program.sql.Parameters.AddWithValue("@munka.statusz", DG_Reszletek_megrendeles.Rows[0].Cells["Statusz"].Value); Program.sql.Parameters.AddWithValue("@munka.kiindulasi_nyelv_ID", DG_Reszletek_megrendeles.Rows[0].Cells["KiindulasiNyelv"].Value); Program.sql.Parameters.AddWithValue("@munka.celnyelv_ID", DG_Reszletek_megrendeles.Rows[0].Cells["CelNyelv"].Value); Program.sql.Parameters.AddWithValue("@kollega.k_nev", DG_Reszletek_megrendeles.Rows[0].Cells["KollegaNev"].Value); Program.sql.Parameters.AddWithValue("@munka.kollega_dija", DG_Reszletek_megrendeles.Rows[0].Cells["KollegaDija"].Value); Program.sql.Parameters.AddWithValue("@munka.hitelesites", DG_Reszletek_megrendeles.Rows[0].Cells["Hitelesites"].Value); Program.sql.Parameters.AddWithValue("@munka.futar", DG_Reszletek_megrendeles.Rows[0].Cells["Futar"].Value); Program.sql.Parameters.AddWithValue("@munka.elkeszult_datum", DateTime.Now);*/ } } }
// // Copyright (c) Autodesk, Inc. All rights reserved. // // This computer source code and related instructions and comments are the // unpublished confidential and proprietary information of Autodesk, Inc. // and are protected under Federal copyright and state trade secret law. // They may not be disclosed to, copied or used by any third party without // the prior written consent of Autodesk, Inc. // using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; #if !UNITY_WSA using System.Net; using System.Security.Cryptography.X509Certificates; #elif UNITY_WSA using UnityEngine.Networking; #endif using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using SimpleJSON; namespace Autodesk.Forge.ARKit { public class MaterialRequest : RequestObjectInterface { #region Properties public int matId { get; set; } public Material material { get; set; } #endregion #region Constructors public MaterialRequest (IForgeLoaderInterface _loader, Uri _uri, string _bearer, int _matId, JSONNode node) : base (_loader, _uri, _bearer) { resolved = SceneLoadingStatus.eMaterial; matId = _matId; lmvtkDef = node; } #endregion #region Forge Request Object Interface #if !UNITY_WSA public override void FireRequest (Action<object, AsyncCompletedEventArgs> callback = null) { emitted = DateTime.Now; try { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; using ( client = new WebClient () ) { if ( callback != null ) client.DownloadStringCompleted += new DownloadStringCompletedEventHandler (callback); if ( !string.IsNullOrEmpty (bearer) ) client.Headers.Add ("Authorization", "Bearer " + bearer); client.Headers.Add ("Keep-Alive", "timeout=15, max=100"); //if ( compression == true ) // client.Headers.Add ("Accept-Encoding", "gzip, deflate"); state = SceneLoadingStatus.ePending; client.DownloadStringAsync (uri, this); } } catch ( Exception ex ) { Debug.Log (ForgeLoader.GetCurrentMethod () + " " + ex.Message); state = SceneLoadingStatus.eError; } } #elif UNITY_WSA public override void FireRequest (Action<object, AsyncCompletedEventArgs> callback =null) { emitted = DateTime.Now; mb.StartCoroutine (_FireRequest_ (callback)) ; } public override IEnumerator _FireRequest_ (Action<object, AsyncCompletedEventArgs> callback =null) { //using ( client =new UnityWebRequest (uri.AbsoluteUri) ) { System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; using ( client =UnityWebRequest.Get (uri.AbsoluteUri) ) { //client.SetRequestHeader ("Connection", "keep-alive") ; //client.method =UnityWebRequest.kHttpVerbGET ; //if ( callback != null ) // client.DownloadStringCompleted +=new DownloadStringCompletedEventHandler (callback) ; if ( !string.IsNullOrEmpty (bearer) ) client.SetRequestHeader ("Authorization", "Bearer " + bearer) ; //client.SetRequestHeader ("Keep-Alive", "timeout=15, max=100"); //if ( compression == true ) // client.SetRequestHeader ("Accept-Encoding", "gzip, deflate"); state =SceneLoadingStatus.ePending ; //client.DownloadStringAsync (uri, this) ; #if UNITY_2017_2_OR_NEWER yield return client.SendWebRequest () ; #else yield return client.Send () ; #endif if ( client.isNetworkError || client.isHttpError ) { Debug.Log (ForgeLoader.GetCurrentMethod () + " " + client.error + " - " + client.responseCode) ; state =SceneLoadingStatus.eError ; } else { //client.downloadHandler.data //client.downloadHandler.text if ( callback != null ) { DownloadStringCompletedEventArgs args =new DownloadStringCompletedEventArgs (null, false, this) ; args.Result =client.downloadHandler.text ; callback (this, args) ; } } } } #endif //public override void CancelRequest () ; public override void ProcessResponse (AsyncCompletedEventArgs e) { //TimeSpan tm = DateTime.Now - emitted; //UnityEngine.Debug.Log ("Received: " + tm.TotalSeconds.ToString () + " / " + uri.ToString ()); DownloadStringCompletedEventArgs args = e as DownloadStringCompletedEventArgs; try { lmvtkDef = JSON.Parse (args.Result); state = SceneLoadingStatus.eReceived; } catch ( Exception ex ) { Debug.Log (ForgeLoader.GetCurrentMethod () + " " + ex.Message); state = SceneLoadingStatus.eError; } finally { } } public override string GetName () { return ("material-" + matId); } public override GameObject BuildScene (string name, bool saveToDisk = false) { material = CreateMaterial (lmvtkDef, null); material.SetupMaterialWithBlendMode ((BlendMode)material.GetFloat ("_Mode")); material.SetMaterialKeywords (Texture.TextureType.Diffuse, false); #if UNITY_EDITOR if ( saveToDisk ) { AssetDatabase.CreateAsset (material, ForgeConstants._resourcesPath + this.loader.PROJECTID + "/" + name + ".mat"); //material =AssetDatabase.LoadAssetAtPath<Material> (ForgeConstants._resourcesPath + this.loader.PROJECTID + "/" + name + ".mat") ; } #endif base.BuildScene (name, saveToDisk); return (gameObject); } #endregion #region Simple Material public enum BlendMode { Opaque = 0, Cutout = 1, Fade = 2, Transparent = 3 } protected Material CreateMaterial (string jsonSt, string proteinSt) { StandardMaterial lmvMat = new StandardMaterial (jsonSt, proteinSt); return (CreateMaterial (lmvMat)); } protected Material CreateMaterial (JSONNode json, JSONNode protein) { StandardMaterial lmvMat = new StandardMaterial (json, protein); return (CreateMaterial (lmvMat)); } protected Material CreateMaterialV1 (StandardMaterial lmvMat) { // https://docs.unity3d.com/Manual/StandardShaderMetallicVsSpecular.html // Standard: The shader exposes a “metallic” value that states whether the material is metallic or not. // Standard (Specular setup): Choose this shader for the classic approach. Material mat = new Material ( lmvMat.isMetal == true ? Shader.Find ("Standard") : Shader.Find ("Standard (Specular setup)") ); try { if ( lmvMat.specular_tex != null ) { mat.EnableKeyword ("_SPECULARHIGHLIGHTS_OFF"); mat.SetFloat ("_SpecularHighlights", 0f); } //mat.DisableKeyword ("_SPECULARHIGHLIGHTS_OFF") ; //mat.SetFloat ("_SpecularHighlights", 1f) ; mat.EnableKeyword ("_GLOSSYREFLECTIONS_OFF"); mat.SetFloat ("_GlossyReflections", 0f); var ambiant = lmvMat.ambient; if ( ambiant != Color.clear ) mat.SetColor ("_Color", ambiant); var diffuse = lmvMat.diffuse; if ( diffuse != Color.clear ) mat.SetColor ("_Color", diffuse); var emissive = lmvMat.emissive; if ( emissive != Color.clear ) mat.SetColor ("_EmissionColor", emissive); var specular = lmvMat.specular; if ( specular != Color.clear && ( lmvMat.isMetal == true // In Unity3d, the texture would not show && lmvMat.diffuse_tex != null && specular != Color.white ) ) mat.SetColor ("_SpecColor", specular); var transparent = lmvMat.transparent; if ( transparent ) { mat.SetFloat ("_Mode", (float)BlendMode.Transparent); mat.EnableKeyword ("_ALPHABLEND_ON"); Color color = mat.GetColor ("_Color"); color.a = lmvMat.transparency; mat.SetColor ("_Color", color); } // Create a new request to get the Textures if ( lmvMat.diffuse_tex != null ) { //TextureRequest req =new TextureRequest (loader, null, mat, Texture.TextureType.Diffuse, lmvMat.material) ; TextureRequest req = new TextureRequest (loader, null, bearer, mat, lmvMat.diffuse_tex, lmvMat.material); if ( fireRequestCallback != null ) fireRequestCallback (this, req); } if ( lmvMat.specular_tex != null ) { TextureRequest req = new TextureRequest (loader, null, bearer, mat, lmvMat.specular_tex, lmvMat.material); if ( fireRequestCallback != null ) fireRequestCallback (this, req); } if ( lmvMat.bump_tex != null ) { TextureRequest req = new TextureRequest (loader, null, bearer, mat, lmvMat.bump_tex, lmvMat.material); if ( fireRequestCallback != null ) fireRequestCallback (this, req); } } catch ( System.Exception e ) { Debug.Log ("exception " + e.Message); mat = ForgeLoaderEngine.GetDefaultMaterial (); } return (mat); } protected Material CreateMaterial (StandardMaterial lmvMat) { // https://docs.unity3d.com/Manual/StandardShaderMetallicVsSpecular.html // Standard: The shader exposes a “metallic” value that states whether the material is metallic or not. // Standard (Specular setup): Choose this shader for the classic approach. bool isMetal = lmvMat.isMetal; Material mat = new Material (isMetal ? Shader.Find ("Standard") : Shader.Find ("Standard (Specular setup)")); try { // Color properties Color color = Color.clear; Color diffuse = lmvMat.diffuse; Color ambient = lmvMat.ambient; Color specular = lmvMat.specular; color = diffuse != Color.clear ? diffuse : ambient; if ( color == Color.clear && isMetal ) color = specular; mat.SetColor ("_Color", color); // Metallic properties if ( isMetal ) mat.SetFloat ("_Metallic", 1); float glossiness = lmvMat.glossiness / 2000; mat.SetFloat ("_Glossiness", glossiness); mat.SetFloat ("_Shininess", glossiness); if ( specular != Color.white ) mat.SetColor ("_SpecColor", color); var specularTexture = lmvMat.specular_tex; if ( specularTexture != null ) { mat.EnableKeyword ("_SPECULARHIGHLIGHTS_OFF"); mat.SetFloat ("_SpecularHighlights", 0f); mat.EnableKeyword ("_GLOSSYREFLECTIONS_OFF"); mat.SetFloat ("_GlossyReflections", 0f); } else { mat.DisableKeyword ("_SPECULARHIGHLIGHTS_OFF"); mat.SetFloat ("_SpecularHighlights", 1f); mat.DisableKeyword ("_GLOSSYREFLECTIONS_OFF"); mat.SetFloat ("_GlossyReflections", 1f); } // Emissive properties var emissive = lmvMat.emissive; if ( emissive != Color.clear ) mat.SetColor ("_EmissionColor", emissive); //var specular = lmvMat.specular; //if ( specular != Color.clear // && ( // lmvMat.isMetal == true // In Unity3d, the texture would not show // && lmvMat.diffuse_tex != null // && specular != Color.white // ) //) // mat.SetColor ("_SpecColor", specular); // Transparent properties var transparent = lmvMat.transparent; if ( transparent ) { mat.SetFloat ("_Mode", (float)BlendMode.Transparent); mat.EnableKeyword ("_ALPHABLEND_ON"); color.a = lmvMat.transparency; mat.SetColor ("_Color", color); } // Create a new request to get the Textures if ( lmvMat.diffuse_tex != null ) { //TextureRequest req =new TextureRequest (loader, null, mat, Texture.TextureType.Diffuse, lmvMat.material) ; TextureRequest req = new TextureRequest (loader, null, bearer, mat, lmvMat.diffuse_tex, lmvMat.material); if ( fireRequestCallback != null ) fireRequestCallback (this, req); } if ( lmvMat.specular_tex != null ) { TextureRequest req = new TextureRequest (loader, null, bearer, mat, lmvMat.specular_tex, lmvMat.material); if ( fireRequestCallback != null ) fireRequestCallback (this, req); } if ( lmvMat.bump_tex != null ) { TextureRequest req = new TextureRequest (loader, null, bearer, mat, lmvMat.bump_tex, lmvMat.material); if ( fireRequestCallback != null ) fireRequestCallback (this, req); } } catch ( System.Exception e ) { Debug.Log ("exception " + e.Message); mat = ForgeLoaderEngine.GetDefaultMaterial (); } return (mat); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.Concurrent; using System.Threading; using System.Reflection; namespace SAAS.FrameWork.Message { public class MessageBus:IMessageBus { private static object _instanceLocker = new object(); private ConcurrentQueue<IMessage> _messaegPool = new ConcurrentQueue<IMessage>(); private int POLLING_INTERVAL = 300; private Thread _thread; private MessageBus() { _thread = new Thread(Subscribe); RunIt(); } public static MessageBus Instance { get { return SingletonProxy<MessageBus>.Create(() => new MessageBus()); } } private void ProcessMessage(IMessage message) { try { message.ProcessMe(); } catch(Exception) { // Esmart.Framework.Logging.LogManager.CreateLog4net().Error("applicationError", ex);//LOG4写文本 } } private void Subscribe() { while (true) { try { if (_messaegPool.Count > 0) { IMessage message; if (_messaegPool.TryDequeue(out message)) { ProcessMessage(message); } } else { Thread.Sleep(POLLING_INTERVAL); } } catch(Exception) { //Esmart.Framework.Logging.LogManager.CreateLog4net().Error("applicationError", ex);//LOG4写文本 } } } public void Pubish(IMessage message) { _messaegPool.Enqueue(message); } public void RunIt() { _thread.Start(); } public void StopIt() { throw new NotImplementedException(); } } }
namespace Zebble.Device { using Android.Content; using Android.Content.PM; using Android.Media; using Android.Provider; using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Zebble.Services; using Olive; partial class Media { static int NextRequestId; public static Task<bool> IsCameraAvailable() { var packageManager = Android.App.Application.Context.PackageManager; if (packageManager.HasSystemFeature(PackageManager.FeatureCamera)) return Task.FromResult(result: true); if (packageManager.HasSystemFeature(PackageManager.FeatureCameraFront)) return Task.FromResult(result: true); return Task.FromResult(result: false); } public static bool SupportsTakingPhoto() => true; public static bool SupportsPickingPhoto() => true; public static bool SupportsTakingVideo() => true; public static bool SupportsPickingVideo() => true; static async Task<FileInfo> DoTakePhoto(MediaCaptureSettings settings) { var result = (await TakeMedia("image/*", MediaStore.ActionImageCapture, enableMultipleSelection: false, settings)).FirstOrDefault(); await FixOrientation(result); return result; } static async Task<FileInfo> DoTakeVideo(MediaCaptureSettings settings) { return (await TakeMedia("video/*", MediaStore.ActionVideoCapture, enableMultipleSelection: false, settings)).FirstOrDefault(); } static async Task<FileInfo[]> DoPickPhoto(bool enableMultipleSelection) { var result = await TakeMedia("image/*", Intent.ActionPick, enableMultipleSelection, new Device.MediaCaptureSettings()); foreach (var r in result) await FixOrientation(r); return result; } static Task<FileInfo[]> DoPickVideo(bool enableMultipleSelection) { return TakeMedia("video/*", Intent.ActionPick, enableMultipleSelection, new Device.MediaCaptureSettings()); } static Task<FileInfo[]> TakeMedia(string type, string action, bool enableMultipleSelection, Device.MediaCaptureSettings options) { var id = NextRequestId++; var completionSource = new TaskCompletionSource<FileInfo[]>(id); UIRuntime.CurrentActivity.StartActivity(CreateIntent(id, type, action, enableMultipleSelection, options)); void OnMediaPicked(MediaPickedEventArgs e) { GC.Collect(); PickerActivity.Picked.RemoveHandler(OnMediaPicked); if (e.RequestId != id) return; if (e.Media.Any(x => !x.Exists())) completionSource.TrySetResult(null); else if (e.Error != null) completionSource.SetException(e.Error); else completionSource.TrySetResult(e.Media); } PickerActivity.Picked.Handle(OnMediaPicked); GC.Collect(); return completionSource.Task; } static Intent CreateIntent(int id, string type, string action, bool enableMultipleSelection, Device.MediaCaptureSettings settings) { var result = new Intent(UIRuntime.CurrentActivity, typeof(PickerActivity)) .PutExtra("id", id) .PutExtra("type", type) .PutExtra("action", action) .PutExtra(Intent.ExtraAllowMultiple, enableMultipleSelection) .PutExtra("purge-camera-roll", settings.PurgeCameraRoll) .SetFlags(ActivityFlags.NewTask); if (settings.Camera == CameraOption.Front) result.PutExtra("android.intent.extras.CAMERA_FACING", 1); if (action == MediaStore.ActionVideoCapture) { if (settings.VideoMaxDuration.HasValue) result.PutExtra(MediaStore.ExtraDurationLimit, (int)settings.VideoMaxDuration.Value.TotalSeconds); if (settings.VideoQuality == VideoQuality.Low) result.PutExtra(MediaStore.ExtraVideoQuality, 0); else result.PutExtra(MediaStore.ExtraVideoQuality, 1); } return result; } static async Task FixOrientation(FileInfo file) { if (file != null) await ImageService.Rotate(file, file, ImageService.FindExifRotationDegrees(file)); } static Task DoSaveToAlbum(FileInfo file) { var isPhoto = file.GetMimeType().StartsWith("image"); var mediaType = isPhoto ? Android.OS.Environment.DirectoryPictures : Android.OS.Environment.DirectoryMovies; var directory = new DirectoryInfo(Android.OS.Environment.GetExternalStoragePublicDirectory(mediaType).Path) .GetOrCreateSubDirectory(Device.IO.Root.Name); if (!directory.Exists()) throw new IOException("Failed to create directory " + directory.Name); var destination = directory.GetFile(file.Name); if (destination.Exists()) { var num = 1; while (true) { destination = directory.GetFile(file.NameWithoutExtension() + " " + num + file.Extension); if (!destination.Exists()) break; num++; } } file.CopyTo(destination); try { MediaScannerConnection.ScanFile(UIRuntime.CurrentActivity, new[] { destination.FullName }, null, null); var values = new ContentValues(); values.Put(MediaStore.Images.Media.InterfaceConsts.Title, destination.NameWithoutExtension()); values.Put(MediaStore.Images.Media.InterfaceConsts.Description, string.Empty); values.Put(MediaStore.Images.Media.InterfaceConsts.DateTaken, Java.Lang.JavaSystem.CurrentTimeMillis()); values.Put(MediaStore.Images.ImageColumns.BucketId, destination.FullName.GetHashCode()); values.Put(MediaStore.Images.ImageColumns.BucketDisplayName, destination.Name.ToLowerInvariant()); values.Put("_data", destination.FullName); UIRuntime.CurrentActivity.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, values); } catch (Exception ex) { Log.For(typeof(Media)).Error(ex, "Failed to save to scan file."); } var publicUri = Android.Net.Uri.FromFile(new Java.IO.File(destination.FullName)); var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile, publicUri); UIRuntime.CurrentActivity.SendBroadcast(mediaScanIntent); return Task.CompletedTask; } } }
using System; using System.Diagnostics; using System.IO; using System.Net; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Telegram.Bot; using Telegram.Bot.Types.Enums; namespace WebArchive.Bot { class Program { private static TelegramBotClient BotClient; private static string SetupBasePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; private static readonly WebProxy MWebProxy = new WebProxy("127.0.0.1", 7890); static void Main(string[] args) { //Environment.SetEnvironmentVariable("http_proxy", $"{MWebProxy.Address.Host}:{MWebProxy.Address.Port}", EnvironmentVariableTarget.User); Console.WriteLine("Telegram Wayback WebArchive Bot"); string tokenStr; if (File.Exists(SetupBasePath + "token.text")) tokenStr = File.ReadAllText(SetupBasePath + "token.text"); else if (!string.IsNullOrWhiteSpace(string.Join("", args))) tokenStr = string.Join("http_proxy", MWebProxy.Address.DnsSafeHost); else { Console.WriteLine("Token:"); tokenStr = Console.ReadLine(); } BotClient = new TelegramBotClient(tokenStr,MWebProxy); Console.Title = "Bot:@" + BotClient.GetMeAsync().Result.Username; Console.WriteLine($"@{BotClient.GetMeAsync().Result.Username} : Connected"); BotClient.OnMessage += (sender, eventArgs) => { var message = eventArgs.Message; if (message == null || message.Type != MessageType.Text) return; Console.WriteLine($"@{message.From.Username}: " + message.Text); Task.Run(() => { var waitMessage = BotClient.SendTextMessageAsync(message.Chat.Id, "请稍等…", replyToMessageId: message.MessageId).Result; try { var url = new Uri(message.Text, UriKind.Absolute); var uuid = Guid.NewGuid(); Console.WriteLine(uuid); Directory.CreateDirectory($"{SetupBasePath}html/{uuid}"); var startInfo = new ProcessStartInfo("monolith", $"\"{url}\" -o {SetupBasePath}html/{uuid}/index.html -t 30000") { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, StandardOutputEncoding = Encoding.UTF8 }; startInfo.EnvironmentVariables["http_proxy"] = MWebProxy.Address.ToString(); startInfo.EnvironmentVariables["https_proxy"] = MWebProxy.Address.ToString(); startInfo.EnvironmentVariables["no_proxy"] = false.ToString().ToLower(); var monolith = new Process {StartInfo = startInfo}; monolith.Start(); monolith.WaitForExit(30000); try { if (!File.Exists($"{SetupBasePath}html/{uuid}/index.html")) BotClient.SendTextMessageAsync(message.Chat.Id, "请求超时。", replyToMessageId: message.MessageId); else { var webClient = new WebClient {Encoding = Encoding.UTF8}; webClient.Proxy = MWebProxy; var strsBytes = webClient.UploadFile( "https://ipfs.infura.io:5001/api/v0/add?pin=true", $"{SetupBasePath}html/{uuid}/index.html"); Console.WriteLine(Encoding.UTF8.GetString(strsBytes).Trim()); var jObj = JsonConvert.DeserializeObject<dynamic>(Encoding.UTF8.GetString(strsBytes)); BotClient.SendTextMessageAsync(message.Chat.Id, "https://ipfs.io/ipfs/" + jObj.Hash.ToString(), replyToMessageId: message.MessageId); } } catch (Exception e) { Console.WriteLine(e); BotClient.SendTextMessageAsync(message.Chat.Id, "上传到IPFS网络失败,请稍候重试。", replyToMessageId: message.MessageId); } finally { File.Delete($"{SetupBasePath}html/{uuid}/index.html"); Directory.Delete($"{SetupBasePath}html/{uuid}/"); BotClient.DeleteMessageAsync(message.Chat.Id, waitMessage.MessageId); } } catch (Exception e) { Console.WriteLine(e); BotClient.SendTextMessageAsync(message.Chat.Id, "可能是无效的网址,或不可达。", replyToMessageId: message.MessageId); BotClient.DeleteMessageAsync(message.Chat.Id, waitMessage.MessageId); } }); }; BotClient.StartReceiving(Array.Empty<UpdateType>()); while (true) { if (Console.ReadLine() != "exit") continue; BotClient.StopReceiving(); } // ReSharper disable once FunctionNeverReturns } } }
using SignalrData.Models; using SQLite; namespace TDC_Union.Model { public class ClassUnionFee { public ClassUnionFee() { } public ClassUnionFee(UnionFeeEventArgs uf) { StudentID = uf.StudentID; ID = uf.ID; _1 = uf._1; _2 = uf._2; _3 = uf._3; _4 = uf._4; _5 = uf._5; _6 = uf._6; _7 = uf._7; _8 = uf._8; _9 = uf._9; _10 = uf._10; _11 = uf._11; _12 = uf._12; Year = uf.Year; accept = uf.accept; } [PrimaryKey] public int idpee { get; set; } public string StudentID { get; set; } public string ID { get; set; } public string _1 { get; set; } public string _2 { get; set; } public string _3 { get; set; } public string _4 { get; set; } public string _5 { get; set; } public string _6 { get; set; } public string _7 { get; set; } public string _8 { get; set; } public string _9 { get; set; } public string _10 { get; set; } public string _11 { get; set; } public string _12 { get; set; } public string Year { get; set; } public string accept { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string DOB { get; set; } } }
using Assets.Scripts.Models; using UnityEngine; namespace Assets.Scripts.Controllers.InteractiveObjects.MiningObjects { public class DestroyableObject : InteractiveObject { public GameObject MainObject; public int Hp; public int CurrentHp { get; set; } public BaseObject ItemModel { get; set; } public bool Initialized { get; set; } protected override void Init() { base.Init(); if (Initialized) return; CurrentHp = Hp; } public override void PlayerInteract(HolderObject interactObject, GameManager gameManager, Vector3? hitPosition = null) { base.PlayerInteract(interactObject, gameManager, hitPosition); CurrentHp -= interactObject.Item.Damage; if (CurrentHp > 0) GameManager.Player.MainHud.ShowHudText("[" + CurrentHp + "/" + Hp + "]", HudTextColor.Yellow); if (CurrentHp <= 0) { CurrentHp = 0; if (ItemModel != null) { if (ItemModel.AddDestroyReward) { foreach (var holderObject in ItemModel.CraftRecipe) { var placeObject = HolderObjectFactory.GetItem(holderObject.Item.GetType(), holderObject.Amount / 2); GameManager.PlacementItemsController.DropItemToGround(GameManager, placeObject); } } } GameManager.PlacementItemsController.RemovePlacedItem(MainObject); MainObject.SetActive(false); SoundManager.PlaySFX(WorldConsts.AudioConsts.Destroy); } } public void ChangeHealth(GameManager gameManager, int damage) { CurrentHp -= damage; if (CurrentHp <= 0) { CurrentHp = 0; gameManager.PlacementItemsController.RemovePlacedItem(MainObject); MainObject.SetActive(false); SoundManager.PlaySFX(WorldConsts.AudioConsts.Destroy); } } } }
using Optymalizacja_wykorzystania_pamieci.Diagnostics; using Optymalizacja_wykorzystania_pamieci.Interfaces; using System; using System.Collections.Generic; using System.Linq; namespace Optymalizacja_wykorzystania_pamieci.Tasks.Array_of_Numbers { class Array_Of_Numbers { public int[] numbers { get; set; } private int[] array_secondary { get; set; } private Array_Parameters[] parameters { get; set; } private bool allocation { get; set; } public Array_Of_Numbers(int size, bool allocation) { this.numbers = new int[size]; Random rand = new Random(); for (int i = 0; i < numbers.Length; i++) { numbers[i] = rand.Next(100000); } this.allocation = allocation; this.array_secondary = new int[size]; } public Queue<TaskInterface> PrepareForSort(int number_of_tasks, Diagnostician diag) { Queue<TaskInterface> list_of_tasks = new Queue<TaskInterface>(); this.parameters = new Array_Parameters[number_of_tasks]; int whole = numbers.Length / number_of_tasks; int rest = numbers.Length % number_of_tasks; int param_1 = 0; int param_2 = whole + 1; for (int i = 0; i < number_of_tasks; i++) { if (i > 0) param_1 = param_1 + param_2; param_2 = whole + 1; if (rest < i + 1) param_2--; this.parameters[i] = new Array_Parameters(param_1, param_2); //Dodawanie do kolejki zadań list_of_tasks.Enqueue(new Engine_Task<Array_Of_Numbers, Array_Parameters> (i, this, new TypeOfTask<Array_Of_Numbers, Array_Parameters>(SortingSelection), parameters[i])); } return list_of_tasks; } private void SortingSelection(Array_Of_Numbers array_original, Array_Parameters parameters) { if (array_original.allocation) { MergeSort(array_original.numbers, parameters.start_index, parameters.start_index + parameters.number_of_numbers - 1, array_original.array_secondary, 0, true); } else { MergeSort(array_original.numbers, parameters.start_index, parameters.start_index + parameters.number_of_numbers - 1, array_original.array_secondary, 0, false); } } private static void MergeSort(int[] array_of_numbers, int begin, int end, int[] array_secondary, int start_index, bool merge) { if (begin < end) { //podziel sortowana tablice na pola MergeSort(array_of_numbers, begin, (begin + end) / 2, array_secondary, start_index, merge); MergeSort(array_of_numbers, (begin + end) / 2 + 1, end, array_secondary, start_index, merge); //scal posortowane tablice if(merge) MergingWithAllocation(array_of_numbers, begin, end, array_secondary, start_index); else Merging(array_of_numbers, begin, end, array_secondary, start_index); } } private static void Merging(int[] array_of_numbers, int begin, int end, int[] array_secondary, int start_index) { //Skopiuj wartosci do tablicy pomocniczej for (int i = begin; i <= end; i++) { array_secondary[i-start_index] = array_of_numbers[i]; } //Scalaj tablice int p = begin; int q = (begin + end) / 2 + 1; int r = begin; while (p <= (begin + end) / 2 && q <= end) { if (array_secondary[p-start_index] < array_secondary[q-start_index]) { array_of_numbers[r] = array_secondary[p-start_index]; r++; p++; } else { array_of_numbers[r] = array_secondary[q-start_index]; r++; q++; } } //Przepisz koncowke while (p <= (begin + end) / 2) { array_of_numbers[r] = array_secondary[p-start_index]; r++; p++; } } private static void MergingWithAllocation (int[] array_of_numbers, int begin, int end, int[] array_secondary, int start_index){ for (int i = begin; i <= end; i++) { array_secondary[i - start_index] = array_of_numbers[i]; } int[] array_allocated = new int[end - begin + 1]; int p = begin; int q = (begin + end) / 2 + 1; int r = begin; while (p <= (begin + end) / 2 && q <= end) { if (array_secondary[p - start_index] < array_secondary[q - start_index]) { array_allocated[r - begin] = array_secondary[p - start_index]; array_of_numbers[r] = array_allocated[r - begin]; r++; p++; } else { array_allocated[r - begin] = array_secondary[q - start_index]; array_of_numbers[r] = array_allocated[r - begin]; r++; q++; } } while (p <= (begin + end) / 2) { array_allocated[r - begin] = array_secondary[p - start_index]; array_of_numbers[r] = array_allocated[r - begin]; r++; p++; } } //-----------------------------------------------------------------------Finalizacja---------------------------------------------------------------- public void Finalization() { this.HeapSort(); } //-------------------------------------------------------------------------Metody kopca-------------------------------------------------------------- private void HeapSort() { Array.Copy(this.numbers, this.array_secondary, this.numbers.Count()); int[,] heap = new int[parameters.Length, 2]; int n = 0; for (int i = 0; i < parameters.Length; i++) { HeapAdd(heap, -this.array_secondary[parameters[i].start_index], i, ref n); } int index = 0; for(int i = 0; i < this.numbers.Count(); i++) { this.numbers[i] = -heap[0, 0]; index = heap[0, 1]; HeapRemove(heap, ref n); parameters[index].start_index++; parameters[index].number_of_numbers--; if (parameters[index].number_of_numbers > 0) HeapAdd(heap, -this.array_secondary[parameters[index].start_index], index, ref n); } } private static void HeapAdd(int[,] heap, int value, int part_number, ref int n) { int i, j; i = n++; j = (i - 1) / 2; while (i > 0 && heap[j, 0] < value) { heap[i, 0] = heap[j, 0]; heap[i, 1] = heap[j, 1]; i = j; j = (i - 1) / 2; } heap[i, 0] = value; heap[i, 1] = part_number; } private static void HeapRemove(int[,] heap, ref int n) { int i, j; int[] v = new int[2]; if (n-- > 0) { v[0] = heap[n, 0]; v[1] = heap[n, 1]; i = 0; j = 1; while (j < n) { if (j + 1 < n && heap[j + 1, 0] > heap[j, 0]) j++; if (v[0] >= heap[j, 0]) break; heap[i, 0] = heap[j, 0]; heap[i, 1] = heap[j, 1]; i = j; j = 2 * j + 1; } heap[i, 0] = v[0]; heap[i, 1] = v[1]; } } public void ShowResults() { Console.WriteLine("\nFragment tablicy po sortowaniu:\n"); int i = 0; while(i < 200 && i < this.numbers.Length) { Console.Write("{0}, ", this.numbers[i]); i++; } Console.WriteLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using Eevee.Models; using Vspace = NaturalLanguage.vector.VectorSpace; namespace Eevee.Pages.Songs { public class IndexModel : PageModel { public readonly Eevee.Data.EeveeContext _context; private readonly NaturalLanguage.NN.INN _textprocessor; private readonly int like_weight = 1; public IndexModel(Eevee.Data.EeveeContext context, NaturalLanguage.NN.INN textprocessor) { _context = context; _textprocessor = textprocessor; } public IList<Song> Song { get;set; } [BindProperty(SupportsGet = true)] public string SearchString { get; set; } = ""; public string msg = ""; public string similarity = ""; User _User { get; set; } private float[] preference_vector { get; set; } public IList<Playlist> Playlists { get; set; } public async Task OnGetAsync(int? id) { preference_vector = Vspace.Ones(10); if (HttpContext.User.Identity.IsAuthenticated) { int _id = Int32.Parse(HttpContext.User.Claims.Where(c => c.Type == "UserID").Select(c => c.Value).SingleOrDefault()); Playlists = _context.Playlist.Where(p => p.User.UserID == _id).ToList(); _User = _context.User.Find(_id); preference_vector = Vspace.ToArray(_User.PreferenceVector); } if (id != null) { Song = await _context.Song.Where(s => s.Album.Artist.ArtistID == id).Include(x => x.Genre).Include(x => x.Album).ThenInclude(x => x.Artist).ToListAsync(); } else { List<Song> songs = _context.Song.Include(x => x.Genre).Include(x => x.Album).ThenInclude(x => x.Artist).ToList(); if (SearchString.Length > 0) { SearchString = SearchString.ToLower(); if (!string.IsNullOrEmpty(SearchString)) { Song s = _context.Song.Where(x=>x.Name.ToLower() == SearchString).FirstOrDefault(); if (s != null) { int[] f = AudioAnalysis.Compare.ToArray(s.FreqVec); songs = songs.OrderByDescending(x => AudioAnalysis.Compare.Similarity(f, AudioAnalysis.Compare.ToArray(x.FreqVec)) + .01*x.Rating/(double)x.Listens).ToList(); foreach (var song in songs) { msg += song.Name + ":" + AudioAnalysis.Compare.Similarity(f, AudioAnalysis.Compare.ToArray(song.FreqVec)) + "; "; } } else { Artist a = _context.Artist.Where(x => x.Name.ToLower() == SearchString).FirstOrDefault(); if (a != null) { songs = _context.Song.Where(s => s.Album.Artist.ArtistID == a.ArtistID).ToList(); songs = songs.OrderByDescending(x => .01 * x.Rating / (double)x.Listens).ToList(); } else { Genre g = _context.Genre.Where(x => x.Name.ToLower() == SearchString).FirstOrDefault(); if (g != null) { songs = _context.Song.Where(s => s.Genre.GenreID == g.GenreID).ToList(); songs = songs.OrderByDescending(x => .01 * x.Rating / (double)x.Listens).ToList(); } else { var word_vector = _textprocessor.PredictText(SearchString); songs.Sort((a, b) => (Vspace.Loss(word_vector, Vspace.ToArray(a.WordVec)).CompareTo(Vspace.Loss(word_vector, Vspace.ToArray(b.WordVec))))); } } } } } Song = songs; } } public JsonResult OnPostAddSong(string song_id, string pl_id) { var playlist =_context.Playlist.Where(p=>p.PlaylistID == Int32.Parse(pl_id)).FirstOrDefault(); var song = _context.Song.Where(s => s.SongID == Int32.Parse(song_id)).FirstOrDefault(); PlaylistSongAssignment playlistSongAssignment = new PlaylistSongAssignment() { Playlist = playlist, Song = song }; _context.PlaylistSongAssignment.Add(playlistSongAssignment); _context.SaveChanges(); return new JsonResult("Added song to playlist"); } public JsonResult OnPostIncreaseListen(string song_id) { if (HttpContext.User.Identity.IsAuthenticated) { int _id = Int32.Parse(HttpContext.User.Claims.Where(c => c.Type == "UserID").Select(c => c.Value).SingleOrDefault()); _User = _context.User.Find(_id); } if (_User != null) { History history = _context.History.Where(x => x.User.UserID == _User.UserID && x.Song.SongID == Int32.Parse(song_id)).FirstOrDefault(); Song song = _context.Song.Where(s => s.SongID == Int32.Parse(song_id)).Include(x => x.Album).ThenInclude(x => x.Artist).FirstOrDefault(); if (history == null) { _User.PreferenceVector = Vspace.ConvertToString( Vspace.Normalize(Vspace.Add(Vspace.Scale(0.05f, Vspace.ToArray(song.WordVec)), Vspace.ToArray(_User.PreferenceVector)))); song.Listens += 1; Artist artist = _context.Artist.Where(a => a.ArtistID == song.Album.Artist.ArtistID).FirstOrDefault(); artist.Listens += 1; History new_history = new History() { User = _User, Song = song, Progress = 0, Liked = 0 }; _context.User.Update(_User); _context.Song.Update(song); _context.Artist.Update(artist); _context.History.Add(new_history); _context.SaveChanges(); return new JsonResult("Listen1"); } return new JsonResult("Listen2"); } return new JsonResult("Clicked play " + song_id); } public JsonResult OnPostLike(string song_id, string val) { if (HttpContext.User.Identity.IsAuthenticated) { int _id = Int32.Parse(HttpContext.User.Claims.Where(c => c.Type == "UserID").Select(c => c.Value).SingleOrDefault()); _User = _context.User.Find(_id); preference_vector = Vspace.ToArray(_User.PreferenceVector); } int like = Int32.Parse(val); if (_User != null) { History history = _context.History.Where(x => x.User.UserID == _User.UserID && x.Song.SongID == Int32.Parse(song_id)).FirstOrDefault(); Song song = _context.Song.Where(s => s.SongID == Int32.Parse(song_id)).Include(x => x.Album).ThenInclude(x => x.Artist).FirstOrDefault(); if (history == null) { history = new History() { User = _User, Song = song, Progress = 0, Liked = like }; _context.History.Add(history); _context.SaveChanges(); return new JsonResult("updated 1"); } if(history.Liked != like) { song.Rating += like; Artist artist = _context.Artist.Where(a => a.ArtistID == song.Album.Artist.ArtistID).FirstOrDefault(); artist.Rating += like; history.Liked = like; _User.PreferenceVector = Vspace.ConvertToString( Vspace.Normalize(Vspace.Add(Vspace.Scale(like, Vspace.ToArray(song.WordVec)), Vspace.ToArray(_User.PreferenceVector)))); _context.Song.Update(song); _context.Artist.Update(artist); _context.History.Update(history); _context.User.Update(_User); _context.SaveChanges(); } return new JsonResult("Like1"); } return new JsonResult("updated"); } } }
using System; using System.Collections.Generic; using System.Web.UI; using System.Web.UI.WebControls; using System.Diagnostics; namespace MisterPostman { /// <summary> /// Object that active Postman in a page. /// </summary> public class PostmanActivator { private Page _page; private Control[] _controls; private PostmanObserver[] _observers; private Stopwatch _stopwatch; /// <summary> /// Creates a activator to a page. /// </summary> public PostmanActivator(Page page) { _page = page; // Handles page events to check changed controls. _page.Load += new EventHandler(page_Load); _page.SaveStateComplete += new EventHandler(page_SaveStateComplete); _stopwatch = new Stopwatch(); } void page_Load(object sender, EventArgs e) { _stopwatch.Start(); // Gets all page controls (ignores literals). _controls = FlattenHierachy(_page); _observers = new PostmanObserver[_controls.Length]; for (int i = 0; i < _controls.Length; i++) { // Set contitional UpdatePanels. var updatePanel = _controls[i] as UpdatePanel; if (updatePanel != null) { updatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional; updatePanel.ChildrenAsTriggers = false; } // Create an observer to each control and takes the initial checksum. _observers[i] = new PostmanObserver(_controls[i]); _observers[i].TakeChecksum(); } _stopwatch.Stop(); } void page_SaveStateComplete(object sender, EventArgs e) { _stopwatch.Start(); foreach (var o in _observers) { // Takes the last checksum. o.TakeChecksum(); if (o.IsChanged) { // If control state changed, get the parent UpdatePanel to update. var updatePanel = GetUpdatePanelOf(o.TargetControl); if (updatePanel != null) updatePanel.Update(); } } _stopwatch.Stop(); } /// <summary> /// Gets the UpdatePanel of a Control. /// </summary> private UpdatePanel GetUpdatePanelOf(Control control) { if (control.Parent == null) return null; if(control.Parent is UpdatePanel) return control.Parent as UpdatePanel; else return GetUpdatePanelOf(control.Parent); } /// <summary> /// Get all page controls, recursively, ignoring irrelevant controls. /// </summary> public static Control[] FlattenHierachy(Control root) { if (IgnoreControl(root)) return new Control[0]; var list = new List<Control>() { root }; if (root.HasControls()) { foreach (Control c in root.Controls) { list.AddRange(FlattenHierachy(c)); } } return list.ToArray(); } /// <summary> /// Verifies if FlattenHierachy goes to ignore this control. /// </summary> private static bool IgnoreControl(Control root) { return root is LiteralControl; } } }
using UnityEngine; using System.Collections; public class ScoreKeeper : MonoBehaviour { public int score = 0; public GameObject scoreUIObject; ScoreUI scoreUI; // Use this for initialization void Start () { scoreUI = scoreUIObject.GetComponent<ScoreUI> (); } // Update is called once per frame void Update () { } public void IncreaseScore (int points) { score += points; scoreUI.UpdateScore (score); } }
using Apbd_example_tutorial_10.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Apbd_example_tutorial_10.DTOs.Requests { public class EnrollStudentRequest { public Enrollment enrollment { get; set; } public string studentIndex { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GSVM.Assembler; using GSVM.Assembler.Targets; namespace GSASMTest { class Program { static string testCode = @" ; sample comment jmp main main: hlt"; static void Main(string[] args) { Assembler asm = new Assembler(CPU1.Name); byte[] data = asm.Assemble(testCode); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace WindowsFormsApplication5 { public partial class Form_registration : Form { public Form_registration() { InitializeComponent(); } private void button_back_Click(object sender, EventArgs e) { this.Hide(); this.Close(); } private void Form_registration_Load(object sender, EventArgs e) { } private void button_auth_Click(object sender, EventArgs e) { if (textBox_login.Text != "" || textBox_password.Text != "") { const string message = "Вы уверены что хотите добавить данные?"; const string caption = "Добавление"; var result = MessageBox.Show(message, caption, MessageBoxButtons.YesNo); if (result == DialogResult.No) { } else { MySqlConnection connection = new MySqlConnection("server=localhost;user=root;password=;database=Holiday_Cakes;SslMode=none"); connection.Open(); MySqlCommand myCommand = new MySqlCommand(String.Format("INSERT INTO User (`Log`, `Pass`, `ID_Role`, `Full_Name`) VALUES ('" + textBox_login.Text + "', '" + textBox_password.Text + "', '1', '" + textBox_FullName.Text + "')"), connection); myCommand.ExecuteNonQuery(); connection.Close(); MessageBox.Show("Запись добавлена"); { } } } else { MessageBox.Show("Данные должны содержать номер телефона или адрес электронной почты"); } } private void comboBox_Role_SelectedIndexChanged(object sender, EventArgs e) { } } }
using EuroMillionsHelper.Model; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestEuroMillions { [TestClass] public class UnitTestRepartitionDizaineTirage { [TestMethod] public void TestMethod_RepartitionDizaineTirage_5_unites() { Tirage source = new Tirage(1, 2, 3, 4, 5, 0, 0); int[] expected = new int[5] { 5, 0, 0, 0, 0}; int[] result = Tirage.RepartitionDizaineTirage(source); Assert.IsTrue(AssertAreEqual(result, expected)); } [TestMethod] public void TestMethod_RepartitionDizaineTirage_5_dizaines() { Tirage source = new Tirage(10, 12, 13, 14, 15, 0, 0); int[] expected = new int[5] { 0, 5, 0, 0, 0 }; int[] result = Tirage.RepartitionDizaineTirage(source); Assert.IsTrue(AssertAreEqual(result, expected)); } [TestMethod] public void TestMethod_RepartitionDizaineTirage_5_vingtaines() { Tirage source = new Tirage(21, 22, 23, 24, 25, 0, 0); int[] expected = new int[5] { 0, 0, 5, 0, 0 }; int[] result = Tirage.RepartitionDizaineTirage(source); Assert.IsTrue(AssertAreEqual(result, expected)); } [TestMethod] public void TestMethod_RepartitionDizaineTirage_5_trentaines() { Tirage source = new Tirage(31, 32, 33, 34, 35, 0, 0); int[] expected = new int[5] { 0, 0, 0, 5, 0 }; int[] result = Tirage.RepartitionDizaineTirage(source); Assert.IsTrue(AssertAreEqual(result, expected)); } [TestMethod] public void TestMethod_RepartitionDizaineTirage_5_quarantaines() { Tirage source = new Tirage(41, 42, 43, 44, 50, 0, 0); int[] expected = new int[5] { 0, 0, 0, 0, 5 }; int[] result = Tirage.RepartitionDizaineTirage(source); Assert.IsTrue(AssertAreEqual(result, expected)); } [TestMethod] public void TestMethod_RepartitionDizaineTirage_one_of_each() { Tirage source = new Tirage(1, 10, 20, 34, 45, 0, 0); int[] expected = new int[5] { 1, 1, 1, 1, 1 }; int[] result = Tirage.RepartitionDizaineTirage(source); Assert.IsTrue(AssertAreEqual(result, expected)); } public static bool AssertAreEqual(int[] t1, int[] t2) { bool result = true; if (t1.Length != t2.Length) { return false; } for (int i = 0; i < t1.Length; i++) { if (t1[i] != t2[i]) { result = false; break; } } return result; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace GDS.Comon { /// <summary> /// SqlServer数据访问帮助类 /// </summary> public sealed class SqlHelper { public static string ConnectionString; #region 私有构造函数和方法 private SqlHelper() { } /// <summary> /// 将SqlParameter参数数组(参数值)分配给SqlCommand命令. /// 这个方法将给任何一个参数分配DBNull.Value; /// 该操作将阻止默认值的使用. /// </summary> /// <param name="command">命令名</param> /// <param name="commandParameters">SqlParameters数组</param> private static void AttachParameters(SqlCommand command, SqlParameter[] commandParameters) { if (command == null) throw new ArgumentNullException("command"); if (commandParameters != null) { foreach (SqlParameter p in commandParameters) { if (p != null) { // 检查未分配值的输出参数,将其分配以DBNull.Value. if ((p.Direction == ParameterDirection.InputOutput || p.Direction == ParameterDirection.Input) && (p.Value == null)) { p.Value = DBNull.Value; } command.Parameters.Add(p); } } } } /// <summary> /// 将DataRow类型的列值分配到SqlParameter参数数组. /// </summary> /// <param name="commandParameters">要分配值的SqlParameter参数数组</param> /// <param name="dataRow">将要分配给存储过程参数的DataRow</param> private static void AssignParameterValues(SqlParameter[] commandParameters, DataRow dataRow) { if ((commandParameters == null) || (dataRow == null)) { return; } int i = 0; // 设置参数值 foreach (SqlParameter commandParameter in commandParameters) { // 创建参数名称,如果不存在,只抛出一个异常. if (commandParameter.ParameterName == null || commandParameter.ParameterName.Length <= 1) throw new Exception( string.Format("请提供参数{0}一个有效的名称{1}.", i, commandParameter.ParameterName)); // 从dataRow的表中获取为参数数组中数组名称的列的索引. // 如果存在和参数名称相同的列,则将列值赋给当前名称的参数. if (dataRow.Table.Columns.IndexOf(commandParameter.ParameterName.Substring(1)) != -1) commandParameter.Value = dataRow[commandParameter.ParameterName.Substring(1)]; i++; } } /// <summary> /// 将一个对象数组分配给SqlParameter参数数组. /// </summary> /// <param name="commandParameters">要分配值的SqlParameter参数数组</param> /// <param name="parameterValues">将要分配给存储过程参数的对象数组</param> private static void AssignParameterValues(SqlParameter[] commandParameters, object[] parameterValues) { if ((commandParameters == null) || (parameterValues == null)) { return; } // 确保对象数组个数与参数个数匹配,如果不匹配,抛出一个异常. if (commandParameters.Length != parameterValues.Length) { throw new ArgumentException("参数值个数与参数不匹配."); } // 给参数赋值 for (int i = 0, j = commandParameters.Length; i < j; i++) { // If the current array value derives from IDbDataParameter, then assign its Value property if (parameterValues[i] is IDbDataParameter) { IDbDataParameter paramInstance = (IDbDataParameter)parameterValues[i]; if (paramInstance.Value == null) { commandParameters[i].Value = DBNull.Value; } else { commandParameters[i].Value = paramInstance.Value; } } else if (parameterValues[i] == null) { commandParameters[i].Value = DBNull.Value; } else { commandParameters[i].Value = parameterValues[i]; } } } /// <summary> /// 预处理用户提供的命令,数据库连接/事务/命令类型/参数 /// </summary> /// <param name="command">要处理的SqlCommand</param> /// <param name="connection">数据库连接</param> /// <param name="transaction">一个有效的事务或者是null值</param> /// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param> /// <param name="commandText">存储过程名或都T-SQL命令文本</param> /// <param name="commandParameters">和命令相关联的SqlParameter参数数组,如果没有参数为'null'</param> /// <param name="mustCloseConnection"><c>true</c> 如果连接是打开的,则为true,其它情况下为false.</param> private static void PrepareCommand(SqlCommand command, SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, out bool mustCloseConnection) { if (command == null) throw new ArgumentNullException("command"); if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText"); // If the provided connection is not open, we will open it if (connection.State != ConnectionState.Open) { mustCloseConnection = true; connection.Open(); } else { mustCloseConnection = false; } // 给命令分配一个数据库连接. command.Connection = connection; // 设置命令文本(存储过程名或SQL语句) command.CommandText = commandText; // 分配事务 if (transaction != null) { if (transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); command.Transaction = transaction; } // 设置命令类型. command.CommandType = commandType; // 分配命令参数 if (commandParameters != null) { AttachParameters(command, commandParameters); } return; } #endregion 私有构造函数和方法结束 #region ExecuteNonQuery命令 /// <summary> /// 执行指定连接字符串,类型的SqlCommand. /// </summary> /// <remarks> /// 示例: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders"); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param> /// <param name="commandText">存储过程名称或SQL语句</param> /// <returns>返回命令影响的行数</returns> public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText) { return ExecuteNonQuery(connectionString, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 执行指定连接字符串,类型的SqlCommand.如果没有提供参数,不返回结果. /// </summary> /// <remarks> /// 示例: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="commandType">命令类型 (存储过程,命令文本, 其它.)</param> /// <param name="commandText">存储过程名称或SQL语句</param> /// <param name="commandParameters">SqlParameter参数数组</param> /// <returns>返回命令影响的行数</returns> public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); return ExecuteNonQuery(connection, commandType, commandText, commandParameters); } } /// <summary> /// 执行指定连接字符串的存储过程,将对象数组的值赋给存储过程参数, /// 此方法需要在参数缓存方法中探索参数并生成参数. /// </summary> /// <remarks> /// 这个方法没有提供访问输出参数和返回值. /// 示例: /// int result = ExecuteNonQuery(connString, "PublishOrders", 24, 36); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串/param> /// <param name="spName">存储过程名称</param> /// <param name="parameterValues">分配到存储过程输入参数的对象数组</param> /// <returns>返回受影响的行数</returns> public static int ExecuteNonQuery(string connectionString, string spName, params object[] parameterValues) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果存在参数值 if ((parameterValues != null) && (parameterValues.Length > 0)) { // 从探索存储过程参数(加载到缓存)并分配给存储过程参数数组. SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // 给存储过程参数赋值 AssignParameterValues(commandParameters, parameterValues); return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters); } else { // 没有参数情况下 return ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定数据库连接对象的命令 /// </summary> /// <remarks> /// 示例: /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders"); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="commandType">命令类型(存储过程,命令文本或其它.)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <returns>返回影响的行数</returns> public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText) { return ExecuteNonQuery(connection, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 执行指定数据库连接对象的命令 /// </summary> /// <remarks> /// 示例: /// int result = ExecuteNonQuery(conn, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="commandType">命令类型(存储过程,命令文本或其它.)</param> /// <param name="commandText">T存储过程名称或T-SQL语句</param> /// <param name="commandParameters">SqlParamter参数数组</param> /// <returns>返回影响的行数</returns> public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { if (connection == null) throw new ArgumentNullException("connection"); // 创建SqlCommand命令,并进行预处理 SqlCommand cmd = new SqlCommand(); bool mustCloseConnection = false; PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection); // Finally, execute the command int retval = cmd.ExecuteNonQuery(); // 清除参数,以便再次使用. cmd.Parameters.Clear(); if (mustCloseConnection) connection.Close(); return retval; } /// <summary> /// 执行指定数据库连接对象的命令,将对象数组的值赋给存储过程参数. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输出参数和返回值 /// 示例: /// int result = ExecuteNonQuery(conn, "PublishOrders", 24, 36); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="spName">存储过程名</param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> /// <returns>返回影响的行数</returns> public static int ExecuteNonQuery(SqlConnection connection, string spName, params object[] parameterValues) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果有参数值 if ((parameterValues != null) && (parameterValues.Length > 0)) { // 从缓存中加载存储过程参数 SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 给存储过程分配参数值 AssignParameterValues(commandParameters, parameterValues); return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters); } else { return ExecuteNonQuery(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行带事务的SqlCommand. /// </summary> /// <remarks> /// 示例.: /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "PublishOrders"); /// </remarks> /// <param name="transaction">一个有效的数据库连接对象</param> /// <param name="commandType">命令类型(存储过程,命令文本或其它.)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <returns>返回影响的行数/returns> public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText) { return ExecuteNonQuery(transaction, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 执行带事务的SqlCommand(指定参数). /// </summary> /// <remarks> /// 示例: /// int result = ExecuteNonQuery(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="transaction">一个有效的数据库连接对象</param> /// <param name="commandType">命令类型(存储过程,命令文本或其它.)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <param name="commandParameters">SqlParamter参数数组</param> /// <returns>返回影响的行数</returns> public static int ExecuteNonQuery(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // 预处理 SqlCommand cmd = new SqlCommand(); bool mustCloseConnection = false; PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // 执行 int retval = cmd.ExecuteNonQuery(); // 清除参数集,以便再次使用. cmd.Parameters.Clear(); return retval; } /// <summary> /// 执行带事务的SqlCommand(指定参数值). /// </summary> /// <remarks> /// 此方法不提供访问存储过程输出参数和返回值 /// 示例: /// int result = ExecuteNonQuery(conn, trans, "PublishOrders", 24, 36); /// </remarks> /// <param name="transaction">一个有效的数据库连接对象</param> /// <param name="spName">存储过程名</param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> /// <returns>返回受影响的行数</returns> public static int ExecuteNonQuery(SqlTransaction transaction, string spName, params object[] parameterValues) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果有参数值 if ((parameterValues != null) && (parameterValues.Length > 0)) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 给存储过程参数赋值 AssignParameterValues(commandParameters, parameterValues); // 调用重载方法 return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters); } else { // 没有参数值 return ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName); } } #endregion ExecuteNonQuery方法结束 #region ExecuteDataset方法 /// <summary> /// 执行指定数据库连接字符串的命令,返回DataSet. /// </summary> /// <remarks> /// 示例: /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <returns>返回一个包含结果集的DataSet</returns> public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText) { return ExecuteDataset(connectionString, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 执行指定数据库连接字符串的命令,返回DataSet. /// </summary> /// <remarks> /// 示例: /// DataSet ds = ExecuteDataset(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <param name="commandParameters">SqlParamters参数数组</param> /// <returns>返回一个包含结果集的DataSet</returns> public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); // 创建并打开数据库连接对象,操作完成释放对象. using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // 调用指定数据库连接字符串重载方法. return ExecuteDataset(connection, commandType, commandText, commandParameters); } } /// <summary> /// 执行指定数据库连接字符串的命令,直接提供参数值,返回DataSet. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输出参数和返回值. /// 示例: /// DataSet ds = ExecuteDataset(connString, "GetOrders", 24, 36); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="spName">存储过程名</param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> /// <returns>返回一个包含结果集的DataSet</returns> public static DataSet ExecuteDataset(string connectionString, string spName, params object[] parameterValues) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); if ((parameterValues != null) && (parameterValues.Length > 0)) { // 从缓存中检索存储过程参数 SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // 给存储过程参数分配值 AssignParameterValues(commandParameters, parameterValues); return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters); } else { return ExecuteDataset(connectionString, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定数据库连接对象的命令,返回DataSet. /// </summary> /// <remarks> /// 示例: /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名或T-SQL语句</param> /// <returns>返回一个包含结果集的DataSet</returns> public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText) { return ExecuteDataset(connection, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 执行指定数据库连接对象的命令,指定存储过程参数,返回DataSet. /// </summary> /// <remarks> /// 示例: /// DataSet ds = ExecuteDataset(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名或T-SQL语句</param> /// <param name="commandParameters">SqlParamter参数数组</param> /// <returns>返回一个包含结果集的DataSet</returns> public static DataSet ExecuteDataset(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { if (connection == null) throw new ArgumentNullException("connection"); // 预处理 SqlCommand cmd = new SqlCommand(); bool mustCloseConnection = false; PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection); // 创建SqlDataAdapter和DataSet. using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); // 填充DataSet. da.Fill(ds); cmd.Parameters.Clear(); if (mustCloseConnection) connection.Close(); return ds; } } /// <summary> /// 执行指定数据库连接对象的命令,指定参数值,返回DataSet. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输入参数和返回值. /// 示例.: /// DataSet ds = ExecuteDataset(conn, "GetOrders", 24, 36); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="spName">存储过程名</param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> /// <returns>返回一个包含结果集的DataSet</returns> public static DataSet ExecuteDataset(SqlConnection connection, string spName, params object[] parameterValues) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); if ((parameterValues != null) && (parameterValues.Length > 0)) { // 比缓存中加载存储过程参数 SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 给存储过程参数分配值 AssignParameterValues(commandParameters, parameterValues); return ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters); } else { return ExecuteDataset(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定事务的命令,返回DataSet. /// </summary> /// <remarks> /// 示例: /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="transaction">事务</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名或T-SQL语句</param> /// <returns>返回一个包含结果集的DataSet</returns> public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText) { return ExecuteDataset(transaction, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 执行指定事务的命令,指定参数,返回DataSet. /// </summary> /// <remarks> /// 示例: /// DataSet ds = ExecuteDataset(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="transaction">事务</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名或T-SQL语句</param> /// <param name="commandParameters">SqlParamter参数数组</param> /// <returns>返回一个包含结果集的DataSet</returns> public static DataSet ExecuteDataset(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // 预处理 SqlCommand cmd = new SqlCommand(); bool mustCloseConnection = false; PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // 创建 DataAdapter & DataSet using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); da.Fill(ds); cmd.Parameters.Clear(); return ds; } } /// <summary> /// 执行指定事务的命令,指定参数值,返回DataSet. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输入参数和返回值. /// 示例.: /// DataSet ds = ExecuteDataset(trans, "GetOrders", 24, 36); /// </remarks> /// <param name="transaction">事务</param> /// <param name="spName">存储过程名</param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> /// <returns>返回一个包含结果集的DataSet</returns> public static DataSet ExecuteDataset(SqlTransaction transaction, string spName, params object[] parameterValues) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); if ((parameterValues != null) && (parameterValues.Length > 0)) { // 从缓存中加载存储过程参数 SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 给存储过程参数分配值 AssignParameterValues(commandParameters, parameterValues); return ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters); } else { return ExecuteDataset(transaction, CommandType.StoredProcedure, spName); } } public static DataTable ExecuteGetTable(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); cmd.CommandTimeout = 120; using (SqlConnection conn = new SqlConnection(connectionString)) { bool mustCloseConnection = false; PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters, out mustCloseConnection); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); cmd.Parameters.Clear(); return dt; } } #endregion ExecuteDataset数据集命令结束 #region ExecuteReader 数据阅读器 /// <summary> /// 枚举,标识数据库连接是由SqlHelper提供还是由调用者提供 /// </summary> private enum SqlConnectionOwnership { /// <summary>由SqlHelper提供连接</summary> Internal, /// <summary>由调用者提供连接</summary> External } /// <summary> /// 执行指定数据库连接对象的数据阅读器. /// </summary> /// <remarks> /// 如果是SqlHelper打开连接,当连接关闭DataReader也将关闭. /// 如果是调用都打开连接,DataReader由调用都管理. /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="transaction">一个有效的事务,或者为 'null'</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名或T-SQL语句</param> /// <param name="commandParameters">SqlParameters参数数组,如果没有参数则为'null'</param> /// <param name="connectionOwnership">标识数据库连接对象是由调用者提供还是由SqlHelper提供</param> /// <returns>返回包含结果集的SqlDataReader</returns> private static SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership) { if (connection == null) throw new ArgumentNullException("connection"); bool mustCloseConnection = false; // 创建命令 SqlCommand cmd = new SqlCommand(); try { PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // 创建数据阅读器 SqlDataReader dataReader; if (connectionOwnership == SqlConnectionOwnership.External) { dataReader = cmd.ExecuteReader(); } else { dataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } // 清除参数,以便再次使用.. // HACK: There is a problem here, the output parameter values are fletched // when the reader is closed, so if the parameters are detached from the command // then the SqlReader can磘 set its values. // When this happen, the parameters can磘 be used again in other command. bool canClear = true; foreach (SqlParameter commandParameter in cmd.Parameters) { if (commandParameter.Direction != ParameterDirection.Input) canClear = false; } if (canClear) { cmd.Parameters.Clear(); } return dataReader; } catch { if (mustCloseConnection) connection.Close(); throw; } } /// <summary> /// 执行指定数据库连接字符串的数据阅读器. /// </summary> /// <remarks> /// 示例: /// SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名或T-SQL语句</param> /// <returns>返回包含结果集的SqlDataReader</returns> public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText) { return ExecuteReader(connectionString, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 执行指定数据库连接字符串的数据阅读器,指定参数. /// </summary> /// <remarks> /// 示例: /// SqlDataReader dr = ExecuteReader(connString, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名或T-SQL语句</param> /// <param name="commandParameters">SqlParamter参数数组(new SqlParameter("@prodid", 24))</param> /// <returns>返回包含结果集的SqlDataReader</returns> public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); SqlConnection connection = null; try { connection = new SqlConnection(connectionString); connection.Open(); return ExecuteReader(connection, null, commandType, commandText, commandParameters, SqlConnectionOwnership.Internal); } catch { // If we fail to return the SqlDatReader, we need to close the connection ourselves if (connection != null) connection.Close(); throw; } } /// <summary> /// 执行指定数据库连接字符串的数据阅读器,指定参数值. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输出参数和返回值参数. /// 示例: /// SqlDataReader dr = ExecuteReader(connString, "GetOrders", 24, 36); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="spName">存储过程名</param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> /// <returns>返回包含结果集的SqlDataReader</returns> public static SqlDataReader ExecuteReader(string connectionString, string spName, params object[] parameterValues) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); if ((parameterValues != null) && (parameterValues.Length > 0)) { SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); AssignParameterValues(commandParameters, parameterValues); return ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters); } else { return ExecuteReader(connectionString, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定数据库连接对象的数据阅读器. /// </summary> /// <remarks> /// 示例: /// SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名或T-SQL语句</param> /// <returns>返回包含结果集的SqlDataReader</returns> public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText) { return ExecuteReader(connection, commandType, commandText, (SqlParameter[])null); } /// <summary> /// [调用者方式]执行指定数据库连接对象的数据阅读器,指定参数. /// </summary> /// <remarks> /// 示例: /// SqlDataReader dr = ExecuteReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandParameters">SqlParamter参数数组</param> /// <returns>返回包含结果集的SqlDataReader</returns> public static SqlDataReader ExecuteReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { return ExecuteReader(connection, (SqlTransaction)null, commandType, commandText, commandParameters, SqlConnectionOwnership.External); } /// <summary> /// [调用者方式]执行指定数据库连接对象的数据阅读器,指定参数值. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输出参数和返回值参数. /// 示例: /// SqlDataReader dr = ExecuteReader(conn, "GetOrders", 24, 36); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="spName">T存储过程名</param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> /// <returns>返回包含结果集的SqlDataReader</returns> public static SqlDataReader ExecuteReader(SqlConnection connection, string spName, params object[] parameterValues) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); if ((parameterValues != null) && (parameterValues.Length > 0)) { SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); AssignParameterValues(commandParameters, parameterValues); return ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters); } else { return ExecuteReader(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// [调用者方式]执行指定数据库事务的数据阅读器,指定参数值. /// </summary> /// <remarks> /// 示例: /// SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="transaction">一个有效的连接事务</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <returns>返回包含结果集的SqlDataReader</returns> public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText) { return ExecuteReader(transaction, commandType, commandText, (SqlParameter[])null); } /// <summary> /// [调用者方式]执行指定数据库事务的数据阅读器,指定参数. /// </summary> /// <remarks> /// 示例: /// SqlDataReader dr = ExecuteReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="transaction">一个有效的连接事务</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <param name="commandParameters">分配给命令的SqlParamter参数数组</param> /// <returns>返回包含结果集的SqlDataReader</returns> public static SqlDataReader ExecuteReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); return ExecuteReader(transaction.Connection, transaction, commandType, commandText, commandParameters, SqlConnectionOwnership.External); } /// <summary> /// [调用者方式]执行指定数据库事务的数据阅读器,指定参数值. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输出参数和返回值参数. /// /// 示例: /// SqlDataReader dr = ExecuteReader(trans, "GetOrders", 24, 36); /// </remarks> /// <param name="transaction">一个有效的连接事务</param> /// <param name="spName">存储过程名称</param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> /// <returns>返回包含结果集的SqlDataReader</returns> public static SqlDataReader ExecuteReader(SqlTransaction transaction, string spName, params object[] parameterValues) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果有参数值 if ((parameterValues != null) && (parameterValues.Length > 0)) { SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); AssignParameterValues(commandParameters, parameterValues); return ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters); } else { // 没有参数值 return ExecuteReader(transaction, CommandType.StoredProcedure, spName); } } #endregion ExecuteReader数据阅读器 #region ExecuteScalar 返回结果集中的第一行第一列 /// <summary> /// 执行指定数据库连接字符串的命令,返回结果集中的第一行第一列. /// </summary> /// <remarks> /// 示例: /// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount"); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <returns>返回结果集中的第一行第一列</returns> public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText) { // 执行参数为空的方法 return ExecuteScalar(connectionString, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 执行指定数据库连接字符串的命令,指定参数,返回结果集中的第一行第一列. /// </summary> /// <remarks> /// 示例: /// int orderCount = (int)ExecuteScalar(connString, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <param name="commandParameters">分配给命令的SqlParamter参数数组</param> /// <returns>返回结果集中的第一行第一列</returns> public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); // 创建并打开数据库连接对象,操作完成释放对象. using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // 调用指定数据库连接字符串重载方法. return ExecuteScalar(connection, commandType, commandText, commandParameters); } } /// <summary> /// 执行指定数据库连接字符串的命令,指定参数值,返回结果集中的第一行第一列. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输出参数和返回值参数. /// /// 示例: /// int orderCount = (int)ExecuteScalar(connString, "GetOrderCount", 24, 36); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="spName">存储过程名称</param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> /// <returns>返回结果集中的第一行第一列</returns> public static object ExecuteScalar(string connectionString, string spName, params object[] parameterValues) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果有参数值 if ((parameterValues != null) && (parameterValues.Length > 0)) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // 给存储过程参数赋值 AssignParameterValues(commandParameters, parameterValues); // 调用重载方法 return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters); } else { // 没有参数值 return ExecuteScalar(connectionString, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定数据库连接对象的命令,返回结果集中的第一行第一列. /// </summary> /// <remarks> /// 示例: /// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount"); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <returns>返回结果集中的第一行第一列</returns> public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText) { // 执行参数为空的方法 return ExecuteScalar(connection, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 执行指定数据库连接对象的命令,指定参数,返回结果集中的第一行第一列. /// </summary> /// <remarks> /// 示例: /// int orderCount = (int)ExecuteScalar(conn, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <param name="commandParameters">分配给命令的SqlParamter参数数组</param> /// <returns>返回结果集中的第一行第一列</returns> public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { if (connection == null) throw new ArgumentNullException("connection"); // 创建SqlCommand命令,并进行预处理 SqlCommand cmd = new SqlCommand(); bool mustCloseConnection = false; PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection); // 执行SqlCommand命令,并返回结果. object retval = cmd.ExecuteScalar(); // 清除参数,以便再次使用. cmd.Parameters.Clear(); if (mustCloseConnection) connection.Close(); return retval; } /// <summary> /// 执行指定数据库连接对象的命令,指定参数值,返回结果集中的第一行第一列. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输出参数和返回值参数. /// /// 示例: /// int orderCount = (int)ExecuteScalar(conn, "GetOrderCount", 24, 36); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="spName">存储过程名称</param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> /// <returns>返回结果集中的第一行第一列</returns> public static object ExecuteScalar(SqlConnection connection, string spName, params object[] parameterValues) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果有参数值 if ((parameterValues != null) && (parameterValues.Length > 0)) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 给存储过程参数赋值 AssignParameterValues(commandParameters, parameterValues); // 调用重载方法 return ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters); } else { // 没有参数值 return ExecuteScalar(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定数据库事务的命令,返回结果集中的第一行第一列. /// </summary> /// <remarks> /// 示例: /// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount"); /// </remarks> /// <param name="transaction">一个有效的连接事务</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <returns>返回结果集中的第一行第一列</returns> public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText) { // 执行参数为空的方法 return ExecuteScalar(transaction, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 执行指定数据库事务的命令,指定参数,返回结果集中的第一行第一列. /// </summary> /// <remarks> /// 示例: /// int orderCount = (int)ExecuteScalar(trans, CommandType.StoredProcedure, "GetOrderCount", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="transaction">一个有效的连接事务</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <param name="commandParameters">分配给命令的SqlParamter参数数组</param> /// <returns>返回结果集中的第一行第一列</returns> public static object ExecuteScalar(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // 创建SqlCommand命令,并进行预处理 SqlCommand cmd = new SqlCommand(); bool mustCloseConnection = false; PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // 执行SqlCommand命令,并返回结果. object retval = cmd.ExecuteScalar(); // 清除参数,以便再次使用. cmd.Parameters.Clear(); return retval; } /// <summary> /// 执行指定数据库事务的命令,指定参数值,返回结果集中的第一行第一列. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输出参数和返回值参数. /// /// 示例: /// int orderCount = (int)ExecuteScalar(trans, "GetOrderCount", 24, 36); /// </remarks> /// <param name="transaction">一个有效的连接事务</param> /// <param name="spName">存储过程名称</param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> /// <returns>返回结果集中的第一行第一列</returns> public static object ExecuteScalar(SqlTransaction transaction, string spName, params object[] parameterValues) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果有参数值 if ((parameterValues != null) && (parameterValues.Length > 0)) { // PPull the parameters for this stored procedure from the parameter cache () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 给存储过程参数赋值 AssignParameterValues(commandParameters, parameterValues); // 调用重载方法 return ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters); } else { // 没有参数值 return ExecuteScalar(transaction, CommandType.StoredProcedure, spName); } } #endregion ExecuteScalar #region ExecuteXmlReader XML阅读器 /// <summary> /// 执行指定数据库连接对象的SqlCommand命令,并产生一个XmlReader对象做为结果集返回. /// </summary> /// <remarks> /// 示例: /// XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句 using "FOR XML AUTO"</param> /// <returns>返回XmlReader结果集对象.</returns> public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText) { // 执行参数为空的方法 return ExecuteXmlReader(connection, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 执行指定数据库连接对象的SqlCommand命令,并产生一个XmlReader对象做为结果集返回,指定参数. /// </summary> /// <remarks> /// 示例: /// XmlReader r = ExecuteXmlReader(conn, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句 using "FOR XML AUTO"</param> /// <param name="commandParameters">分配给命令的SqlParamter参数数组</param> /// <returns>返回XmlReader结果集对象.</returns> public static XmlReader ExecuteXmlReader(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { if (connection == null) throw new ArgumentNullException("connection"); bool mustCloseConnection = false; // 创建SqlCommand命令,并进行预处理 SqlCommand cmd = new SqlCommand(); try { PrepareCommand(cmd, connection, (SqlTransaction)null, commandType, commandText, commandParameters, out mustCloseConnection); // 执行命令 XmlReader retval = cmd.ExecuteXmlReader(); // 清除参数,以便再次使用. cmd.Parameters.Clear(); return retval; } catch { if (mustCloseConnection) connection.Close(); throw; } } /// <summary> /// 执行指定数据库连接对象的SqlCommand命令,并产生一个XmlReader对象做为结果集返回,指定参数值. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输出参数和返回值参数. /// /// 示例: /// XmlReader r = ExecuteXmlReader(conn, "GetOrders", 24, 36); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="spName">存储过程名称 using "FOR XML AUTO"</param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> /// <returns>返回XmlReader结果集对象.</returns> public static XmlReader ExecuteXmlReader(SqlConnection connection, string spName, params object[] parameterValues) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果有参数值 if ((parameterValues != null) && (parameterValues.Length > 0)) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 给存储过程参数赋值 AssignParameterValues(commandParameters, parameterValues); // 调用重载方法 return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters); } else { // 没有参数值 return ExecuteXmlReader(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定数据库事务的SqlCommand命令,并产生一个XmlReader对象做为结果集返回. /// </summary> /// <remarks> /// 示例: /// XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders"); /// </remarks> /// <param name="transaction">一个有效的连接事务</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句 using "FOR XML AUTO"</param> /// <returns>返回XmlReader结果集对象.</returns> public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText) { // 执行参数为空的方法 return ExecuteXmlReader(transaction, commandType, commandText, (SqlParameter[])null); } /// <summary> /// 执行指定数据库事务的SqlCommand命令,并产生一个XmlReader对象做为结果集返回,指定参数. /// </summary> /// <remarks> /// 示例: /// XmlReader r = ExecuteXmlReader(trans, CommandType.StoredProcedure, "GetOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="transaction">一个有效的连接事务</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句 using "FOR XML AUTO"</param> /// <param name="commandParameters">分配给命令的SqlParamter参数数组</param> /// <returns>返回XmlReader结果集对象.</returns> public static XmlReader ExecuteXmlReader(SqlTransaction transaction, CommandType commandType, string commandText, params SqlParameter[] commandParameters) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); // 创建SqlCommand命令,并进行预处理 SqlCommand cmd = new SqlCommand(); bool mustCloseConnection = false; PrepareCommand(cmd, transaction.Connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // 执行命令 XmlReader retval = cmd.ExecuteXmlReader(); // 清除参数,以便再次使用. cmd.Parameters.Clear(); return retval; } /// <summary> /// 执行指定数据库事务的SqlCommand命令,并产生一个XmlReader对象做为结果集返回,指定参数值. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输出参数和返回值参数. /// /// 示例: /// XmlReader r = ExecuteXmlReader(trans, "GetOrders", 24, 36); /// </remarks> /// <param name="transaction">一个有效的连接事务</param> /// <param name="spName">存储过程名称</param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> /// <returns>返回一个包含结果集的DataSet.</returns> public static XmlReader ExecuteXmlReader(SqlTransaction transaction, string spName, params object[] parameterValues) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果有参数值 if ((parameterValues != null) && (parameterValues.Length > 0)) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 给存储过程参数赋值 AssignParameterValues(commandParameters, parameterValues); // 调用重载方法 return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters); } else { // 没有参数值 return ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName); } } #endregion ExecuteXmlReader 阅读器结束 #region FillDataset 填充数据集 /// <summary> /// 执行指定数据库连接字符串的命令,映射数据表并填充数据集. /// </summary> /// <remarks> /// 示例: /// FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <param name="dataSet">要填充结果集的DataSet实例</param> /// <param name="tableNames">表映射的数据表数组 /// 用户定义的表名 (可有是实际的表名.)</param> public static void FillDataset(string connectionString, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (dataSet == null) throw new ArgumentNullException("dataSet"); // 创建并打开数据库连接对象,操作完成释放对象. using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // 调用指定数据库连接字符串重载方法. FillDataset(connection, commandType, commandText, dataSet, tableNames); } } /// <summary> /// 执行指定数据库连接字符串的命令,映射数据表并填充数据集.指定命令参数. /// </summary> /// <remarks> /// 示例: /// FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <param name="commandParameters">分配给命令的SqlParamter参数数组</param> /// <param name="dataSet">要填充结果集的DataSet实例</param> /// <param name="tableNames">表映射的数据表数组 /// 用户定义的表名 (可有是实际的表名.) /// </param> public static void FillDataset(string connectionString, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames, params SqlParameter[] commandParameters) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (dataSet == null) throw new ArgumentNullException("dataSet"); // 创建并打开数据库连接对象,操作完成释放对象. using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // 调用指定数据库连接字符串重载方法. FillDataset(connection, commandType, commandText, dataSet, tableNames, commandParameters); } } /// <summary> /// 执行指定数据库连接字符串的命令,映射数据表并填充数据集,指定存储过程参数值. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输出参数和返回值参数. /// /// 示例: /// FillDataset(connString, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, 24); /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="spName">存储过程名称</param> /// <param name="dataSet">要填充结果集的DataSet实例</param> /// <param name="tableNames">表映射的数据表数组 /// 用户定义的表名 (可有是实际的表名.) /// </param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> public static void FillDataset(string connectionString, string spName, DataSet dataSet, string[] tableNames, params object[] parameterValues) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (dataSet == null) throw new ArgumentNullException("dataSet"); // 创建并打开数据库连接对象,操作完成释放对象. using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); // 调用指定数据库连接字符串重载方法. FillDataset(connection, spName, dataSet, tableNames, parameterValues); } } /// <summary> /// 执行指定数据库连接对象的命令,映射数据表并填充数据集. /// </summary> /// <remarks> /// 示例: /// FillDataset(conn, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <param name="dataSet">要填充结果集的DataSet实例</param> /// <param name="tableNames">表映射的数据表数组 /// 用户定义的表名 (可有是实际的表名.) /// </param> public static void FillDataset(SqlConnection connection, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames) { FillDataset(connection, commandType, commandText, dataSet, tableNames, null); } /// <summary> /// 执行指定数据库连接对象的命令,映射数据表并填充数据集,指定参数. /// </summary> /// <remarks> /// 示例: /// FillDataset(conn, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <param name="dataSet">要填充结果集的DataSet实例</param> /// <param name="tableNames">表映射的数据表数组 /// 用户定义的表名 (可有是实际的表名.) /// </param> /// <param name="commandParameters">分配给命令的SqlParamter参数数组</param> public static void FillDataset(SqlConnection connection, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames, params SqlParameter[] commandParameters) { FillDataset(connection, null, commandType, commandText, dataSet, tableNames, commandParameters); } /// <summary> /// 执行指定数据库连接对象的命令,映射数据表并填充数据集,指定存储过程参数值. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输出参数和返回值参数. /// /// 示例: /// FillDataset(conn, "GetOrders", ds, new string[] {"orders"}, 24, 36); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="spName">存储过程名称</param> /// <param name="dataSet">要填充结果集的DataSet实例</param> /// <param name="tableNames">表映射的数据表数组 /// 用户定义的表名 (可有是实际的表名.) /// </param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> public static void FillDataset(SqlConnection connection, string spName, DataSet dataSet, string[] tableNames, params object[] parameterValues) { if (connection == null) throw new ArgumentNullException("connection"); if (dataSet == null) throw new ArgumentNullException("dataSet"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果有参数值 if ((parameterValues != null) && (parameterValues.Length > 0)) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 给存储过程参数赋值 AssignParameterValues(commandParameters, parameterValues); // 调用重载方法 FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters); } else { // 没有参数值 FillDataset(connection, CommandType.StoredProcedure, spName, dataSet, tableNames); } } /// <summary> /// 执行指定数据库事务的命令,映射数据表并填充数据集. /// </summary> /// <remarks> /// 示例: /// FillDataset(trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}); /// </remarks> /// <param name="transaction">一个有效的连接事务</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <param name="dataSet">要填充结果集的DataSet实例</param> /// <param name="tableNames">表映射的数据表数组 /// 用户定义的表名 (可有是实际的表名.) /// </param> public static void FillDataset(SqlTransaction transaction, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames) { FillDataset(transaction, commandType, commandText, dataSet, tableNames, null); } /// <summary> /// 执行指定数据库事务的命令,映射数据表并填充数据集,指定参数. /// </summary> /// <remarks> /// 示例: /// FillDataset(trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="transaction">一个有效的连接事务</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <param name="dataSet">要填充结果集的DataSet实例</param> /// <param name="tableNames">表映射的数据表数组 /// 用户定义的表名 (可有是实际的表名.) /// </param> /// <param name="commandParameters">分配给命令的SqlParamter参数数组</param> public static void FillDataset(SqlTransaction transaction, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames, params SqlParameter[] commandParameters) { FillDataset(transaction.Connection, transaction, commandType, commandText, dataSet, tableNames, commandParameters); } /// <summary> /// 执行指定数据库事务的命令,映射数据表并填充数据集,指定存储过程参数值. /// </summary> /// <remarks> /// 此方法不提供访问存储过程输出参数和返回值参数. /// /// 示例: /// FillDataset(trans, "GetOrders", ds, new string[]{"orders"}, 24, 36); /// </remarks> /// <param name="transaction">一个有效的连接事务</param> /// <param name="spName">存储过程名称</param> /// <param name="dataSet">要填充结果集的DataSet实例</param> /// <param name="tableNames">表映射的数据表数组 /// 用户定义的表名 (可有是实际的表名.) /// </param> /// <param name="parameterValues">分配给存储过程输入参数的对象数组</param> public static void FillDataset(SqlTransaction transaction, string spName, DataSet dataSet, string[] tableNames, params object[] parameterValues) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); if (dataSet == null) throw new ArgumentNullException("dataSet"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果有参数值 if ((parameterValues != null) && (parameterValues.Length > 0)) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 给存储过程参数赋值 AssignParameterValues(commandParameters, parameterValues); // 调用重载方法 FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames, commandParameters); } else { // 没有参数值 FillDataset(transaction, CommandType.StoredProcedure, spName, dataSet, tableNames); } } /// <summary> /// [私有方法][内部调用]执行指定数据库连接对象/事务的命令,映射数据表并填充数据集,DataSet/TableNames/SqlParameters. /// </summary> /// <remarks> /// 示例: /// FillDataset(conn, trans, CommandType.StoredProcedure, "GetOrders", ds, new string[] {"orders"}, new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="transaction">一个有效的连接事务</param> /// <param name="commandType">命令类型 (存储过程,命令文本或其它)</param> /// <param name="commandText">存储过程名称或T-SQL语句</param> /// <param name="dataSet">要填充结果集的DataSet实例</param> /// <param name="tableNames">表映射的数据表数组 /// 用户定义的表名 (可有是实际的表名.) /// </param> /// <param name="commandParameters">分配给命令的SqlParamter参数数组</param> private static void FillDataset(SqlConnection connection, SqlTransaction transaction, CommandType commandType, string commandText, DataSet dataSet, string[] tableNames, params SqlParameter[] commandParameters) { if (connection == null) throw new ArgumentNullException("connection"); if (dataSet == null) throw new ArgumentNullException("dataSet"); // 创建SqlCommand命令,并进行预处理 SqlCommand command = new SqlCommand(); bool mustCloseConnection = false; PrepareCommand(command, connection, transaction, commandType, commandText, commandParameters, out mustCloseConnection); // 执行命令 using (SqlDataAdapter dataAdapter = new SqlDataAdapter(command)) { // 追加表映射 if (tableNames != null && tableNames.Length > 0) { string tableName = "Table"; for (int index = 0; index < tableNames.Length; index++) { if (tableNames[index] == null || tableNames[index].Length == 0) throw new ArgumentException("The tableNames parameter must contain a list of tables, a value was provided as null or empty string.", "tableNames"); dataAdapter.TableMappings.Add(tableName, tableNames[index]); tableName += (index + 1).ToString(); } } // 填充数据集使用默认表名称 dataAdapter.Fill(dataSet); // 清除参数,以便再次使用. command.Parameters.Clear(); } if (mustCloseConnection) connection.Close(); } #endregion #region UpdateDataset 更新数据集 /// <summary> /// 执行数据集更新到数据库,指定inserted, updated, or deleted命令. /// </summary> /// <remarks> /// 示例: /// UpdateDataset(conn, insertCommand, deleteCommand, updateCommand, dataSet, "Order"); /// </remarks> /// <param name="insertCommand">[追加记录]一个有效的T-SQL语句或存储过程</param> /// <param name="deleteCommand">[删除记录]一个有效的T-SQL语句或存储过程</param> /// <param name="updateCommand">[更新记录]一个有效的T-SQL语句或存储过程</param> /// <param name="dataSet">要更新到数据库的DataSet</param> /// <param name="tableName">要更新到数据库的DataTable</param> public static void UpdateDataset(SqlCommand insertCommand, SqlCommand deleteCommand, SqlCommand updateCommand, DataSet dataSet, string tableName) { if (insertCommand == null) throw new ArgumentNullException("insertCommand"); if (deleteCommand == null) throw new ArgumentNullException("deleteCommand"); if (updateCommand == null) throw new ArgumentNullException("updateCommand"); if (tableName == null || tableName.Length == 0) throw new ArgumentNullException("tableName"); // 创建SqlDataAdapter,当操作完成后释放. using (SqlDataAdapter dataAdapter = new SqlDataAdapter()) { // 设置数据适配器命令 dataAdapter.UpdateCommand = updateCommand; dataAdapter.InsertCommand = insertCommand; dataAdapter.DeleteCommand = deleteCommand; // 更新数据集改变到数据库 dataAdapter.Update(dataSet, tableName); // 提交所有改变到数据集. dataSet.AcceptChanges(); } } #endregion #region CreateCommand 创建一条SqlCommand命令 /// <summary> /// 创建SqlCommand命令,指定数据库连接对象,存储过程名和参数. /// </summary> /// <remarks> /// 示例: /// SqlCommand command = CreateCommand(conn, "AddCustomer", "CustomerID", "CustomerName"); /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="spName">存储过程名称</param> /// <param name="sourceColumns">源表的列名称数组</param> /// <returns>返回SqlCommand命令</returns> public static SqlCommand CreateCommand(SqlConnection connection, string spName, params string[] sourceColumns) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 创建命令 SqlCommand cmd = new SqlCommand(spName, connection); cmd.CommandType = CommandType.StoredProcedure; // 如果有参数值 if ((sourceColumns != null) && (sourceColumns.Length > 0)) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 将源表的列到映射到DataSet命令中. for (int index = 0; index < sourceColumns.Length; index++) commandParameters[index].SourceColumn = sourceColumns[index]; // Attach the discovered parameters to the SqlCommand object AttachParameters(cmd, commandParameters); } return cmd; } #endregion #region ExecuteNonQueryTypedParams 类型化参数(DataRow) /// <summary> /// 执行指定连接数据库连接字符串的存储过程,使用DataRow做为参数值,返回受影响的行数. /// </summary> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="spName">存储过程名称</param> /// <param name="dataRow">使用DataRow作为参数值</param> /// <returns>返回影响的行数</returns> public static int ExecuteNonQueryTypedParams(String connectionString, String spName, DataRow dataRow) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化. if (dataRow != null && dataRow.ItemArray.Length > 0) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // 分配参数值 AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName, commandParameters); } else { return SqlHelper.ExecuteNonQuery(connectionString, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定连接数据库连接对象的存储过程,使用DataRow做为参数值,返回受影响的行数. /// </summary> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="spName">存储过程名称</param> /// <param name="dataRow">使用DataRow作为参数值</param> /// <returns>返回影响的行数</returns> public static int ExecuteNonQueryTypedParams(SqlConnection connection, String spName, DataRow dataRow) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化. if (dataRow != null && dataRow.ItemArray.Length > 0) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 分配参数值 AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName, commandParameters); } else { return SqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定连接数据库事物的存储过程,使用DataRow做为参数值,返回受影响的行数. /// </summary> /// <param name="transaction">一个有效的连接事务 object</param> /// <param name="spName">存储过程名称</param> /// <param name="dataRow">使用DataRow作为参数值</param> /// <returns>返回影响的行数</returns> public static int ExecuteNonQueryTypedParams(SqlTransaction transaction, String spName, DataRow dataRow) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // Sf the row has values, the store procedure parameters must be initialized if (dataRow != null && dataRow.ItemArray.Length > 0) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 分配参数值 AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName, commandParameters); } else { return SqlHelper.ExecuteNonQuery(transaction, CommandType.StoredProcedure, spName); } } #endregion #region ExecuteDatasetTypedParams 类型化参数(DataRow) /// <summary> /// 执行指定连接数据库连接字符串的存储过程,使用DataRow做为参数值,返回DataSet. /// </summary> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="spName">存储过程名称</param> /// <param name="dataRow">使用DataRow作为参数值</param> /// <returns>返回一个包含结果集的DataSet.</returns> public static DataSet ExecuteDatasetTypedParams(string connectionString, String spName, DataRow dataRow) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); //如果row有值,存储过程必须初始化. if (dataRow != null && dataRow.ItemArray.Length > 0) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // 分配参数值 AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName, commandParameters); } else { return SqlHelper.ExecuteDataset(connectionString, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定连接数据库连接对象的存储过程,使用DataRow做为参数值,返回DataSet. /// </summary> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="spName">存储过程名称</param> /// <param name="dataRow">使用DataRow作为参数值</param> /// <returns>返回一个包含结果集的DataSet.</returns> /// public static DataSet ExecuteDatasetTypedParams(SqlConnection connection, String spName, DataRow dataRow) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化. if (dataRow != null && dataRow.ItemArray.Length > 0) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 分配参数值 AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName, commandParameters); } else { return SqlHelper.ExecuteDataset(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定连接数据库事务的存储过程,使用DataRow做为参数值,返回DataSet. /// </summary> /// <param name="transaction">一个有效的连接事务 object</param> /// <param name="spName">存储过程名称</param> /// <param name="dataRow">使用DataRow作为参数值</param> /// <returns>返回一个包含结果集的DataSet.</returns> public static DataSet ExecuteDatasetTypedParams(SqlTransaction transaction, String spName, DataRow dataRow) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化. if (dataRow != null && dataRow.ItemArray.Length > 0) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 分配参数值 AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName, commandParameters); } else { return SqlHelper.ExecuteDataset(transaction, CommandType.StoredProcedure, spName); } } #endregion #region ExecuteReaderTypedParams 类型化参数(DataRow) /// <summary> /// 执行指定连接数据库连接字符串的存储过程,使用DataRow做为参数值,返回DataReader. /// </summary> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="spName">存储过程名称</param> /// <param name="dataRow">使用DataRow作为参数值</param> /// <returns>返回包含结果集的SqlDataReader</returns> public static SqlDataReader ExecuteReaderTypedParams(String connectionString, String spName, DataRow dataRow) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化. if (dataRow != null && dataRow.ItemArray.Length > 0) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // 分配参数值 AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName, commandParameters); } else { return SqlHelper.ExecuteReader(connectionString, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定连接数据库连接对象的存储过程,使用DataRow做为参数值,返回DataReader. /// </summary> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="spName">存储过程名称</param> /// <param name="dataRow">使用DataRow作为参数值</param> /// <returns>返回包含结果集的SqlDataReader</returns> public static SqlDataReader ExecuteReaderTypedParams(SqlConnection connection, String spName, DataRow dataRow) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化. if (dataRow != null && dataRow.ItemArray.Length > 0) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 分配参数值 AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName, commandParameters); } else { return SqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定连接数据库事物的存储过程,使用DataRow做为参数值,返回DataReader. /// </summary> /// <param name="transaction">一个有效的连接事务 object</param> /// <param name="spName">存储过程名称</param> /// <param name="dataRow">使用DataRow作为参数值</param> /// <returns>返回包含结果集的SqlDataReader</returns> public static SqlDataReader ExecuteReaderTypedParams(SqlTransaction transaction, String spName, DataRow dataRow) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化. if (dataRow != null && dataRow.ItemArray.Length > 0) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 分配参数值 AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName, commandParameters); } else { return SqlHelper.ExecuteReader(transaction, CommandType.StoredProcedure, spName); } } #endregion #region ExecuteScalarTypedParams 类型化参数(DataRow) /// <summary> /// 执行指定连接数据库连接字符串的存储过程,使用DataRow做为参数值,返回结果集中的第一行第一列. /// </summary> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="spName">存储过程名称</param> /// <param name="dataRow">使用DataRow作为参数值</param> /// <returns>返回结果集中的第一行第一列</returns> public static object ExecuteScalarTypedParams(String connectionString, String spName, DataRow dataRow) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化. if (dataRow != null && dataRow.ItemArray.Length > 0) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connectionString, spName); // 分配参数值 AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName, commandParameters); } else { return SqlHelper.ExecuteScalar(connectionString, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定连接数据库连接对象的存储过程,使用DataRow做为参数值,返回结果集中的第一行第一列. /// </summary> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="spName">存储过程名称</param> /// <param name="dataRow">使用DataRow作为参数值</param> /// <returns>返回结果集中的第一行第一列</returns> public static object ExecuteScalarTypedParams(SqlConnection connection, String spName, DataRow dataRow) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化. if (dataRow != null && dataRow.ItemArray.Length > 0) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 分配参数值 AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName, commandParameters); } else { return SqlHelper.ExecuteScalar(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定连接数据库事务的存储过程,使用DataRow做为参数值,返回结果集中的第一行第一列. /// </summary> /// <param name="transaction">一个有效的连接事务 object</param> /// <param name="spName">存储过程名称</param> /// <param name="dataRow">使用DataRow作为参数值</param> /// <returns>返回结果集中的第一行第一列</returns> public static object ExecuteScalarTypedParams(SqlTransaction transaction, String spName, DataRow dataRow) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化. if (dataRow != null && dataRow.ItemArray.Length > 0) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 分配参数值 AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName, commandParameters); } else { return SqlHelper.ExecuteScalar(transaction, CommandType.StoredProcedure, spName); } } #endregion #region ExecuteXmlReaderTypedParams 类型化参数(DataRow) /// <summary> /// 执行指定连接数据库连接对象的存储过程,使用DataRow做为参数值,返回XmlReader类型的结果集. /// </summary> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="spName">存储过程名称</param> /// <param name="dataRow">使用DataRow作为参数值</param> /// <returns>返回XmlReader结果集对象.</returns> public static XmlReader ExecuteXmlReaderTypedParams(SqlConnection connection, String spName, DataRow dataRow) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化. if (dataRow != null && dataRow.ItemArray.Length > 0) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(connection, spName); // 分配参数值 AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName, commandParameters); } else { return SqlHelper.ExecuteXmlReader(connection, CommandType.StoredProcedure, spName); } } /// <summary> /// 执行指定连接数据库事务的存储过程,使用DataRow做为参数值,返回XmlReader类型的结果集. /// </summary> /// <param name="transaction">一个有效的连接事务 object</param> /// <param name="spName">存储过程名称</param> /// <param name="dataRow">使用DataRow作为参数值</param> /// <returns>返回XmlReader结果集对象.</returns> public static XmlReader ExecuteXmlReaderTypedParams(SqlTransaction transaction, String spName, DataRow dataRow) { if (transaction == null) throw new ArgumentNullException("transaction"); if (transaction != null && transaction.Connection == null) throw new ArgumentException("The transaction was rollbacked or commited, please provide an open transaction.", "transaction"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); // 如果row有值,存储过程必须初始化. if (dataRow != null && dataRow.ItemArray.Length > 0) { // 从缓存中加载存储过程参数,如果缓存中不存在则从数据库中检索参数信息并加载到缓存中. () SqlParameter[] commandParameters = SqlHelperParameterCache.GetSpParameterSet(transaction.Connection, spName); // 分配参数值 AssignParameterValues(commandParameters, dataRow); return SqlHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName, commandParameters); } else { return SqlHelper.ExecuteXmlReader(transaction, CommandType.StoredProcedure, spName); } } #endregion public static void SqlBulkCopyByDatatable(string TableName, DataTable dt, string connectionString, List<string> column = null) { using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString)) { sqlbulkcopy.BulkCopyTimeout = 500; try { sqlbulkcopy.DestinationTableName = TableName; for (int i = 0; i < dt.Columns.Count; i++) { if (column != null && column.Contains(dt.Columns[i].ColumnName)) { sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName); } } sqlbulkcopy.WriteToServer(dt); } catch (System.Exception ex) { Loger.LogErr(ex); } } } //sourcecolumns, destcolumns长度一致对应 public static void SqlBulkCopyByDatatable(string TableName, DataTable dt, string connectionString, List<string> sourcecolumns, List<string> destcolumns) { using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString)) { sqlbulkcopy.BulkCopyTimeout = 500; try { sqlbulkcopy.DestinationTableName = TableName; if (sourcecolumns != null) { int i = 0; foreach (var column in sourcecolumns) { sqlbulkcopy.ColumnMappings.Add(column, destcolumns[i]); i++; } } sqlbulkcopy.WriteToServer(dt); } catch (System.Exception ex) { Loger.LogErr(ex); } } } } /// <summary> /// SqlHelperParameterCache提供缓存存储过程参数,并能够在运行时从存储过程中探索参数. /// </summary> public sealed class SqlHelperParameterCache { #region 私有方法,字段,构造函数 // 私有构造函数,妨止类被实例化. private SqlHelperParameterCache() { } // 这个方法要注意 private static Hashtable paramCache = Hashtable.Synchronized(new Hashtable()); /// <summary> /// 探索运行时的存储过程,返回SqlParameter参数数组. /// 初始化参数值为 DBNull.Value. /// </summary> /// <param name="connection">一个有效的数据库连接</param> /// <param name="spName">存储过程名称</param> /// <param name="includeReturnValueParameter">是否包含返回值参数</param> /// <returns>返回SqlParameter参数数组</returns> private static SqlParameter[] DiscoverSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); SqlCommand cmd = new SqlCommand(spName, connection); cmd.CommandType = CommandType.StoredProcedure; connection.Open(); // 检索cmd指定的存储过程的参数信息,并填充到cmd的Parameters参数集中. SqlCommandBuilder.DeriveParameters(cmd); connection.Close(); // 如果不包含返回值参数,将参数集中的每一个参数删除. if (!includeReturnValueParameter) { cmd.Parameters.RemoveAt(0); } // 创建参数数组 SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count]; // 将cmd的Parameters参数集复制到discoveredParameters数组. cmd.Parameters.CopyTo(discoveredParameters, 0); // 初始化参数值为 DBNull.Value. foreach (SqlParameter discoveredParameter in discoveredParameters) { discoveredParameter.Value = DBNull.Value; } return discoveredParameters; } /// <summary> /// SqlParameter参数数组的深层拷贝. /// </summary> /// <param name="originalParameters">原始参数数组</param> /// <returns>返回一个同样的参数数组</returns> private static SqlParameter[] CloneParameters(SqlParameter[] originalParameters) { SqlParameter[] clonedParameters = new SqlParameter[originalParameters.Length]; for (int i = 0, j = originalParameters.Length; i < j; i++) { clonedParameters[i] = (SqlParameter)((ICloneable)originalParameters[i]).Clone(); } return clonedParameters; } #endregion 私有方法,字段,构造函数结束 #region 缓存方法 /// <summary> /// 追加参数数组到缓存. /// </summary> /// <param name="connectionString">一个有效的数据库连接字符串</param> /// <param name="commandText">存储过程名或SQL语句</param> /// <param name="commandParameters">要缓存的参数数组</param> public static void CacheParameterSet(string connectionString, string commandText, params SqlParameter[] commandParameters) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText"); string hashKey = connectionString + ":" + commandText; paramCache[hashKey] = commandParameters; } /// <summary> /// 从缓存中获取参数数组. /// </summary> /// <param name="connectionString">一个有效的数据库连接字符</param> /// <param name="commandText">存储过程名或SQL语句</param> /// <returns>参数数组</returns> public static SqlParameter[] GetCachedParameterSet(string connectionString, string commandText) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (commandText == null || commandText.Length == 0) throw new ArgumentNullException("commandText"); string hashKey = connectionString + ":" + commandText; SqlParameter[] cachedParameters = paramCache[hashKey] as SqlParameter[]; if (cachedParameters == null) { return null; } else { return CloneParameters(cachedParameters); } } #endregion 缓存方法结束 #region 检索指定的存储过程的参数集 /// <summary> /// 返回指定的存储过程的参数集 /// </summary> /// <remarks> /// 这个方法将查询数据库,并将信息存储到缓存. /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符</param> /// <param name="spName">存储过程名</param> /// <returns>返回SqlParameter参数数组</returns> public static SqlParameter[] GetSpParameterSet(string connectionString, string spName) { return GetSpParameterSet(connectionString, spName, false); } /// <summary> /// 返回指定的存储过程的参数集 /// </summary> /// <remarks> /// 这个方法将查询数据库,并将信息存储到缓存. /// </remarks> /// <param name="connectionString">一个有效的数据库连接字符.</param> /// <param name="spName">存储过程名</param> /// <param name="includeReturnValueParameter">是否包含返回值参数</param> /// <returns>返回SqlParameter参数数组</returns> public static SqlParameter[] GetSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter) { if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); using (SqlConnection connection = new SqlConnection(connectionString)) { return GetSpParameterSetInternal(connection, spName, includeReturnValueParameter); } } /// <summary> /// [内部]返回指定的存储过程的参数集(使用连接对象). /// </summary> /// <remarks> /// 这个方法将查询数据库,并将信息存储到缓存. /// </remarks> /// <param name="connection">一个有效的数据库连接字符</param> /// <param name="spName">存储过程名</param> /// <returns>返回SqlParameter参数数组</returns> internal static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName) { return GetSpParameterSet(connection, spName, false); } /// <summary> /// [内部]返回指定的存储过程的参数集(使用连接对象) /// </summary> /// <remarks> /// 这个方法将查询数据库,并将信息存储到缓存. /// </remarks> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="spName">存储过程名</param> /// <param name="includeReturnValueParameter"> /// 是否包含返回值参数 /// </param> /// <returns>返回SqlParameter参数数组</returns> internal static SqlParameter[] GetSpParameterSet(SqlConnection connection, string spName, bool includeReturnValueParameter) { if (connection == null) throw new ArgumentNullException("connection"); using (SqlConnection clonedConnection = (SqlConnection)((ICloneable)connection).Clone()) { return GetSpParameterSetInternal(clonedConnection, spName, includeReturnValueParameter); } } /// <summary> /// [私有]返回指定的存储过程的参数集(使用连接对象) /// </summary> /// <param name="connection">一个有效的数据库连接对象</param> /// <param name="spName">存储过程名</param> /// <param name="includeReturnValueParameter">是否包含返回值参数</param> /// <returns>返回SqlParameter参数数组</returns> private static SqlParameter[] GetSpParameterSetInternal(SqlConnection connection, string spName, bool includeReturnValueParameter) { if (connection == null) throw new ArgumentNullException("connection"); if (spName == null || spName.Length == 0) throw new ArgumentNullException("spName"); string hashKey = connection.ConnectionString + ":" + spName + (includeReturnValueParameter ? ":include ReturnValue Parameter" : ""); SqlParameter[] cachedParameters; cachedParameters = paramCache[hashKey] as SqlParameter[]; if (cachedParameters == null) { SqlParameter[] spParameters = DiscoverSpParameterSet(connection, spName, includeReturnValueParameter); paramCache[hashKey] = spParameters; cachedParameters = spParameters; } return CloneParameters(cachedParameters); } #endregion 参数集检索结束 } /// <summary> /// The SqlHelper class is intended to encapsulate high performance, /// scalable best practices for common uses of SqlClient. /// </summary> public abstract class SqlHelperDB { // Hashtable to store cached parameters private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable()); #region AddParameters public static object CheckForNullString(string text) { if (text == null || text.Trim().Length == 0) { return System.DBNull.Value; } else { return text; } } /// <summary> /// this method will add a input sql parameter /// </summary> /// <param name="ParamName"></param> /// <param name="Value"></param> /// <returns></returns> public static SqlParameter MakeInParam(string ParamName, object Value) { return new SqlParameter(ParamName, Value); } /// <summary> /// this method will add a Input SqlParameter /// </summary> /// <param name="ParamName">Name of parameter.</param> /// <param name="DbType">Parameter type.</param> /// <param name="Size">Parameter size.</param> /// <param name="Value">Parameter value.</param> /// <returns>New parameter.</returns> public static SqlParameter MakeInParam(string ParamName, SqlDbType DbType, int Size, object Value) { return MakeParam(ParamName, DbType, Size, ParameterDirection.Input, Value); } /// <summary> /// this method will add a Output SqlParameter /// </summary> /// <param name="ParamName">Name of parameter.</param> /// <param name="DbType">Parameter type.</param> /// <param name="Size">Parameter size.</param> /// <returns>New parameter.</returns> public static SqlParameter MakeOutParam(string ParamName, SqlDbType DbType, int Size) { return MakeParam(ParamName, DbType, Size, ParameterDirection.Output, null); } /// <summary> /// this method will add a Output SqlParameter /// </summary> /// <param name="ParamName">Name of parameter.</param> /// <param name="DbType">Parameter type.</param> /// <param name="Size">Parameter size.</param> /// <returns>New parameter.</returns> public static SqlParameter MakeOutParam(string ParamName, SqlDbType DbType, int Size, object Value) { return MakeParam(ParamName, DbType, Size, ParameterDirection.Output, Value); } /// <summary> /// this method will create a SqlParameter /// </summary> /// <param name="ParamName">Name of parameter.</param> /// <param name="DbType">Parameter type.</param> /// <param name="Size">Parameter size.</param> /// <param name="Direction">Parameter direction.</param> /// <param name="Value">Parameter value.</param> /// <returns>New parameter.</returns> public static SqlParameter MakeParam(string ParamName, SqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value) { SqlParameter param; if (Size > 0) param = new SqlParameter(ParamName, DbType, Size); else param = new SqlParameter(ParamName, DbType); param.Direction = Direction; if (null != Value) param.Value = Value; else param.Value = DBNull.Value; return param; } #endregion /// <summary> /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a SqlConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); using (SqlConnection conn = new SqlConnection(connectionString)) { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } } /// <summary> /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a SqlConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteTranNonQuery(string connectionString, CommandType cmdType, string cmdText) { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; SqlTransaction tx = conn.BeginTransaction(); cmd.Transaction = tx; try { cmd.CommandText = cmdText; int rows = cmd.ExecuteNonQuery(); tx.Commit(); cmd.Dispose(); conn.Close(); return rows; } catch (System.Data.SqlClient.SqlException e) { tx.Rollback(); cmd.Dispose(); conn.Close(); throw (e); } } } public static List<T> GetProcedureDataByColumnsLst<T>(string conn, string pro, params SqlParameter[] commandParameters) { DataTable tb = SqlHelper.ExecuteGetTable(conn, CommandType.StoredProcedure, pro, commandParameters); return DataConvert<T>(tb); } /// <summary> /// Execute a SqlCommand (that returns no resultset) against an existing database connection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="conn">an existing database connection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } /// <summary> /// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="trans">an existing sql transaction</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>an int representing the number of rows affected by the command</returns> public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters); int val = cmd.ExecuteNonQuery(); cmd.Parameters.Clear(); return val; } /// <summary> /// Execute a SqlCommand that returns a resultset against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a SqlConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>A SqlDataReader containing the results</returns> public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); SqlConnection conn = new SqlConnection(connectionString); // we use a try/catch here because if the method throws an exception we want to // close the connection throw code, because no datareader will exist, hence the // commandBehaviour.CloseConnection will not work try { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); cmd.Parameters.Clear(); return rdr; } catch { conn.Close(); throw; } } public static DataTable ExecuteGetTable(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); cmd.CommandTimeout = 120; using (SqlConnection conn = new SqlConnection(connectionString)) { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); cmd.Parameters.Clear(); return dt; } } public static DataSet ExecuteGetDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); cmd.CommandTimeout = 120; using (SqlConnection conn = new SqlConnection(connectionString)) { PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); cmd.Parameters.Clear(); return ds; } } /// <summary> /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="connectionString">a valid connection string for a SqlConnection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); using (SqlConnection connection = new SqlConnection(connectionString)) { PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } } /// <summary> /// Execute a SqlCommand that returns the first column of the first record against an existing database connection /// using the provided parameters. /// </summary> /// <remarks> /// e.g.: /// Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24)); /// </remarks> /// <param name="conn">an existing database connection</param> /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param> /// <param name="commandText">the stored procedure name or T-SQL command</param> /// <param name="commandParameters">an array of SqlParamters used to execute the command</param> /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns> public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters); object val = cmd.ExecuteScalar(); cmd.Parameters.Clear(); return val; } /// <summary> /// add parameter array to the cache /// </summary> /// <param name="cacheKey">Key to the parameter cache</param> /// <param name="cmdParms">an array of SqlParamters to be cached</param> public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters) { parmCache[cacheKey] = commandParameters; } /// <summary> /// Retrieve cached parameters /// </summary> /// <param name="cacheKey">key used to lookup parameters</param> /// <returns>Cached SqlParamters array</returns> public static SqlParameter[] GetCachedParameters(string cacheKey) { SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey]; if (cachedParms == null) return null; SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length]; for (int i = 0, j = cachedParms.Length; i < j; i++) clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone(); return clonedParms; } /// <summary> /// Prepare a command for execution /// </summary> /// <param name="cmd">SqlCommand object</param> /// <param name="conn">SqlConnection object</param> /// <param name="trans">SqlTransaction object</param> /// <param name="cmdType">Cmd type e.g. stored procedure or text</param> /// <param name="cmdText">Command text, e.g. Select * from Products</param> /// <param name="cmdParms">SqlParameters to use in the command</param> private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms) { if (conn.State != ConnectionState.Open) conn.Open(); cmd.Connection = conn; cmd.CommandText = cmdText; if (trans != null) cmd.Transaction = trans; cmd.CommandType = cmdType; if (cmdParms != null) { foreach (SqlParameter parm in cmdParms) cmd.Parameters.Add(parm); } } public static List<T> DataConvert<T>(DataTable tb) { List<T> lst = new List<T>(); DataConvert<T>(tb, ref lst); return lst; } public static List<T> DataConvert<T>(DataTable tb, ref List<T> lst) { for (int i = 0; i < tb.Rows.Count; i++) { lst.Add(DataConvert<T>(tb.Rows[i])); } return lst; } public static T DataConvert<T>(DataRow row, ref T t) { var ps = t.GetType().GetProperties(); var tbColumns = row.Table.Columns; foreach (var c in ps) { var colName = c.Name; if (tbColumns.Contains(colName)) { object nr = row[colName] == DBNull.Value ? null : row[colName]; if (nr == null) { c.SetValue(t, nr, null); } else { var nrType = c.PropertyType; if (nrType == typeof(decimal) || nrType == typeof(decimal?)) { nr = Convert.ToDecimal(nr); } else if (nrType == typeof(Int64) || nrType == typeof(Int64?)) { nr = Convert.ToInt64(nr); } else if (nrType == typeof(double) || nrType == typeof(double?)) { nr = Convert.ToDouble(nr); } else if (nrType == typeof(Int32) || nrType == typeof(Int32?)) { nr = Convert.ToInt32(nr); } else if (nrType == typeof(Int16) || nrType == typeof(Int16?)) { nr = Convert.ToInt16(nr); } c.SetValue(t, nr, null); } } } return t; } public static T DataConvert<T>(DataRow row) { var type = typeof(T); object obj = type.Assembly.CreateInstance(type.FullName); var c = (T)obj; DataConvert(row, ref c); return c; } /// <summary> /// 根据某个条件得到某列的数据 /// </summ /// ary> /// <param name="conn">数据库连接字符串</param> /// <param name="columns">表的列的数组</param> /// <param name="tableName">表名</param> /// <param name="where">查询条件</param> /// <returns></returns> public static DataTable GetDataByColumns(string conn, string[] columns, string tableName, string where) { if (columns == null || columns.Length == 0) { throw new Exception("columns不能为空或者元素个数为0"); } string cols = " "; foreach (var c in columns) { if (c == "*") { cols += c + ","; } else { cols += "[" + c + "],"; } } cols = cols.Substring(0, cols.Length - 1); string sql = "select" + cols + " from " + tableName + " where " + where; return SqlHelper.ExecuteGetTable(conn, CommandType.Text, sql, null); } /// <summary> /// 根据某个条件得到某列的数据 /// </summary> /// <param name="conn">数据库连接字符串</param> /// <param name="columns">表的列</param> /// <param name="tableName">表名</param> /// <param name="where">查询条件</param> /// <returns></returns> public static DataTable GetDataByColumns(string conn, string column, string tableName, string where) { if (string.IsNullOrEmpty(column)) { throw new Exception("column字段不能为空"); } string[] columns = new string[] { column }; return GetDataByColumns(conn, columns, tableName, where); } public static T GetDataByColumns<T>(string conn, string column, string tableName, string where) { if (string.IsNullOrEmpty(column)) { throw new Exception("column字段不能为空"); } string[] cols = new string[] { column }; return GetDataByColumns<T>(conn, cols, tableName, where); } public static T GetDataByColumns<T>(string conn, string[] columns, string tableName, string where) { DataTable tb = GetDataByColumns(conn, columns, tableName, where); if (tb.Rows.Count > 0) { return DataConvert<T>(tb.Rows[0]); } else { return default(T); } } public static List<T> GetDataByColumnsLst<T>(string conn, string column, string tableName, string where) { if (string.IsNullOrEmpty(column)) { throw new Exception("column字段不能为空"); } string[] cols = new string[] { column }; return GetDataByColumnsLst<T>(conn, cols, tableName, where); } public static IList<T> GetDataByColumnsIList<T>(string conn, string column, string tableName, string where) { if (string.IsNullOrEmpty(column)) { throw new Exception("column字段不能为空"); } string[] cols = new string[] { column }; return GetDataByColumnsLst<T>(conn, cols, tableName, where); } public static List<T> GetDataByColumnsLst<T>(string conn, string[] columns, string tableName, string where) { using (DataTable tb = GetDataByColumns(conn, columns, tableName, where)) { return DataConvert<T>(tb); } } public static T GetDataByColumns<T>(string conn, string sql, params SqlParameter[] commandParameters) { using (DataTable tb = SqlHelper.ExecuteGetTable(conn, CommandType.Text, sql, commandParameters)) { if (tb != null && tb.Rows.Count > 0) return DataConvert<T>(tb.Rows[0]); else return default(T); } } public static List<T> GetDataByColumnsLst<T>(string conn, string sql, params SqlParameter[] commandParameters) { using (DataTable tb = SqlHelper.ExecuteGetTable(conn, CommandType.Text, sql, commandParameters)) { return DataConvert<T>(tb); } } public static IList<T> GetDataByColumnsIList<T>(string conn, string sql, params SqlParameter[] commandParameters) { using (DataTable tb = SqlHelper.ExecuteGetTable(conn, CommandType.Text, sql, commandParameters)) { return DataConvert<T>(tb); } } /// <summary> /// 类属性转化成字符串 /// </summary> /// <param name="type"></param> /// <returns></returns> public static string PropertiesToString(Type type, List<string> removeIds, Dictionary<string, string> modifyp) { Dictionary<string, string> modifyp2 = new Dictionary<string, string>(); if (modifyp != null) { foreach (var c in modifyp.Keys) { modifyp2.Add(c.ToLower(), modifyp[c]); } } if (removeIds != null) { for (int i = 0; i < removeIds.Count; i++) { removeIds[i] = removeIds[i].ToLower(); } } var ps = type.GetProperties(); StringBuilder sb = new StringBuilder(); foreach (var c in ps) { string name = c.Name; string lname = name.ToLower(); if (removeIds == null || !removeIds.Contains(lname)) { if (modifyp2.ContainsKey(lname)) { name = modifyp2[lname]; sb.Append(name + ","); } else { sb.Append("[" + name + "],"); } } } if (sb.Length > 0) { sb = sb.Remove(sb.Length - 1, 1); } return sb.ToString(); } public static SqlConnection conn; /// <summary> /// 根据sql查询 /// </summary> /// <param name="sql"></param> /// <returns></returns> public static DataSet GetDataSet(string sql, string constr) { SqlDataAdapter adapter = null; DataSet ds = null; try { ds = new DataSet(); conn = new SqlConnection(constr); conn.Open(); adapter = new SqlDataAdapter(sql, conn); adapter.Fill(ds); } catch (Exception ex) { throw new Exception(ex.Message); } finally { if (adapter != null) adapter.Dispose(); if (conn != null) { conn.Close(); conn.Dispose(); } } return ds; } public static SqlParameter[] ObjectToSqlParameters(object obj, string[] removeKey) { //System. List<SqlParameter> lst = new List<SqlParameter>(); var ps = obj.GetType().GetProperties(); List<string> lstRemove = new List<string>(); if (removeKey != null) { foreach (var c in removeKey) { lstRemove.Add(c.ToLower()); } } foreach (var c in ps) { if (lstRemove.Contains(c.Name.ToLower())) { continue; } object value = c.GetValue(obj, null); if (c.PropertyType == typeof(int) || c.PropertyType == typeof(int?)) { lst.Add(CreateSqlParameter(c.Name, SqlDbType.Int, value)); } else if (c.PropertyType == typeof(long) || c.PropertyType == typeof(long?)) { lst.Add(CreateSqlParameter(c.Name, SqlDbType.BigInt, value)); } else if (c.PropertyType == typeof(string)) { lst.Add(CreateSqlParameter(c.Name, SqlDbType.VarChar, value)); } else if (c.PropertyType == typeof(bool) || c.PropertyType == typeof(bool?)) { lst.Add(CreateSqlParameter(c.Name, SqlDbType.Bit, value)); } else if (c.PropertyType == typeof(byte[])) { lst.Add(CreateSqlParameter(c.Name, SqlDbType.Binary, value)); } else if (c.PropertyType == typeof(DateTime) || c.PropertyType == typeof(DateTime?)) { lst.Add(CreateSqlParameter(c.Name, SqlDbType.DateTime, value)); } else if (c.PropertyType == typeof(decimal?) || c.PropertyType == typeof(decimal) || c.PropertyType == typeof(float) || c.PropertyType == typeof(float?) || c.PropertyType == typeof(double) || c.PropertyType == typeof(double?)) { lst.Add(CreateSqlParameter(c.Name, SqlDbType.Decimal, value)); } else if (c.PropertyType == typeof(System.Guid) || c.PropertyType == typeof(Guid?)) { lst.Add(CreateSqlParameter(c.Name, SqlDbType.UniqueIdentifier, value)); } } return lst.ToArray(); } public static SqlParameter[] ObjectToSqlParameters(object obj) { return ObjectToSqlParameters(obj, null); } private static SqlParameter CreateSqlParameter(string name, SqlDbType dbType, object value) { if (!name.StartsWith("@")) { name = "@" + name; } if (value == null) { value = DBNull.Value; } SqlParameter sp = new SqlParameter(name, dbType); sp.Value = value; return sp; } } }
using EddiDataDefinitions; using System; using Utilities; namespace EddiEvents { [PublicAPI] public class NPCAttackCommencedEvent : Event { public const string NAME = "NPC attack commenced"; public const string DESCRIPTION = "Triggered when an attack on your ship by an NPC is detected"; public static readonly NPCAttackCommencedEvent SAMPLE = new NPCAttackCommencedEvent(DateTime.UtcNow, MessageSource.BountyHunter); [PublicAPI("The localized source of the attack (Pirate, Military, Bounty hunter, Cargo hunter, etc)")] public string by => Source.localizedName; [PublicAPI("The invariant source of the attack (Pirate, Military, Bounty hunter, Cargo hunter, etc)")] public string by_invariant => Source.invariantName; // Not intended to be user facing public MessageSource Source { get; } public NPCAttackCommencedEvent(DateTime timestamp, MessageSource source) : base(timestamp, NAME) { Source = source; } } }
using System.IO; using System.Linq; using System.Text; using iSukces.Code.Interfaces; namespace iSukces.Code { public abstract class CodeWriter : ICodeWriter { protected CodeWriter(ILangInfo langInfo) { LangInfo = langInfo; } public void Append(string text) { _sb.Append(text); } /* public void Block(string open, string customCloseText, Action method) { Writeln(open); this.IncIndent(); method(); this.Close(customCloseText); } public void Block(string open, Action method) { Writeln(open); this.IncIndent(); method(); this.Close(); } public void Clear() { _sb = new StringBuilder(); Indent = 0; // opening = new Dictionary<int, string>(); } */ protected virtual string GetCodeForSave() { return Code; } public void Save(string filename) { var fi = new FileInfo(filename); fi.Directory.Create(); using(var fs = new FileStream(filename, File.Exists(filename) ? FileMode.Create : FileMode.CreateNew)) { SaveToStream(fs); } } public bool SaveIfDifferent(string filename) { if (!File.Exists(filename)) { Save(filename); return true; } byte[] newa; var existing = File.ReadAllBytes(filename); using(var fs = new MemoryStream()) { SaveToStream(fs); newa = fs.ToArray(); } if (newa.SequenceEqual(existing)) return false; File.WriteAllBytes(filename, newa); return true; } private void SaveToStream(Stream stream) { if (LangInfo.AddBOM) stream.Write(new byte[] {0xEF, 0xBB, 0xBF}, 0, 3); var x = Encoding.UTF8.GetBytes(GetCodeForSave()); stream.Write(x, 0, x.Length); } // public bool AutoCloseComment { get; set; } public override string ToString() { return Code; } /// <summary> /// opis języka /// </summary> public ILangInfo LangInfo { get; } public string[] Lines { get { var tmp = Code; var l = tmp.Split('\n'); for (var i = 0; i < l.Length; i++) l[i] = l[i].Replace("\r", ""); return l; } } /// <summary> /// Czy trimować tekst /// </summary> public bool TrimText { get; set; } public string Code { get { var x = _sb.ToString(); if (TrimText) return x.Trim(); return x; } } public int Indent { get => _indent; set { if (value < 0) value = 0; if (value == _indent) return; _indent = value; _indentStr = value > 0 ? new string(' ', IndentSize * value) : string.Empty; } } private string _indentStr = ""; // private Dictionary<int, string> opening = new Dictionary<int, string>(); private readonly StringBuilder _sb = new StringBuilder(); private int _indent; private const int IndentSize = 4; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.Mvc; using ZY.OA.Common; using ZY.OA.IBLL; using ZY.OA.Model; using ZY.OA.Model.Enum; using ZY.OA.Model.SearchModel; namespace ZY.OA.UI.PortalNew.Controllers { public class ActionInfoController : BaseController { public IActionInfoService ActionInfoService { get; set; } public IRoleInfoService RoleInfoService { get; set; } public ActionResult Index() { return View(); } //获取权限信息 public ActionResult GetActionInfo() { int pageIndex = Request["page"] == null ? 1 : int.Parse(Request["page"]); int pageSize = Request["rows"] == null ? 10 : int.Parse(Request["rows"]); int total = 0; string Remark = Request["Remark"]; string HttpMethd = Request["HttpMethd"]; string ActionName = Request["ActionName"]; ActionInfoSearchParms actionInfoSearchParms = new ActionInfoSearchParms() { pageIndex = pageIndex, pageSize = pageSize, total = total, Remark = Remark, HttpMethd = HttpMethd, ActionName = ActionName }; var ActionInfos = ActionInfoService.GetPageEntityBySearch(actionInfoSearchParms); return Content(SerializerHelper.SerializerToString(new { rows = ActionInfos, total = actionInfoSearchParms.total })); } //添加权限信息 public ActionResult AddActionInfo() { return View(); } //添加权限信息 [HttpPost] public ActionResult AddActionInfo(ActionInfo actionInfo) { if (!string.IsNullOrEmpty(actionInfo.ActionName) && !string.IsNullOrEmpty(actionInfo.Url) && !string.IsNullOrEmpty(Request["Sort"])) { int sort = 0; int.TryParse(Request["Sort"], out sort); short normal = (short)DelFlagEnum.Normal; actionInfo.Url = Request["Url"].ToLower(); actionInfo.Sort = sort; actionInfo.SubTime = DateTime.Now; actionInfo.ModfiedOn = DateTime.Now; actionInfo.DelFlag = normal; actionInfo.IsMenu = Request["isOrNo"] == "true" ? true : false; actionInfo.MenuIcon = Request["ImgSrc"]; ActionInfo action = ActionInfoService.Add(actionInfo); if (action != null) { return Content("ok"); } } return Content("no"); } //上传图片 public ActionResult UpLoadFile() { HttpPostedFileBase file = Request.Files["MenuIcon"];//获取客户端上传的文件 if (file != null) { string fileExt = Path.GetExtension(file.FileName); //获取扩展名 string[] fileExtArray = { ".BMP", ".JPG", ".JPEG", ".PNG", ".GIF" }; bool b = false; string thumbpath = ""; foreach (string Ext in fileExtArray) { if (fileExt.ToUpper() == Ext) { b = true; //源图路径 string path = "/UpLoadImg/" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "/"; Directory.CreateDirectory(Path.GetDirectoryName(Request.MapPath(path)));//创建源路径 string originalpath = path + Guid.NewGuid().ToString() + file.FileName; string originalImagePath = Request.MapPath(originalpath); file.SaveAs(originalImagePath); //缩略图路径 string tbpath = "/UploadImgThumbnail/" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "/"; Directory.CreateDirectory(Path.GetDirectoryName(Request.MapPath(tbpath)));//创建缩略图路径 thumbpath = tbpath + Guid.NewGuid().ToString() + file.FileName; string thumbnailPath = Request.MapPath(thumbpath); ImageClass.MakeThumbnail(originalImagePath, thumbnailPath, 100, 100, "HW"); } } if (b) { return Content("ok:" + thumbpath); } else { return Content("no:"); } } else { return Content("no:"); } } //编辑权限信息 public ActionResult EditAction() { int id = int.Parse(Request["id"]); ActionInfo actionInfo = ActionInfoService.GetEntities(a => a.ID == id).FirstOrDefault(); if (actionInfo != null) { ViewBag.actionInfo = actionInfo; } return View(); } //编辑权限信息 [HttpPost] public ActionResult EditAction(ActionInfo actionInfo) { if (!string.IsNullOrEmpty(actionInfo.ActionName) && !string.IsNullOrEmpty(actionInfo.Url) && !string.IsNullOrEmpty(Request["Sort"])) { int sort = 0; int.TryParse(Request["Sort"], out sort); actionInfo.Url = Request["Url"].ToLower(); actionInfo.Sort = sort; actionInfo.ModfiedOn = DateTime.Now; actionInfo.IsMenu = Request["isOrNo"] == "true" ? true : false; if (actionInfo.IsMenu == true) { actionInfo.MenuIcon = Request["ImgSrc"]; } else { actionInfo.MenuIcon = ""; } if (ActionInfoService.Update(actionInfo)) { return Content("ok"); } } return Content("no"); } //删除权限信息 [HttpPost] public ActionResult DeleteActionInfo() { string actionIds = Request["actionIds"]; if (!string.IsNullOrEmpty(actionIds)) { string[] actionIdArray = actionIds.Split(','); List<int> actionIdList = new List<int>(); foreach (string id in actionIdArray) { actionIdList.Add(int.Parse(id)); } if (ActionInfoService.DeleteListBylogical(actionIdList)) { return Content("ok"); } } return Content("no"); } //设置权限角色展示 public ActionResult SetActionRoleInfo() { int actionId = int.Parse(Request["id"]); short Normal = (short)DelFlagEnum.Normal; //获取要设置角色的权限信息 ActionInfo actionInfo = ActionInfoService.GetEntities(a => a.ID == actionId).FirstOrDefault(); //获取所有的角色信息 List<RoleInfo> RoleInfoList = RoleInfoService.GetEntities(r => r.DelFlag == Normal).ToList(); List<int> actionRoleId = actionInfo.RoleInfo.Select(r => r.ID).ToList(); ViewBag.actionInfo = actionInfo; ViewBag.RoleInfoList = RoleInfoList; ViewBag.actionRoleId = actionRoleId; return View(); } //设置权限角色 public ActionResult SetActionRole() { int actionId= Request["actionInfoId"]==null?0:int.Parse(Request["actionInfoId"]); string [] allKeys= Request.Form.AllKeys; List<int> roleIdlist = new List<int>(); foreach (var Key in allKeys) { if (Key.StartsWith("CKB_")) { roleIdlist.Add(int.Parse(Request[Key])); } } if (ActionInfoService.SetActionRoleInfo(actionId, roleIdlist)) { return Content("ok"); } else { return Content("no"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Object_oriented_Programming_in_C_Part_1 { class A //object-oriented programming { static void Main(string[] args) { //methods part 1 int a, b, c, d; int addResult = 0; a = 5; b = 3; //addResult = a + b; Console.WriteLine($" {a} + {b} = {addResult}"); //Console.WriteLine("The process is done"); DisplayMessage(); //heres the method being called. addResult = PerformAddOperation(a, b); c = 5; d = 3; //addResult = c + d; Console.WriteLine($" {c} + {d} = {addResult}"); //Console.WriteLine("The process is done"); DisplayMessage(); addResult = PerformAddOperation(c, d); } static int PerformAddOperation(int x, int y) { int addResult = 0; addResult = x + y; Console.WriteLine($" {x} + {y} = {addResult}"); DisplayMessage(); return addResult; } static void DisplayMessage() //this is a new method. it will run every time is called. { Console.WriteLine("process is done"); Console.WriteLine("this process was run by Salv"); Console.WriteLine("time:" + DateTime.Now.ToShortTimeString()); } //method exercise. Ask for a name. static void ReadOutName() { GetName(); //this calls the object/function. } static void GetName() { string name = string.Empty; name = Console.ReadLine(); SayHi(name); } static void SayHi(string name) { Console.WriteLine($" Welcome back {name}"); } static void ReadMessage() { Console.ReadLine(); } } class B //object-oriented program { static void Main(string[] args) { string firstEmployee, secondEmployee; firstEmployee = "David Smith"; secondEmployee = "Sophia Watson"; Console.WriteLine($"Inside Main Method\n---------\n{firstEmployee} \n{secondEmployee}\n\n"); //ChangeNames(firstEmployee, secondEmployee); //this calls the function from within this block. //ChangeNames(ref firstEmployee, ref secondEmployee); ChangeNames(out firstEmployee, out secondEmployee); //when you use out keyword, you dont need to declare the variables. Console.WriteLine($"Inside Main Method\n---------\n{firstEmployee} \n{secondEmployee}\n\n"); } //static void ChangeNames(string firstEmp, string secEmp) //again this is a function. //static void ChangeNames(ref string firstEmp, ref string secEmp) //if you use reference keyword it does change the last/output values. static void ChangeNames(out string firstEmp, out string secEmp) { //this is called passing by value, without changing the variables. firstEmp = "Olivia Aaron"; secEmp = "Alvaro Salazar"; Console.WriteLine($"Outside Main Method\n---------\n{firstEmp} \n{secEmp}\n\n"); } } class C //Method Overloaded. { static void Main(string[] args) { string guestName = ""; Console.WriteLine("Hello, dear guest, what is your name?"); guestName = Console.ReadLine(); if (guestName == string.Empty) WelcomeGuest(); } static void WelcomeGuest() { Console.WriteLine("Okay, we hope you enjoy your stay"); //Console.ReadLine(); } } class D //Overloaded Exercise, add up functions. { static void Main(string[] args) { int a, b, c, intResult; //this creates an end-result varible to store the end result. double x, y, z, douResult; intResult = 0; a = 1; b = 2; c = 3; douResult = 0; x = 0.50; y = 1.50; z = 2.0; Console.WriteLine(PerformAdd(a, b));// you can add the function name inside the console.writeline together with the variables. Console.WriteLine(PerformAdd2(a, b, c)); Console.WriteLine(PerformAdd3(x, y, z)); } static int PerformAdd(int num1, int num2)// as you can see, you can put different variable names as long as they work, like a is num1, it doesnt matter. { return num1 + num2; } static int PerformAdd2(int num1, int num2, int num3) { return num1 + num2 + num3; } static double PerformAdd3(double num1, double num2, double num3) { return num1 + num2 + num3; } } class E //Classes { static void Main(string[] args) { Person perOne = new Person();//here you can insert it into other classes and use it. This is a constructor. perOne.FirstName = "Ahmad"; perOne.LastName = "Mohey"; perOne.Country = "Egypt"; Person perTwo = new Person(); //this is a constructor. They have the same name. perTwo.FirstName = "Tim"; perTwo.LastName = "David"; perTwo.Country = "Australia"; Console.WriteLine(perOne.FirstName, perOne.LastName); Console.WriteLine(perTwo.FirstName, perTwo.LastName); } class Person //this is a new class called, you guessed, person. { string firstName; //to make them visible inside others you gotta add public to it. string lastName; DateTime birthDate; string country; public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName = value; } } public DateTime BirthDate { get; set; } public string Country { get; set; } } } class F //Datetime exploration. { static void Main(string[] args) { DateTime date = new DateTime();//just press F12 or view/object browser too see stuff. Console.WriteLine(date); SayHi();//this is the call of the say hi method created after. Didnt want to make more classes. Person person = new Person();// for non-static methods i need to create an instance like this first. person.SayHi(); //then add the name of the variable followed by the method. which is SayHi here.//this is the say hi from the class "Person" } //static methods. static void SayHi() //void SayHi() //if you put this on it wont work. cos its not instanciated/started with static. { Console.WriteLine("Hi, from the static method"); } } class Person { public void SayHi() { Console.WriteLine("Hi, from the non-static method"); } } class dogs //Scope exercise, what scope esencially is, is a methods capacity to be inside and used //in other methods. Thats why sometimes they dont show in the drop down menu. { string dogname; string dogbreed; string dogcolor; string trainername; public void traindog() { string trainername; trainername = "Daniel"; } public void feeddog() { string foodname; } } class H { static string name = "Sam"; static void Main(string[] args) { SayHi2(); } static void SayHi2() { name = "Jori"; //this overwrites the static string up there, Sam. Because its been declared locally. Console.WriteLine("Hi," + name); } } class inheritance //inheritance exercise { static void Main(string[] args) { animal animal = new animal();// you can call the variable (in black) anything you want it could be a cat. dogs2 dog = new dogs2();//this is constructed the following way. First, the name of the class. //then the variable name, which is dog, then equals, then the keyword "new" followed //by the class name again, dogs. birds bird = new birds(); bird.FeedAnimal(); //now FeedAnimal method has been "inherited" or shared basically with other classes. } } class animal { public string animalName; public DateTime animalBirthDate; public void FeedAnimal() { } } class dogs2 : animal //this is literally what makes inheritance work, just the addition of : followed by the class you want. { public string dogBreed; public string dogIntelligence; public bool isEasyToTrain; } class birds : animal //same again. { public string birdColor; public string birdCountry; } class Encapsulation //Encampsulation { private string privateVariable; public string publicVariable; protected string protectedVaraible; internal string internalVariable; private void TrainAnimalPrivate() { } public void TrainAnimalPublic() { } protected void TrainAnimalProtected() { } internal void TrainAnimalInternal() { } } //what encapsulation is all about is about the declaration of different variables, for security purposes. //private, protected, internal, see beggining of the video to check what they are. class Dogs : Encapsulation { Dogs dog = new Dogs(); void FeedDog()//this void method is just an empty, all purposes method that can be created on the fly i believe thus void. { } } class Cats { Encapsulation animal = new Encapsulation(); void FeedCat() { } } class Vehicle //vehicle inheritance exercise. { } class WheeledVehicles : Vehicle { private string color; private decimal price; public string Color { get; set; } public decimal Price { get; set; } public void ChangeColor() { Console.WriteLine("Color is changing.\nColor has changed"); } } class FourWheeledVehicles : WheeledVehicles { private string brandName; private int capacity; public string BrandName { get; set; } public int Capacity { get; set; } public void StartVehicle() { Console.WriteLine("Car has started"); } public void RunAtFullSpeed() { Console.WriteLine("Car is running on full speed"); } } class RunVehicleProgram { static void Main(string[] args) { FourWheeledVehicles car = new FourWheeledVehicles(); car.ChangeColor(); car.StartVehicle(); car.RunAtFullSpeed(); } } class Polymorphism //polymorphism means "many forms" { static void Main(string[] args) { Shapes[] shapes = new Shapes[4];//this is an array, eventhough we havent studied arrayed he created one with 4 spaces. shapes[0] = new Shapes();//this is whats in each array space. shapes[1] = new Circles(); shapes[2] = new Lines(); shapes[3] = new Triangle(); foreach (var shape in shapes) { shape.Draw(); } } } class Shapes { public virtual void Draw()//by putting virtual you tell it that this method can be "overwritten" { Console.WriteLine("I am a simple shape"); } } class Circles : Shapes { public new void Draw()//this will tell it to repeat shapes. cos its just another "new" shape. { Console.WriteLine("I am circle"); } } class Lines : Shapes { public override void Draw()//this tells it to override with whatever you tell it to next. { Console.WriteLine("I am line"); } } class Triangle : Shapes { public override void Draw()//overwrite whatever is the original template, virtual shapes. { Console.WriteLine("I am triangle"); } } class Abstraction //im not %100 what abstraction is about. { static void Main(string[] args) { Lines2 line2 = new Lines2(); line2.SayHi(); line2.Draw(); } } abstract class Shapes2 { abstract public void Draw(); public void SayHi() { Console.WriteLine("Hi from the abstact class"); } } class Lines2 : Shapes2 { public override void Draw() { Console.WriteLine("Hi I am a line"); } } #region //you can section off parts of code with region. class CarExercise //display values then override them. { static void Main(string[] args) { Mercedes mer = new Mercedes(); Volvo volvo = new Volvo(); mer.DisplayInfo(); volvo.DisplayInfo(); } } class Cars { #region - you can section off inside classes too. Variables private decimal price; protected int maxSpeed; public string color; #endregion protected decimal Price//you gotta type this is to use the price in the override field, //because its set to private, or it'll give an error, check it. { get { return price; } set { price = value; } } public virtual void DisplayInfo()//virtual tells it the next things can be overwriten. { price = 10000; maxSpeed = 300; color = "Black"; Console.WriteLine($"Default values : price is {price}, max speed is {maxSpeed} and the color is {color}"); } } class Mercedes : Cars { public override void DisplayInfo() { base.DisplayInfo();//to snipped/access the functions of the base class just type base. base.Price = 15000; base.color = "blue"; base.maxSpeed = 200; Console.WriteLine($"Overriden values : price is {Price}, max speed is {maxSpeed} and the color is {color}"); } } class Volvo : Cars { public override void DisplayInfo() { base.DisplayInfo(); base.Price = 5000; base.color = "grey"; base.maxSpeed = 160; Console.WriteLine($"Overriden values 2: price is {Price}, max speed is {maxSpeed} and the color is {color}"); } } #endregion }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using OUTDOOR.src.view.options; using OUTDOOR.src.tools.objects; namespace OUTDOOR.src.view.pages { public partial class inicio_page : Form { private Inicio_option inicio; private Jugador _jugador; public inicio_page(Jugador jugador) { _jugador = jugador; InitializeComponent(); inicio = new Inicio_option(); inicio.insertarNombre(_jugador); inicio.Dock = DockStyle.Fill; this.panel_contenedor.Controls.Add(inicio); } void Animacion_menu_entrar(object sender, EventArgs e) { Control panel = sender as Control; panel.BackColor = Color.FromArgb(129, 40, 52); } void Animacion_menu_salir(object sender, EventArgs e) { Control panel = sender as Control; if (!panel.Bounds.Contains(this.PointToClient(Cursor.Position))) { panel.BackColor = Color.FromArgb(86, 7, 35); } } private void label8_Click(object sender, EventArgs e) { inicio.pararHilo(); Login_page login = new Login_page(); login.Show(); this.Dispose(); } private void panel7_Click(object sender, EventArgs e) { this.panel_contenedor.Controls.Clear(); inicio.pararHilo(); inicio = new Inicio_option(); inicio.Dock = DockStyle.Fill; inicio.insertarNombre(_jugador); this.panel_contenedor.Controls.Add(inicio); } private void panel9_Click(object sender, EventArgs e) { inicio.pararHilo(); this.panel_contenedor.Controls.Clear(); score_option score = new score_option(); score.Dock = DockStyle.Fill; score.insertarNombre(_jugador); this.panel_contenedor.Controls.Add(score); } private void panel11_Click(object sender, EventArgs e) { inicio.pararHilo(); this.panel_contenedor.Controls.Clear(); Estadisticas_option estadisticas = new Estadisticas_option(); estadisticas.Dock = DockStyle.Fill; estadisticas.insertarNombre(_jugador); this.panel_contenedor.Controls.Add(estadisticas); } private void panel13_Click(object sender, EventArgs e) { inicio.pararHilo(); this.panel_contenedor.Controls.Clear(); Creditos_option creditos = new Creditos_option(); creditos.Dock = DockStyle.Fill; this.panel_contenedor.Controls.Add(creditos); } private void inicio_page_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 13) { inicio.pararHilo(); try { var nivel=inicio.nivel(); (new Juego_page(_jugador,nivel)).Show(); this.Dispose(); } catch { MessageBox.Show("Seleccione un nivel de dificultad"); } } } } }
namespace PalTracker { public class WelcomeMessage { public string Message { get; set;} public string User { get; set;} public WelcomeMessage( string message ){ Message = message; } public WelcomeMessage( string message, string user ){ Message = message; User = user; } public WelcomeMessage(){ } } }
using RRExpress.Common.Interfaces; using System.IO; using System.Net.Http; using System.Net.Http.Headers; namespace RRExpress.Common { public class ProtobufContentHandler : IContentHandler { public string ContentType { get { return "application/x-protobuf"; } } public HttpContent GetContent(object data) { using (var msm = new MemoryStream()) { ProtoBuf.Serializer.Serialize(msm, data); var content = new ByteArrayContent(msm.ToArray()); content.Headers.ContentType = MediaTypeHeaderValue.Parse(this.ContentType); return content; } } public T Parse<T>(IClientSetup client, byte[] bytes) { using (var msm = new MemoryStream(bytes)) { //return ProtoBuf.Serializer.DeserializeWithLengthPrefix<T>(msm, ProtoBuf.PrefixStyle.None); return ProtoBuf.Serializer.Deserialize<T>(msm); } } /// <summary> /// /// </summary> /// <param name="client"></param> public void SetRequestHttpClient(HttpClient client) { //添加 Accept client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(this.ContentType)); } } }
using System.Collections; using UnityEngine; public class TransformFollower : MonoBehaviour { [SerializeField] private bool lookAt = true; [SerializeField] private Transform target; [SerializeField] private Vector3 offsetPosition = new Vector3(0, 0, 0); [SerializeField] private Vector3 offsetPositionDialog = new Vector3(3, 0, 0); [SerializeField] private Vector3 offsetUp = new Vector3(0, 1, 0); [SerializeField] private Space offsetPositionSpace = Space.Self; [SerializeField] public bool b_offsetPositionDialog = false; [SerializeField] private bool m_AutoTargetPlayer = true; // Whether the rig should automatically target the player. [SerializeField] public float f_transitionTimeFinal = 10f; [HideInInspector] public float f_transitionTime = 3f; [HideInInspector] public bool stopFollowing = false; private Vector3 TargetPosition; private bool b_smooth; protected virtual void Start() { // if auto targeting is used, find the object tagged "Player" // any class inheriting from this should call base.Start() to perform this action! if (m_AutoTargetPlayer) { FindAndTargetPlayer(); } StartCoroutine(ChangeSpeedCamera()); } private void LateUpdate() { Refresh(); if (m_AutoTargetPlayer && (target == null || !target.gameObject.activeSelf)) { FindAndTargetPlayer(); } } public void FindAndTargetPlayer() { // auto target an object tagged player, if no target has been assigned var targetObj = GameObject.FindGameObjectWithTag("Player"); if (targetObj) { SetTarget(targetObj.transform); } } public virtual void SetTarget(Transform newTransform) { target = newTransform; } public Transform Target { get { return target; } } public void Refresh() { if (target == null) { return; } if (!stopFollowing) { // compute position if (offsetPositionSpace == Space.Self) { if (b_offsetPositionDialog) { b_smooth = true; TargetPosition = target.TransformPoint(offsetPosition + offsetPositionDialog); } else { StartCoroutine(SwitchBool()); TargetPosition = target.TransformPoint(offsetPosition); } } else { TargetPosition = target.position + offsetPosition; } if (b_smooth) { transform.position = Vector3.Lerp(transform.position, TargetPosition, f_transitionTime * Time.fixedDeltaTime); } else { transform.position = TargetPosition; } } // compute rotation if (lookAt) { transform.LookAt(target.position + offsetUp); } } IEnumerator ChangeSpeedCamera() { yield return new WaitForSeconds(2); f_transitionTime = Mathf.Lerp(f_transitionTime, f_transitionTimeFinal, 0.5f); } IEnumerator SwitchBool() { yield return new WaitForSeconds(1); b_smooth = false; } }
namespace Object_oriented_design_principles { using System; using System.Linq; /// <summary> /// Create generic classes for representing square, symmetric and diagonal matrices /// (a symmetric matrix is a square matrix that coincides with its transpose to it, /// a diagonal matrix is a square matrix whose elements outside the main diagonal /// obviously have default values for the element type). Describe in the created /// classes an event that occurs when a matrix element with indices (i, j) changes. /// To provide the possibility of extending the functionality of the class hierarchy, /// adding the possibility for the addition operation of two matrices of any kind. /// Develop unit-tests. /// </summary> public class FirstTask { public static class MatrixFactory { public static SquareMatrix Create(double[][] matrix) { if (IsMatrixDiagonal(matrix)) { return new DiagonalMatrix(matrix); } else if (IsMatrixSymmetric(matrix)) { return new SymmetricMatrix(matrix); } else { return new SquareMatrix(matrix); } } private static bool IsMatrixSymmetric(double[][] matrix) { for (var row = 0; row < matrix.Length - 1; row++) { for (var column = 0; column < matrix.Length - 1; column++) { if (Math.Abs(matrix[row][column] - matrix[column][row]) > 0.0001) { return false; } } } return true; } private static bool IsMatrixDiagonal(double[][] matrix) { for (var row = 0; row < matrix.Length - 1; row++) { for (var column = 0; column < matrix.Length - 1; column++) { if ((row != column && matrix[row][column] != 0.0) || (row == column && matrix[row][column] == 0.0)) { return false; } } } return true; } } public class SquareMatrix { private double[][] matrix; public SquareMatrix(double[][] matrix) { this.matrix = matrix; } public event EventHandler<ElementChangedArgs> ElementChanged = ElementChangedHandler; public double this[int row, int column] { get => matrix[row][column]; set { matrix[row][column] = value; OnElementChanged(row, column); } } public static SquareMatrix operator +(SquareMatrix firstMatrix, SquareMatrix secondMatrix) { if (firstMatrix.matrix.Length != secondMatrix.matrix.Length) { throw new ArgumentException("Addition can only be applied to matrices of the same size."); } var sumOfMatrices = new double[firstMatrix.matrix.Length][]; for (var i = 0; i < firstMatrix.matrix.Length; i++) { sumOfMatrices[i] = firstMatrix.matrix[i].Zip(secondMatrix.matrix[i], (x, y) => x + y).ToArray(); } return MatrixFactory.Create(sumOfMatrices); } public void OnElementChanged(int row, int column) { var arguments = new ElementChangedArgs { Row = row, Column = column }; ElementChanged?.Invoke(this, arguments); } public override string ToString() { return matrix.Aggregate(string.Empty, (current, row) => current + $"[{string.Join(", ", row)}]" + Environment.NewLine); } public override bool Equals(object obj) { if (!(obj is SquareMatrix anotherMatrix)) { return false; } for (var row = 0; row < matrix.Length; row++) { for (var column = 0; column < matrix.Length; column++) { if (Math.Abs(matrix[row][column] - anotherMatrix.matrix[row][column]) > 0.0001) { return false; } } } return true; } public override int GetHashCode() { unchecked { if (this.matrix == null) { return 0; } return this.matrix.Aggregate(17, (current, element) => (current * 31) + element.GetHashCode()); } } private static void ElementChangedHandler(object source, ElementChangedArgs arg) { Console.WriteLine($"The Element of the matrix with indices ({arg.Row}, {arg.Column}) has been changed by {source.GetType().Name}"); } public class ElementChangedArgs : EventArgs { public int Row { get; set; } public int Column { get; set; } } } public class SymmetricMatrix : SquareMatrix { public SymmetricMatrix(double[][] matrix) : base(matrix) { } } public class DiagonalMatrix : SquareMatrix { public DiagonalMatrix(double[][] matrix) : base(matrix) { } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Nailhang.Display.Tools.TextSearch.Base { public interface IIndex { void Throttle(float quantile); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Serialization { public interface ISerializerFactory { ISerializer CreateSerializer(); } }
using Discord.Commands; using JhinBot.DiscordObjects; using JhinBot.Services; using JhinBot.Enums; using JhinBot.Tables.Objects; using JhinBot.Utils; using NLog; using System.Threading.Tasks; namespace JhinBot.Modules { [Summary("Contains commands related to ingame quotes.")] public class QuoteModule : BotModuleBase { private readonly IQuoteService _quoteService; public QuoteModule(IQuoteService quoteService, IOwnerLogger ownerLogger, IMessageFormatService formatter, IResourceService resources, IEmbedService embedService, IBotConfig botConfig, IDbService dbService) : base(ownerLogger, formatter, resources, embedService, botConfig, dbService) { _quoteService = quoteService; } [Command("talk"), Name("talk"), Summary("Sends one of my poetic creations as a reply.")] public async Task Quote() { await SendMessageAsync(_quoteService.FetchQuote(), MessageFormatting.Italic); } } }
using UnityEngine; using System.Collections; public class PowerupScript : MonoBehaviour { //controls the powerup objects created for Spawn public float speed = 20f; void Update () { //shoot left this.transform.Translate(Vector3.left * speed * Time.deltaTime); } void OnTriggerEnter2D (Collider2D coll){//destroy powerup if it hits player or bound tag = coll.gameObject.tag; if (tag == "Player" || tag == "Bound"){ Destroy (gameObject); print ("hit a player or bound "); } if (tag == "Bullet") print ("hit a bullet"); } //TODO: Fix coll problems //problem has since been solved by changing layer coll matrix }
using Entitas; [Game] public sealed class BlockComponent : IComponent { }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EBS.Domain.ValueObject { public enum PurchaseOrderStatus { [Description("作废")] Cancel = -1, [Description("初始")] Create = 1, [Description("待入库")] WaitStockIn = 2, [Description("待出库")] WaitStockOut = 3, [Description("已完成")] Finished = 4, [Description("财务已审")] FinanceAuditd =5 } // 采购单: 初始, 待收货,待入库,完成 // 采购退单: 待出库,完成 }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using bellyful_proj.Models; using bellyful_proj_v._0._2.Data; namespace bellyful_proj_v._0._2.Controllers { public class BatchesController : Controller { private readonly ApplicationDbContext _context; public BatchesController(ApplicationDbContext context) { _context = context; } // GET: Batches public async Task<IActionResult> Index() { var applicationDbContext = _context.Batch.Include(b => b.MealType); return View(await applicationDbContext.ToListAsync()); } // GET: Batches/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var batch = await _context.Batch .Include(b => b.MealType) .FirstOrDefaultAsync(m => m.BatchId == id); if (batch == null) { return NotFound(); } return View(batch); } // GET: Batches/Create public IActionResult Create() { ViewData["MealTypeId"] = new SelectList(_context.MealType, "MealTypeId", "MealTypeName"); return View(); } // POST: Batches/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("BatchId,AddAmount,ProductionDate,MealTypeId")] Batch batch) { if (ModelState.IsValid) { _context.Add(batch); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["MealTypeId"] = new SelectList(_context.MealType, "MealTypeId", "MealTypeName", batch.MealTypeId); return View(batch); } // GET: Batches/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var batch = await _context.Batch.FindAsync(id); if (batch == null) { return NotFound(); } ViewData["MealTypeId"] = new SelectList(_context.MealType, "MealTypeId", "MealTypeName", batch.MealTypeId); return View(batch); } // POST: Batches/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("BatchId,AddAmount,ProductionDate,MealTypeId")] Batch batch) { if (id != batch.BatchId) { return NotFound(); } if (ModelState.IsValid) { try { _context.Update(batch); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BatchExists(batch.BatchId)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } ViewData["MealTypeId"] = new SelectList(_context.MealType, "MealTypeId", "MealTypeName", batch.MealTypeId); return View(batch); } // GET: Batches/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var batch = await _context.Batch .Include(b => b.MealType) .FirstOrDefaultAsync(m => m.BatchId == id); if (batch == null) { return NotFound(); } return View(batch); } // POST: Batches/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var batch = await _context.Batch.FindAsync(id); _context.Batch.Remove(batch); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool BatchExists(int id) { return _context.Batch.Any(e => e.BatchId == id); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Mono.Cecil; using WebApiToTypeScript.Config; using System.Diagnostics; namespace WebApiToTypeScript.Types { public class TypeService : ServiceAware { private Regex ValidTypeNameRegex { get; } = new Regex("^[a-zA-Z_][a-zA-Z0-9_]*$"); private Dictionary<string, List<Type>> PrimitiveTypesMapping { get; } = new Dictionary<string, List<Type>>(); private List<string> ReservedWords { get; set; } = new List<string>(); public List<TypeDefinition> Types { get; } = new List<TypeDefinition>(); public TypeService() { LoadPrimitiveTypesMapping(); LoadReservedWords(); } public bool IsReservedWord(string word) { return ReservedWords.Contains(word); } public string FixIfReservedWord(string word) { return IsReservedWord(word) ? $"_{word}" : word; } public bool IsValidTypeName(string typeName) { return ValidTypeNameRegex.IsMatch(typeName); } public void LoadAllTypes(string webApiModuleFilePath) { var webApiApplicationModule = ModuleDefinition .ReadModule(webApiModuleFilePath); var corlib = ModuleDefinition.ReadModule(typeof(object).Module.FullyQualifiedName); Types.AddRange(corlib.GetTypes()); Types.AddRange(webApiApplicationModule.GetTypes()); var moduleDirectoryName = Path.GetDirectoryName(webApiModuleFilePath); foreach (var reference in webApiApplicationModule.AssemblyReferences) { var fileName = $"{reference.Name}.dll"; var path = Path.Combine(moduleDirectoryName, fileName); if (!File.Exists(path)) continue; var moduleDefinition = ModuleDefinition.ReadModule(path); Types.AddRange(moduleDefinition.GetTypes()); } } public List<TypeDefinition> GetControllers(string webApiModuleFilePath) { var webApiApplicationModule = ModuleDefinition .ReadModule(webApiModuleFilePath); return webApiApplicationModule.GetTypes() .Where(IsControllerType) .ToList(); } public bool IsNullable(TypeReference type) { var genericType = type as GenericInstanceType; return genericType != null && genericType.FullName.StartsWith("System.Nullable`1"); } public bool IsParameterOptional(ParameterDefinition parameter) { return parameter.IsOptional || !parameter.ParameterType.IsValueType || IsNullable(parameter.ParameterType); } private bool IsControllerType(TypeDefinition type) { var apiControllerType = "System.Web.Http.ApiController"; return type.IsClass && !type.IsAbstract && type.Name.EndsWith("Controller") && GetBaseTypes(type).Any(bt => bt.FullName == apiControllerType); } public IEnumerable<TypeReference> GetBaseTypes(TypeDefinition type) { var baseType = type.BaseType; while (baseType != null) { yield return baseType; var baseTypeDefinition = baseType as TypeDefinition; baseType = baseTypeDefinition?.BaseType; } } public TypeDefinition GetTypeDefinition(string typeName) { return Types .FirstOrDefault(t => t.FullName == typeName); } public CSharpType GetCSharpType(TypeReference type) { var result = new CSharpType(); result.IsValueType = type.IsValueType; var nullableType = StripNullable(type); result.IsNullable = nullableType != null; var collectionType = StripCollection(type); result.IsCollection = collectionType != null; result.IsGenericParameter = type.IsGenericParameter; result.GenericParameterName = type.Name; result.TypeDefinition = GetTypeDefinition(nullableType ?? collectionType ?? type.FullName); return result; } public TypeScriptType GetTypeScriptType(TypeReference cSharpType, string parameterName) { return GetTypeScriptType(cSharpType, parameterName, GetTypeMapping); } public TypeScriptType GetTypeScriptType(TypeReference cSharpType, string parameterName, Func<string, string, TypeMapping> getTypeMapping) { var result = new TypeScriptType(); var type = StripTask(cSharpType) ?? cSharpType; var typeName = type.FullName; var typeMapping = getTypeMapping(parameterName, type.FullName); if (typeMapping != null) { var tsTypeName = typeMapping.TypeScriptTypeName; result.TypeName = tsTypeName; result.InterfaceName = tsTypeName; result.IsPrimitive = IsPrimitiveTypeScriptType(result.TypeName); result.IsEnum = tsTypeName.StartsWith($"{Config.EnumsNamespace}") || result.IsPrimitive; return result; } typeName = StripNullable(type) ?? typeName; var collectionType = StripCollection(type); result.IsCollection = collectionType != null; typeName = collectionType ?? typeName; var typeDefinition = GetTypeDefinition(typeName); if (typeDefinition?.IsEnum ?? false) { if (!Config.GenerateEnums) { result.TypeName = "number"; result.InterfaceName = "number"; result.IsPrimitive = true; } else { EnumsService.AddEnum(typeDefinition); result.TypeName = $"{Config.EnumsNamespace}.{typeDefinition.Name}"; result.InterfaceName = $"{Config.EnumsNamespace}.{typeDefinition.Name}"; result.IsPrimitive = false; } result.IsEnum = true; return result; } var primitiveType = GetPrimitiveTypeScriptType(typeName); if (!string.IsNullOrEmpty(primitiveType)) { result.TypeName = primitiveType; result.InterfaceName = primitiveType; result.IsPrimitive = true; return result; } if (!typeDefinition?.IsValueType ?? false) { if (!Config.GenerateInterfaces) { result.TypeName = $"any"; result.InterfaceName = "any"; } else { InterfaceService.AddInterfaceNode(typeDefinition); result.TypeName = $"{Config.InterfacesNamespace}.{typeDefinition.Name}"; result.InterfaceName = $"{Config.InterfacesNamespace}.I{typeDefinition.Name}"; } return result; } var logTypeName = typeDefinition?.FullName ?? type.FullName; var isValueType = typeDefinition?.IsValueType ?? type.IsValueType; LogMessage($"Parameter [{parameterName}] of type [{logTypeName}] unmapped. IsValueType: [{isValueType}]"); result.TypeName = "any"; result.InterfaceName = "any"; result.IsPrimitive = isValueType; return result; throw new NotSupportedException("Maybe it is a generic class, or a yet unsupported collection, or chain thereof?"); } private TypeMapping GetTypeMapping(string parameterName, string typeFullName) { var typeMapping = Config.TypeMappings .FirstOrDefault(t => MatchTypeMapping(parameterName, typeFullName, t)); return typeMapping; } private bool MatchTypeMapping(string parameterName, string typeFullName, TypeMapping typeMapping) { var doesTypeNameMatch = typeFullName.StartsWith(typeMapping.WebApiTypeName); var matchExists = !string.IsNullOrEmpty(typeMapping.Match); var doesPatternMatch = matchExists && new Regex(typeMapping.Match).IsMatch(parameterName); return (doesTypeNameMatch && !matchExists) || (doesTypeNameMatch && doesPatternMatch); } public string GetPrimitiveTypeScriptType(string typeFullName) { return PrimitiveTypesMapping .Select(m => m.Value.Any(t => t.FullName == typeFullName) ? m.Key : string.Empty) .SingleOrDefault(name => !string.IsNullOrEmpty(name)); } public bool IsPrimitiveTypeScriptType(string typeScriptTypeName) { return PrimitiveTypesMapping.Keys .Contains(typeScriptTypeName); } public string StripNullable(TypeReference type) { var genericType = type as GenericInstanceType; if (genericType != null && genericType.FullName.StartsWith("System.Nullable`1") && genericType.HasGenericArguments && genericType.GenericArguments.Count == 1) { return genericType.GenericArguments.Single().FullName; } return null; } private string StripCollection(TypeReference type) { if (type.IsArray) { return type.GetElementType().FullName; } var genericCollectionTypes = new[] { "System.Collections.Generic.IList`1", "System.Collections.Generic.List`1", "System.Collections.Generic.IEnumerable`1", "System.Collections.Generic.Enumerable`1" }; var genericType = type as GenericInstanceType; if (genericType != null && genericCollectionTypes.Any(gct => genericType.FullName.StartsWith(gct)) && genericType.HasGenericArguments && genericType.GenericArguments.Count == 1) { return genericType.GenericArguments.Single().FullName; } return null; } public TypeReference StripTask(TypeReference type) { var taskType = "System.Threading.Tasks.Task"; var genericType = type as GenericInstanceType; if (genericType != null && genericType.FullName.StartsWith(taskType)) { return genericType.GenericArguments.Single(); } else if (type.FullName.StartsWith(taskType)) { return this.Types.First(x => x.FullName == "System.Void"); } return null; } private void LoadReservedWords() { ReservedWords = new List<string> { "constructor" }; } private void LoadPrimitiveTypesMapping() { var mapping = PrimitiveTypesMapping; mapping["string"] = new List<Type> { typeof(string), typeof(Guid), typeof(DateTime), typeof(TimeSpan) }; mapping["boolean"] = new List<Type> { typeof(bool) }; mapping["number"] = new List<Type> { typeof(byte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(double), typeof(decimal) }; mapping["any"] = new List<Type> { typeof(object) }; mapping["void"] = new List<Type> { typeof(void) }; } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Web; using System.Web.Script.Serialization; using System.Threading; using Microsoft.SharePoint; using Microsoft.SharePoint.WebControls; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Configuration; using System.Data.SqlClient; using System.Data; using System.IO; using System.Drawing; using YFVIC.DMS.Model.Models.Settings; using YFVIC.DMS.Model.Models.HR; using YFVIC.DMS.Model.Models.Common; using YFVIC.DMS.Model.Models.Document; using YFVIC.DMS.Model.Models.SOA; namespace YFVIC.DMS.Solution { public class FactoryUpload : IHttpHandler { public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; HttpPostedFile file = context.Request.Files[0]; string url = SPContext.Current.Web.Url; SPUser user = SPContext.Current.Web.CurrentUser; FolderMgr foldermgr = new FolderMgr(); //string tagfolderurl = ""; string uniqueid = ""; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPSite site = new SPSite(url)) { using (SPWeb web = site.OpenWeb()) { try { Byte[] filecontext = new Byte[file.ContentLength]; file.InputStream.Read(filecontext, 0, file.ContentLength); string folderurl = context.Request.Form["FolderUrl"]; string filename = context.Request.Form["FileName"]; //string newurl = context.Request.Form["NewUrl"]; //string foldername = context.Request.Form["Code"]; //string subname = context.Request.Form["Time"]; //string createtime = context.Request.Form["CreateTime"]; //string folderpath = context.Request.Form["FolderPath"]; //string folderuid =""; web.AllowUnsafeUpdates = true; SPFolder folder = web.GetFolder(folderurl); //if (foldermgr.FolderIsExist(url, newurl)) //{ // if (foldermgr.FolderIsExist(url, createtime)) // { // folder = web.GetFolder(createtime); // folderuid = folder.UniqueId.ToString(); // } // else // { // folderuid = foldermgr.CreateFolder(url, newurl, subname); // folder = web.GetFolder(new Guid(folderuid)); // } //} //else //{ // foldermgr.CreateFolder(url, folderurl, foldername); // folderuid = foldermgr.CreateFolder(url, newurl, subname); // folder = web.GetFolder(new Guid(folderuid)); //} SPFile sfile = folder.Files.Add(filename, filecontext, true); web.AllowUnsafeUpdates = false; uniqueid = sfile.UniqueId.ToString(); ResultEntity result = new ResultEntity { FileUniqueId = sfile.UniqueId.ToString(), FilePath = sfile.Url, FileName = sfile.Name, FolderUrl=folder.UniqueId.ToString() }; // docmgr.AddPermissionForFile(SPContext.Current.Site.Url, sfile.UniqueId.ToString(), loginname,"Read"); context.Response.Write(new JavaScriptSerializer().Serialize(result)); } catch (Exception ex) { if (!string.IsNullOrEmpty(uniqueid)) { web.AllowUnsafeUpdates = true; SPFile fileinfo = web.GetFile(new Guid(uniqueid)); fileinfo.Delete(); web.AllowUnsafeUpdates = false; } ResultEntity result = new ResultEntity { ErrorMessage=ex.Message, isError="true" }; context.Response.Write(new JavaScriptSerializer().Serialize(result)); } } } }); } } public class ResultEntity { public string FileUniqueId { get; set; } public string FilePath { get; set; } public string FileName { get; set; } public string ErrorMessage { get; set; } public string isError { get; set; } public string FolderUrl { get; set; } } }
namespace TripDestination.Web.MVC.ViewModels.Trip { using System; using System.Collections.Generic; using TripDestination.Web.MVC.ViewModels.Shared; public class TripRateInputModel { public int TripId { get; set; } public BaseUserViewModel Driver { get; set; } public string TripFromName { get; set; } public string TripToName { get; set; } public string DateOfLeavingFormatted { get; set; } public bool CurrentUserIsDriver { get; set; } public ICollection<BaseUserViewModel> Passengers { get; set; } public int DriverRating { get; set; } public ICollection<int> PassengerRatings { get; set; } } }
using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace ATeamFitness.Models { public class TimeBlock { [Key] public string TimeBlockId { get; set; } public string TimeBlockIdentifier { get; set; } public string TimeBlockKey { get; set; } public string TrainerName { get; set; } public string Date { get; set; } public string Time { get; set; } public string Location { get; set; } public TimeBlock() { TimeBlockId = GenerateRandomAlphanumericString(); } public string GenerateRandomAlphanumericString() { var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var stringChars = new char[50]; var random = new Random(); for (int i = 0; i < stringChars.Length; i++) { stringChars[i] = chars[random.Next(chars.Length)]; } var finalString = new String(stringChars); return finalString; } } }
namespace ProjetoEscola.Domain.Entities.Enums { public enum StatusLivro { Disponivel, Indisponivel } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace GalaxyMapView.DataSource { static class ReadData { public static string ReadSystem() { Assembly assembly = Assembly.GetExecutingAssembly(); const string path = "GalaxyMapView.DataSource.systems.json"; using (Stream stream = assembly.GetManifestResourceStream(path)) { using (StreamReader reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } public static string ReadStation() { Assembly assembly = Assembly.GetExecutingAssembly(); const string path = "GalaxyMapView.DataSource.stations.json"; using (Stream stream = assembly.GetManifestResourceStream(path)) { using (StreamReader reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } public static string ReadCommodities() { Assembly assembly = Assembly.GetExecutingAssembly(); const string path = "GalaxyMapView.DataSource.commodities.json"; using (Stream stream = assembly.GetManifestResourceStream(path)) { using (StreamReader reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using LoneWolf.Migration.Common; using LoneWolf.Migration.Files; namespace LoneWolf.Migration { public static class FileMigration { public static Result Execute(IEnumerable<string> args) { var input = args.ElementAt(1); var output = args.ElementAt(2); return Migrate(input, output); } private static Result Migrate(string input, string output) { if (!Directory.Exists(input)) return new Result("The path to input does not exist"); if (!Directory.Exists(output)) return new Result("The path to output does not exist"); try { foreach (var migration in GetMigrations(input, output)) { migration.Execute(); } return new Result("Done"); } catch (Exception ex) { return new Result(ex.GetType().Name + ": " + ex.Message + "\n" + ex.StackTrace); } } private static IEnumerable<IMigration> GetMigrations(string input, string output) { return new List<IMigration> { new ImageMigration(input, output), new SectionMigration(input, output), new PageMigration(input, output) }; } } }
using Puppeteer.Core; using Puppeteer.Core.WorldState; using System; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; namespace Puppeteer.UI { internal class AgentView : PuppeteerView { public AgentView(VisualElement _rootElement, VisualElement _leftPanel, VisualElement _rightPanel, Action<int> _updateLastSelectedCallback) : base(_rootElement, _leftPanel, _rightPanel) { m_Label = "Agents"; tooltip = "Configure and observe the agents that are currently in the scene."; var visualTreeAsset = Resources.Load<VisualTreeAsset>("LayoutAgentConfigurator"); visualTreeAsset.CloneTree(m_ConfiguratorElement); m_OnUpdateSerialisedLastSelected = _updateLastSelectedCallback; OnListItemSelectedOrRemoved = ListItemSelectedOrRemoved; ReloadAgentListItems(); EditorApplication.playModeStateChanged += EditorPlayModeStateChanged; } ~AgentView() { EditorApplication.playModeStateChanged -= EditorPlayModeStateChanged; } public void AddPrefabIcon(VisualElement _iconContainer, PuppeteerAgent _agent) { _iconContainer.hierarchy.Clear(); GameObject prefabObject = PrefabUtility.GetCorrespondingObjectFromSource(_agent.gameObject); string path = prefabObject != null ? AssetDatabase.GetAssetPath(prefabObject) : null; IMGUIContainer icon = new IMGUIContainer(() => { if (path != null) { GameObject asset = AssetDatabase.LoadAssetAtPath<GameObject>(path); Editor editor = GetPreviewEditor(asset); editor.OnPreviewGUI(GUILayoutUtility.GetRect(170, 170), new GUIStyle() { normal = { background = Texture2D.whiteTexture } }); } else { GUILayout.Label("Not a Prefab."); } }) { focusable = false, name = "prefabIcon", }; icon.AddToClassList("prefabIcon"); _iconContainer.hierarchy.Add(icon); } public override void RegisterTabViewCallbacks(TabView _tabView) { _tabView.OnTabListItemDeleted += OtherTabArchetypeListItemDeleted; } private void OtherTabArchetypeListItemDeleted(ListItem _deletedListItem) { if (_deletedListItem is ArchetypeListItem deletedArchetypeListItem) { for (int i = 0; i < m_ListItems.Count; ++i) { if (m_ListItems[i] is AgentListItem agentListItem) { PuppeteerAgent agent = agentListItem.GetAgent(); if (agent == null) { continue; } if (agent.ArchetypeGUID != deletedArchetypeListItem.GetDescription().GUID) { continue; } agent.ArchetypeGUID = Guid.Empty; } } } } public override void CleanUp() { for (int i = 0; i < m_ListItems.Count; ++i) { if (m_ListItems[i] is AgentListItem agentListItem) { if (agentListItem.GetAgent() == null) { continue; } agentListItem.GetAgent().OnPuppeteerAgentDestroy -= PuppeteerAgentDestroy; } } } public override void CloseView() { base.CloseView(); if (m_PreviewEditors != null) { // The editors need to be destroyed so the playableGraphs they contain don't leak memory. for (int i = 0; i < m_PreviewEditors.Count; ++i) { UnityEngine.Object.DestroyImmediate(m_PreviewEditors[0]); } m_PreviewEditors.Clear(); } m_AddButton.visible = true; UnregisterWindowCallbacks(); OnListItemDeselected -= ListItemDeselected; } public Editor GetPreviewEditor(GameObject _asset) { if (m_PreviewEditors == null) { m_PreviewEditors = new List<Editor>(); } foreach (Editor editor in m_PreviewEditors) { if ((GameObject)editor.target == _asset) { return editor; } } Editor newEditor = Editor.CreateEditor(_asset); m_PreviewEditors.Add(newEditor); return newEditor; } public override void OpenView(SerialisedConfiguratorState _serialisedConfiguratorStates) { OpenView(_serialisedConfiguratorStates.LastOpenedAgentObjectID); } public void TryOpenEntry(int _instanceID) { var matchingItem = m_ListItems.Find(_entry => (_entry as AgentListItem).GetAgent().gameObject.GetInstanceID() == _instanceID); if (matchingItem != null) { UpdateSelectedListItem(matchingItem); } } protected override void LazyInitConfigurator() { if (m_AgentConfigurator != null) { return; } m_AgentConfigurator = new AgentConfigurator { ArchetypeField = m_ConfiguratorElement.Q<ArchetypeSelectorField>(name: "archetypeSelector"), AgentName = m_ConfiguratorElement.Q<TextField>(name: "gameObjectName"), PrefabIcon = m_ConfiguratorElement.Q<VisualElement>(name: "prefabIconFrame"), WorkingMemoryContainer = m_ConfiguratorElement.Q<VisualElement>(name: "workingMemoryContainer"), PlanContainer = m_ConfiguratorElement.Q<VisualElement>(name: "planContainer"), OpenVisualiserButton = m_ConfiguratorElement.Q<Button>(name: "openVisualiser"), }; m_AgentConfigurator.OpenVisualiserButton.clickable.clicked += () => { PuppeteerPlanVisualiserWindow.CreateWindow(); }; RegisterConfiguratorCallbacks(); } protected override void UpdateConfigurator() { if (m_SelectedListItem is AgentListItem selectedAgentListItem) { EnableRightPanelContent(); LazyInitConfigurator(); PuppeteerAgent selectedAgent = selectedAgentListItem.GetAgent(); if (selectedAgent == null) { return; } EnsureArchetypeSelectorIsInSync(); m_AgentConfigurator.ArchetypeField.SetValueWithoutNotify(selectedAgent.ArchetypeGUID); m_AgentConfigurator.AgentName.Unbind(); m_AgentConfigurator.AgentName.Bind(new SerializedObject(selectedAgent.gameObject)); AddPrefabIcon(m_AgentConfigurator.PrefabIcon, selectedAgent); UpdateWorkingMemoryDisplay(selectedAgent); UpdatePlanDisplay(selectedAgent); } } private void AgentArchetypeChanged(Guid _oldGuid, Guid _newGuid) { EnsureArchetypeSelectorIsInSync(); m_AgentConfigurator.ArchetypeField.SetValueWithoutNotify(_newGuid); } private void ArchetypeFieldChangedEvent(ChangeEvent<Guid> _event) { PuppeteerAgent selectedAgent = (m_SelectedListItem as AgentListItem)?.GetAgent(); if (selectedAgent == null) { return; } selectedAgent.ArchetypeGUID = _event.newValue; EditorUtility.SetDirty(selectedAgent); } private AgentListItem CreateAgentListItem(PuppeteerAgent _agent) { AgentListItem item = new AgentListItem(_agent); item.OnMouseDown += UpdateSelectedListItem; m_ListItems.Add(item); _agent.OnPuppeteerAgentDestroy += PuppeteerAgentDestroy; return item; } private void EditorPlayModeStateChanged(PlayModeStateChange _stateChange) { switch (_stateChange) { case PlayModeStateChange.EnteredEditMode: case PlayModeStateChange.EnteredPlayMode: if (m_IsOpen) { CloseView(); ReloadAgentListItems(); m_SelectedListItem = null; OpenView(m_LastSelectedAgentObjectID); } else { ReloadAgentListItems(); } break; case PlayModeStateChange.ExitingEditMode: case PlayModeStateChange.ExitingPlayMode: break; default: break; } } private void EnsureArchetypeSelectorIsInSync() { PuppeteerAgent selectedAgent = (m_SelectedListItem as AgentListItem)?.GetAgent(); if (selectedAgent == null) { return; } ref var archetypeField = ref m_AgentConfigurator.ArchetypeField; if (!archetypeField.IsInSync()) { PuppeteerEditorHelper.ReplaceArchetypeSelectorField(ref archetypeField, selectedAgent.ArchetypeGUID, ArchetypeFieldChangedEvent); } } private void ListItemDeselected(ListItem _listItem) { if (_listItem is AgentListItem deselectedAgentListItem) { PuppeteerAgent deselectedAgent = deselectedAgentListItem.GetAgent(); deselectedAgent.OnWorkingMemoryChanged -= SelectedAgentWorkingMemoryChanged; deselectedAgent.OnArchetypeChanged -= AgentArchetypeChanged; } } private void ListItemSelectedOrRemoved(ListItem _listItem) { if (_listItem == null) { m_OnUpdateSerialisedLastSelected?.Invoke(0); m_LastSelectedAgentObjectID = 0; } else { PuppeteerAgent selectedAgent = (_listItem as AgentListItem).GetAgent(); int selectedInstanceID = selectedAgent.gameObject.GetInstanceID(); m_LastSelectedAgentObjectID = selectedInstanceID; m_OnUpdateSerialisedLastSelected?.Invoke(selectedInstanceID); selectedAgent.OnArchetypeChanged += AgentArchetypeChanged; } } private void OpenView(int _lastOpenedAgentObjectID) { base.OpenView(null); m_ListItemScrollViewHeader.text = "Agents in Scene"; m_ListItemScrollViewHeaderIcon.image = PuppeteerEditorResourceLoader.AgentIcon32.texture; m_AddButton.visible = false; m_RightPanelContent.Q<Label>(name: "GUIDLabel").text = string.Empty; for (int i = 0; i < m_ListItems.Count; ++i) { m_ListItemScrollView.Add(m_ListItems[i]); } if (m_SelectedListItem != null) { UpdateConfigurator(); } else if (_lastOpenedAgentObjectID != 0) { TryOpenEntry(_lastOpenedAgentObjectID); } else { DisableRightPanelContent(); } OnListItemDeselected = ListItemDeselected; RegisterWindowCallbacks(); } private void PuppeteerAgentDestroy(PuppeteerAgent _agent) { ListItem foundListItem = m_ListItems.Find(_entry => (_entry as AgentListItem).GetAgent() == _agent); if (foundListItem != null) { foundListItem.RemoveFromHierarchy(); m_ListItems.Remove(foundListItem); } } private void RegisterConfiguratorCallbacks() { m_AgentConfigurator.ArchetypeField.RegisterCallback<ChangeEvent<System.Guid>>(ArchetypeFieldChangedEvent); m_AgentConfigurator.ArchetypeField.RegisterCallback<MouseEnterEvent>(_event => { EnsureArchetypeSelectorIsInSync(); }); m_AgentConfigurator.AgentName.RegisterCallback<ChangeEvent<string>>(_change => { if (m_SelectedListItem is AgentListItem selectedAgentListItem) { m_SelectedListItem.ChangeText(_change.newValue); } }); } private void RegisterWindowCallbacks() { m_RootElement.RegisterCallback<MouseEnterEvent>(UpdateAgentsOnEnterWindow); } private void ReloadAgentListItems() { m_ListItems.Clear(); HashSet<PuppeteerAgent> puppets = PuppeteerManager.Instance.GetAgents(); if (puppets.Count > 0) { foreach (var puppet in PuppeteerManager.Instance.GetAgents().OrderBy(_entry => _entry.name)) { CreateAgentListItem(puppet); } } } private void SelectedAgentWorkingMemoryChanged(WorldState<string, object> _worldState) { foreach (KeyValuePair<string, object> memoryEntry in _worldState) { WorkingMemoryItem matchingItem = m_WorkingMemoryListItems.Find(_entry => _entry.GetKey().Equals(memoryEntry.Key)); if (matchingItem == null) { WorkingMemoryItem newWorkingMemoryItem = new WorkingMemoryItem(memoryEntry); m_WorkingMemoryListItems.Add(newWorkingMemoryItem); } else { if (!memoryEntry.Value.Equals(matchingItem.GetValue())) { matchingItem.SetValueWithoutNotify(memoryEntry.Value); } } } PuppeteerAgent selectedAgent = (m_SelectedListItem as AgentListItem)?.GetAgent(); UpdatePlanDisplay(selectedAgent); } private void UnregisterWindowCallbacks() { m_RootElement.UnregisterCallback<MouseEnterEvent>(UpdateAgentsOnEnterWindow); } private void UpdateAgentsOnEnterWindow(MouseEnterEvent _enterEvent) { if (m_SelectedListItem != null) { UpdateConfigurator(); } else { DisableRightPanelContent(); } OnListItemDeselected = ListItemDeselected; } private void UpdatePlanDisplay(PuppeteerAgent _selectedAgent) { m_AgentConfigurator.PlanContainer.Clear(); if (_selectedAgent.GetActiveAction() != null) { m_AgentConfigurator.PlanContainer.Add(new PlanItem(PlanItem.PlanItemType.ActiveAction, _selectedAgent.GetActiveAction().GetLabel())); } Plan<string, object> plan = _selectedAgent.GetPlan(); if (plan != null) { foreach (var item in _selectedAgent.GetPlan()) { m_AgentConfigurator.PlanContainer.Add(new PlanItem(PlanItem.PlanItemType.InactiveAction, item.GetLabel())); } PuppeteerGoal activeGoal = _selectedAgent.GetActiveGoal(); if (activeGoal != null) { var goalDesc = PuppeteerManager.Instance.GetGoalDescription(activeGoal.DescriptionGUID); m_AgentConfigurator.PlanContainer.Add(new PlanItem(PlanItem.PlanItemType.ActiveGoal, goalDesc.DisplayName)); } } } private void UpdateWorkingMemoryDisplay(PuppeteerAgent _selectedAgent) { m_AgentConfigurator.WorkingMemoryContainer.Clear(); m_WorkingMemoryListItems.Clear(); foreach (KeyValuePair<string, object> memoryEntry in _selectedAgent.GetWorkingMemory()) { // #performancePotential: Cache working memory items instead of clearing and creating new ones WorkingMemoryItem workingMemoryItem = new WorkingMemoryItem(memoryEntry); m_AgentConfigurator.WorkingMemoryContainer.Add(workingMemoryItem); m_WorkingMemoryListItems.Add(workingMemoryItem); } _selectedAgent.OnWorkingMemoryChanged += SelectedAgentWorkingMemoryChanged; } private readonly Action<int> m_OnUpdateSerialisedLastSelected; private readonly List<WorkingMemoryItem> m_WorkingMemoryListItems = new List<WorkingMemoryItem>(); private AgentConfigurator m_AgentConfigurator = null; private int m_LastSelectedAgentObjectID = 0; private List<Editor> m_PreviewEditors; private class AgentConfigurator { public TextField AgentName; public ArchetypeSelectorField ArchetypeField; public Button OpenVisualiserButton; public VisualElement PlanContainer; public VisualElement PrefabIcon; public VisualElement WorkingMemoryContainer; } } }
using System; using System.Collections.Generic; using System.Text; namespace InterfaceExampleProject { class HelloInSpanish : ISpeakable { public void SayHello() { Console.WriteLine("Hola"); } public void SayGoodbye() { Console.WriteLine("Adios"); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using log4net; using WpfApp1.Utils; namespace WpfApp1.Views { /// <summary> /// Interaction logic for Login.xaml /// </summary> public partial class Login : UserControl { private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public Login() { InitializeComponent(); // Database.CheckLogin("", ""); } public void LoginButton(object sender, RoutedEventArgs e) { if (!Database.CheckLogin(Username.Text, Password.Password)) { MessageBox.Show("Incorrect Username/Password"); return; } // if (Username.Text != "home" || Password.Password != "1234") // { // MessageBox.Show("Incorrect Username/Password"); // } var window = Application.Current.MainWindow as MainWindow; //window.ContentTemplate = MainWindow // MainWindow.SwitchView = 1; window.TabView.Visibility = Visibility.Visible; Visibility = Visibility.Hidden; Log.Info("Logged in"); Trace.WriteLine("text"); } } }
using System.Data; using MySql.Data.MySqlClient; using System.Data.SqlClient; namespace DatabaseSQLtoMSSQL { class Program { static void Main(string[] args) { // ms sql connection string string mssqlConnection = "Server =server_address; Database =DBName; Uid =UserName; Pwd =Password"; SqlConnection mssqlConn = new SqlConnection(mssqlConnection); mssqlConn.Open(); // mysql connectioin string string ConnectionString = "Server =server_address; Database =DBName; Uid =UserName; Pwd =Password"; MySqlConnection conn = new MySqlConnection(ConnectionString); conn.Open(); // go get the information from the mySql table MySqlCommand myCommand = new MySqlCommand("select * from AllRelVar", conn); // make a data table to hold the info DataTable table = new DataTable(); // load the query results into the table table.Load(myCommand.ExecuteReader()); // copy the table to its new home in the ms sql table using (SqlBulkCopy bulk = new SqlBulkCopy(mssqlConn)) { // tell it which table to copy to bulk.DestinationTableName = "ReligionsAll"; // copy the info bulk.WriteToServer(table); } // close both connections mssqlConn.Close(); conn.Close(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Audio; using System.Reflection; using System.IO; #if UNITY_EDITOR using UnityEditor; #endif namespace AlmenaraGames { [CreateAssetMenu(fileName = "New Audio Object", menuName = "Multi Listener Pooling Audio System/Audio Object")] [HelpURL("https://almenaragames.github.io/#CSharpClass:AlmenaraGames.AudioObject")] public class AudioObject : ScriptableObject { [Tooltip("The identifier to get this Audio Object.")] /// <summary> /// The identifier for get this Audio Object. /// </summary> public string identifier=string.Empty; /// <summary> /// Gets or sets the clips. /// </summary> /// <value>The clips.</value> public AudioClip[] clips=new AudioClip[0]; /// <summary> /// Returns a random clip. /// </summary> public AudioClip RandomClip { get { //Some other code return clips.Length>0?clips[Random.Range(0,clips.Length)]:null; } } [Space(10)] [Tooltip("Sets the overall volume of the sound")] [Range(0,1)] /// <summary> /// The overall volume of the sound. /// </summary> public float volume = 1; [Space(5)] [Tooltip("Sets the spread of a 3d sound in speaker space")] [Range(0,360)] /// <summary> /// The spread of a 3d sound in speaker space. /// </summary> public float spread = 0f; [Space(5)] [Tooltip("Sets the frequency of the sound. Use this to slow down or speed up the sound. A negative pitch value will going to make the sound plays backwards")] [Range(-3,3)] /// <summary> /// The frequency of the sound. Use this to slow down or speed up the sound. A negative pitch value will going to make the sound plays backwards. /// </summary> public float pitch = 1; [Space(5)] [Tooltip("A 2D sound ignores all types of spatial attenuation, thats include spatial position and spread")] /// <summary> /// A 2D sound ignores all types of spatial attenuation, thats include spatial position and spread. /// </summary> public bool spatialMode2D = false; [Space(5)] [Tooltip("Only for 2D sound")] [Range(-1,1)] /// <summary> /// The 2D Stereo pan. /// </summary> public float stereoPan = 0; [Space(10)] [Tooltip("Sets the source to loop")] /// <summary> /// Is the audio clip looping?. If you disable looping on a playing source the sound will stop after the end of the current loop. /// </summary> public bool loop = false; /// <summary> /// The source will going to automatically changes the current clip to the next clip on the list when this Audio Object repeats. /// </summary> [Tooltip("The source will going to automatically changes the current clip to the next clip on the list when this Audio Object repeats")] [UnityEngine.Serialization.FormerlySerializedAs("loopClipsSequentially")] public bool playClipsSequentially = false; [Space(10)] [Tooltip("Sets the priority of the sound. Note that a sound with a larger priority value will more likely be stolen by sounds with smaller priority values")] [Range(0,256)] /// <summary> /// The priority of the sound. Note that a sound with a larger priority value will more likely be stolen by sounds with smaller priority values. /// </summary> public int priority = 128; [Space(5)] [Tooltip("Limits how many Multi Audio Sources can be playing this Audio Object at the same time (0 = No Limits)")] /// <summary> /// Limits how many Multi Audio Sources can be playing this Audio Object at the same time (0 = No Limits). /// </summary> public uint maxSources = 0; [Space(10)] [Tooltip("Withing the Min Distance, the volume will stay at the loudest possible. Outside of this Min Distance it begins to attenuate")] /// <summary> /// Withing the Min Distance, the volume will stay at the loudest possible. Outside of this Min Distance it begins to attenuate. /// </summary> public float minDistance = 1; [Tooltip("Max Distance is the distance where the sound is completely inaudible")] /// <summary> /// Max Distance is the distance where the sound is completely inaudible. /// </summary> public float maxDistance = 20; [Space(10)] [Tooltip("Min random value for multiply the pitch of the sound")] [Range(0.75f,1)] /// <summary> /// Min random value for multiply the pitch of the sound. /// </summary> public float minPitchMultiplier = 0.9f; [Tooltip("Max random value for multiply the pitch of the sound")] [Range(1,1.25f)] /// <summary> /// Max random value for multiply the pitch of the sound. /// </summary> public float maxPitchMultiplier = 1.1f; [Space(10)] [Tooltip("Min random value for multiply the volume of the sound")] [Range(0.25f,1)] /// <summary> /// Min random value for multiply the volume of the sound. /// </summary> public float minVolumeMultiplier = 0.8f; [Tooltip("Max random value for multiply the volume of the sound")] [Range(1,1.75f)] /// <summary> /// Max random value for multiply the volume of the sound. /// </summary> public float maxVolumeMultiplier = 1.2f; [Space(10)] [Tooltip("The amount by which the signal from the sound will be mixed into the global reverb associated with the Reverb from the listeners. The range from 0 to 1 is linear (like the volume property) while the range from 1 to 1.1 is an extra boost range that allows you to boost the reverberated signal by 10 dB")] [Range(0,1.1f)] /// <summary> /// The amount by which the signal from the sound will be mixed into the global reverb associated with the Reverb from the listeners. The range from 0 to 1 is linear (like the volume property) while the range from 1 to 1.1 is an extra boost range that allows you to boost the reverberated signal by 10 dB. /// </summary> public float reverbZoneMix = 1; [Space(10)] [Tooltip("Specifies how much the pitch is changed based on the relative velocity between the listener and the source")] [Range(0,5f)] /// <summary> /// Specifies how much the pitch is changed based on the relative velocity between the listener and the source. /// </summary> public float dopplerLevel = 0.25f; [Space(10)] [Tooltip("Enables or disables sound attenuation over distance")] /// <summary> /// Enables or disables sound attenuation over distance. /// </summary> public bool volumeRolloff = true; [Tooltip("Sets how the sound attenuates over distance")] /// <summary> /// The volume rolloff curve. Sets how the sound attenuates over distance. /// </summary> public AnimationCurve volumeRolloffCurve=AnimationCurve.EaseInOut(0,0,1,1); [Space(10)] [Tooltip("Set whether the sound should play through an Audio Mixer first or directly to the Listener. Leave NULL to use the default SFX/BGM output specified in the <b>Multi Listener Pooling Audio System Config</b>.")] /// <summary> /// Set whether the sound should play through an Audio Mixer first or directly to the Listener. /// </summary> public AudioMixerGroup mixerGroup; [Space(10)] [Tooltip("Enables or disables custom spatialization for the source")] /// <summary> /// Enables or disables custom spatialization for the source. /// </summary> public bool spatialize; [Space(10)] [Tooltip("is the sound a BGM?")] /// <summary> /// Is the sound a BGM?. /// </summary> public bool isBGM = false; #if UNITY_EDITOR [InitializeOnLoad] [CanEditMultipleObjects] [CustomEditor(typeof(AudioObject))] public class AudioObjectEditor : Editor { SerializedObject audioObj; SerializedProperty _clips; SerializedProperty rollOffCurve; SerializedProperty minDistance; SerializedProperty maxDistance; SerializedProperty minPitchMultiplier; SerializedProperty maxPitchMultiplier; SerializedProperty minVolumeMultiplier; SerializedProperty maxVolumeMultiplier; SerializedProperty identifier; SerializedProperty loopClipsSequentially; private Texture playIcon; private Texture stopIcon; private Texture addIcon; private Texture removeIcon; private Texture emptyIcon; private static bool unfolded = true; int currentPickerWindow = -1; private static readonly string[] _dontIncludeMe_0 = new string[] { "m_Script", "playClipsSequentially", "clips", "identifier", "maxDistance", "minDistance", "playClipsSequentially", "priority", "maxSources", "minDistance", "maxDistance", "minVolumeMultiplier", "maxVolumeMultiplier", "minPitchMultiplier", "maxPitchMultiplier", "reverbZoneMix", "dopplerLevel", "volumeRolloff", "volumeRolloffCurve", "mixerGroup", "spatialize", "isBGM" }; private static readonly string[] _dontIncludeMe_1 = new string[] { "m_Script", "playClipsSequentially", "clips", "identifier", "maxDistance", "minDistance", "volume", "spread", "pitch", "spatialMode2D", "stereoPan", "loop", "minVolumeMultiplier", "maxVolumeMultiplier", "minPitchMultiplier", "maxPitchMultiplier", "reverbZoneMix", "dopplerLevel", "volumeRolloff", "volumeRolloffCurve", "mixerGroup", "spatialize", "isBGM" }; private static readonly string[] _dontIncludeMe_2 = new string[] { "m_Script", "playClipsSequentially", "clips", "identifier", "maxDistance", "minDistance", "volume", "spread", "pitch", "spatialMode2D", "stereoPan", "loop", "playClipsSequentially", "priority", "maxSources", "minDistance", "maxDistance", "minVolumeMultiplier", "maxVolumeMultiplier", "minPitchMultiplier", "maxPitchMultiplier", "reverbZoneMix", "dopplerLevel", "volumeRolloff", "volumeRolloffCurve", "mixerGroup", "spatialize", "isBGM" }; private static readonly string[] _dontIncludeMe_3 = new string[] { "m_Script", "playClipsSequentially", "clips", "identifier", "maxDistance", "minDistance", "volume", "spread", "pitch", "spatialMode2D", "stereoPan", "loop", "playClipsSequentially", "priority", "maxSources", "minDistance", "maxDistance", "minPitchMultiplier", "maxPitchMultiplier", "minVolumeMultiplier", "maxVolumeMultiplier", "mixerGroup", "spatialize", "isBGM" }; private static readonly string[] _dontIncludeMe_4 = new string[] { "m_Script", "playClipsSequentially", "clips", "identifier", "maxDistance", "minDistance", "volume", "spread", "pitch", "spatialMode2D", "stereoPan", "loop", "playClipsSequentially", "priority", "maxSources", "minDistance", "maxDistance", "minPitchMultiplier", "maxPitchMultiplier", "minVolumeMultiplier", "maxVolumeMultiplier", "reverbZoneMix", "dopplerLevel", "volumeRolloff", "volumeRolloffCurve" }; private object[] droppedObjects; bool showError = false; AudioObject lastSameId; void OnEnable() { audioObj = new SerializedObject(targets); _clips = audioObj.FindProperty("clips"); rollOffCurve = audioObj.FindProperty("volumeRolloffCurve"); minDistance = audioObj.FindProperty("minDistance"); maxDistance = audioObj.FindProperty("maxDistance"); minPitchMultiplier = audioObj.FindProperty("minPitchMultiplier"); maxPitchMultiplier = audioObj.FindProperty("maxPitchMultiplier"); minVolumeMultiplier = audioObj.FindProperty("minVolumeMultiplier"); maxVolumeMultiplier = audioObj.FindProperty("maxVolumeMultiplier"); identifier = audioObj.FindProperty("identifier"); loopClipsSequentially = audioObj.FindProperty("playClipsSequentially"); playIcon = Resources.Load("MLPASImages/playIcon") as Texture; stopIcon = Resources.Load("MLPASImages/pauseIcon") as Texture; addIcon = Resources.Load("MLPASImages/addIcon") as Texture; removeIcon = Resources.Load("MLPASImages/removeIcon") as Texture; emptyIcon = Resources.Load("MLPASImages/emptyIcon") as Texture; globalAudioObjects = Resources.LoadAll<AudioObject>("Global Audio Objects"); if (!string.IsNullOrEmpty(identifier.stringValue)) { foreach (var itemTest in globalAudioObjects) { if (itemTest != (audioObj.targetObject as AudioObject) && itemTest.identifier == identifier.stringValue) { showError = true; } } } } private static bool _isRegistered = false; private static bool _didSelectionChange = false; private static Object prevSelection; private AudioObject[] globalAudioObjects; private void OnSelectionChanged() { _didSelectionChange = true; } private void OnEditorUpdate() { if (Selection.activeObject != null) prevSelection = Selection.activeObject; if (_didSelectionChange) { _didSelectionChange = false; if (!Application.isPlaying) { if (prevSelection != null && prevSelection.GetType() == typeof(AudioObject)) StopAllClips(); } } } bool GetSingleBoolValue(SerializedProperty _property) { foreach (var targetObject in audioObj.targetObjects) { SerializedObject iteratedObject = new SerializedObject(targetObject); SerializedProperty iteratedProperty = iteratedObject.FindProperty(_property.propertyPath); if (iteratedProperty.boolValue) { return true; } } return false; } public override void OnInspectorGUI() { audioObj.Update(); if (!_isRegistered) { _isRegistered = true; Selection.selectionChanged += OnSelectionChanged; EditorApplication.update += OnEditorUpdate; Undo.undoRedoPerformed += CheckIdentifier; #if UNITY_2017_2_OR_NEWER EditorApplication.playModeStateChanged += PlayModeChange; #else EditorApplication.playmodeStateChanged += PlayModeChangeOlder; #endif } //GUILayout.Space (15f); var centeredStyle = new GUIStyle(GUI.skin.GetStyle("Button")); centeredStyle.alignment = TextAnchor.MiddleCenter; centeredStyle.stretchWidth = true; GUIStyle playButton = new GUIStyle(EditorStyles.toolbarButton); playButton.stretchWidth = false; if (!audioObj.isEditingMultipleObjects) { if (GUILayout.Button(audioObj.targetObject.name.ToUpper() + " Properties", EditorStyles.miniLabel)) { EditorGUIUtility.PingObject(audioObj.targetObject); } GUILayout.Space(15f); unfolded = EditorGUILayout.Foldout(unfolded, "Audio Clips" + " (" + _clips.arraySize.ToString() + ")"); } else { GUILayout.Space(15f); EditorGUILayout.LabelField("Audio Clips", "(Not Supported while Multi-Editing)"); } if (unfolded && !audioObj.isEditingMultipleObjects) { GUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.BeginHorizontal(); currentPickerWindow = EditorGUIUtility.GetControlID(FocusType.Passive) + 10; if (GUILayout.Button(addIcon, playButton)) { _clips.InsertArrayElementAtIndex(_clips.arraySize); EditorGUIUtility.ShowObjectPicker<AudioClip>(null, false, "", currentPickerWindow); } if (Event.current.commandName == "ObjectSelectorUpdated" && EditorGUIUtility.GetObjectPickerControlID() == currentPickerWindow) { currentPickerWindow = -1; AudioClip newAudioClip = EditorGUIUtility.GetObjectPickerObject() as AudioClip; _clips.GetArrayElementAtIndex(_clips.arraySize - 1).objectReferenceValue = newAudioClip; } GUILayout.Label("Add Audio Clip", EditorStyles.miniLabel); GUILayout.EndHorizontal(); for (int i = 0; i < _clips.arraySize; i++) { bool hasClip = _clips.GetArrayElementAtIndex(i).objectReferenceValue != null; GUILayout.BeginHorizontal(); if (GUILayout.Button(removeIcon, playButton)) { StopAllClips(); _clips.GetArrayElementAtIndex(i).objectReferenceValue = null; _clips.DeleteArrayElementAtIndex(i); } if (hasClip) { if (GUILayout.Button(hasClip ? playIcon : emptyIcon, playButton)) { if (hasClip) { StopAllClips(); PlayClip(_clips.GetArrayElementAtIndex(i).objectReferenceValue as AudioClip); } } if (GUILayout.Button(hasClip ? stopIcon : emptyIcon, playButton)) { if (hasClip) { StopClip(_clips.GetArrayElementAtIndex(i).objectReferenceValue as AudioClip); } } } if (_clips.arraySize > i) { _clips.GetArrayElementAtIndex(i).objectReferenceValue = EditorGUILayout.ObjectField(_clips.GetArrayElementAtIndex(i).objectReferenceValue, typeof(AudioClip), false); } GUILayout.EndHorizontal(); } droppedObjects = DropZone(); if (droppedObjects != null && droppedObjects.Length > 0) { foreach (var item in droppedObjects) { if (item.GetType() == typeof(AudioClip)) { _clips.InsertArrayElementAtIndex(_clips.arraySize); _clips.GetArrayElementAtIndex(_clips.arraySize - 1).objectReferenceValue = item as AudioClip; } } } GUILayout.EndVertical(); } GUILayout.Space(10f); if (!audioObj.isEditingMultipleObjects) { string oldIdentifier = identifier.stringValue; identifier.stringValue = EditorGUILayout.TextField(new GUIContent("Identifier", "The identifier to get this Audio Object.\nRemember that the Audio Object needs to be in the \"Resources\\Global Audio Objects\" folder in order to be accessed via this identifier"), identifier.stringValue); if (showError) { EditorGUILayout.HelpBox("Some Audio Object has the same identifier, the identifier needs to be unique.", MessageType.Error); if (lastSameId != null && lastSameId.identifier != identifier.stringValue) showError = false; } if (!string.IsNullOrEmpty(identifier.stringValue)) { if (oldIdentifier != identifier.stringValue) { showError = false; foreach (var itemTest in globalAudioObjects) { if (itemTest != (audioObj.targetObject as AudioObject) && itemTest.identifier == identifier.stringValue) { showError = true; lastSameId = itemTest; } } } string path = AssetDatabase.GetAssetPath(audioObj.targetObject); if (!path.Contains("Resources/Global Audio Objects")) { EditorGUILayout.HelpBox("The AudioObject needs to be inside the \"Resources\\Global Audio Objects\" folder in order to be accessed via this identifier.\n\nIt can be also in a subfolder if it is inside the \"Global Audio Objects\" folder", MessageType.Warning); if (!path.Contains("Resources") || !path.Contains("Global Audio Objects") && path.Contains("Resources/" + Path.GetFileName(AssetDatabase.GetAssetPath(audioObj.targetObject)))) { if (GUILayout.Button("Try to fix Asset Path", EditorStyles.miniButton)) { string assetName = Path.GetFileName(AssetDatabase.GetAssetPath(audioObj.targetObject)); string newPath = (!path.Contains("Resources") ? "Resources/" : "") + "Global Audio Objects" + "/" + assetName; if (!path.Contains("Resources") && !path.Contains("Global Audio Objects")) { if (!AssetDatabase.IsValidFolder(path.Replace(assetName, newPath).Replace("/" + assetName, ""))) { if (!AssetDatabase.IsValidFolder(path.Replace(assetName, newPath.Replace("/" + assetName, "").Replace("/Global Audio Objects", "")))) { AssetDatabase.CreateFolder(path.Replace("/" + assetName, ""), "Resources"); } if (!AssetDatabase.IsValidFolder(path.Replace(assetName, newPath).Replace("/" + assetName, ""))) { AssetDatabase.CreateFolder(path.Replace("/" + assetName, "") + "/Resources", "Global Audio Objects"); } } } else if (!path.Contains("Global Audio Objects")) { if (!AssetDatabase.IsValidFolder(path.Replace("/" + assetName, "") + "/Global Audio Objects")) { AssetDatabase.CreateFolder(path.Replace("/" + assetName, ""), "Global Audio Objects"); } } string testMove = AssetDatabase.MoveAsset(path, path.Replace(assetName, newPath)); if (testMove == "") { EditorGUIUtility.PingObject(audioObj.targetObject); Selection.activeObject = audioObj.targetObject; Debug.Log(assetName + " Moved to: " + "Resources/Global Audio Objects"); } else { Debug.LogError("Error while trying to fix path for: " + assetName); } } } } } } else { EditorGUILayout.LabelField("Identifier", "(Not Supported while Multi-Editing)"); } DrawPropertiesExcluding(audioObj, _dontIncludeMe_0); EditorGUILayout.Space(); Tools.MLPASExtensionMethods.Toggle(loopClipsSequentially, new GUIContent("Play Clips Sequentially", "The source will going to automatically changes the current clip to the next clip on the list when this Audio Object repeats")); DrawPropertiesExcluding(audioObj, _dontIncludeMe_1); EditorGUILayout.Space(); Tools.MLPASExtensionMethods.FloatField(minDistance, new GUIContent("Min Distance", "Withing the Min Distance, the volume will stay at the loudest possible. Outside of this Min Distance it begins to attenuate"), 0, float.MaxValue); Tools.MLPASExtensionMethods.FloatField(maxDistance, new GUIContent("Max Distance", "Max Distance is the distance where the sound is completely inaudible"), !audioObj.isEditingMultipleObjects ? minDistance.floatValue : GetMinDistanceValue(minDistance), float.MaxValue); EditorGUILayout.Space(); EditorGUILayout.Slider(minPitchMultiplier, 0.75f, 1f, new GUIContent("Min Pitch Multiplier" + " (" + Mathf.RoundToInt(minPitchMultiplier.floatValue * 100 - 100).ToString() + "%)", "Min random value for multiply the pitch of the sound")); EditorGUILayout.Slider(maxPitchMultiplier, 1f, 1.25f, new GUIContent("Max Pitch Multiplier" + " (" + Mathf.RoundToInt(maxPitchMultiplier.floatValue * 100 - 100).ToString() + "%)", "Max random value for multiply the pitch of the sound")); if (GUILayout.Button("Disable Random Pitch Multiplier at Start", EditorStyles.miniButton)) { minPitchMultiplier.floatValue = 1; maxPitchMultiplier.floatValue = 1; } DrawPropertiesExcluding(audioObj, _dontIncludeMe_2); EditorGUILayout.Space(); EditorGUILayout.Slider(minVolumeMultiplier, 0.25f, 1f, new GUIContent("Min Volume Multiplier" + " (" + Mathf.RoundToInt(minVolumeMultiplier.floatValue * 100 - 100).ToString() + "%)", "Min random value for multiply the volume of the sound")); EditorGUILayout.Slider(maxVolumeMultiplier, 1f, 1.75f, new GUIContent("Max Volume Multiplier" + " (" + Mathf.RoundToInt(maxVolumeMultiplier.floatValue * 100 - 100).ToString() + "%)", "Max random value for multiply the volume of the sound")); if (GUILayout.Button("Disable Random Volume Multiplier at Start", EditorStyles.miniButton)) { minVolumeMultiplier.floatValue = 1; maxVolumeMultiplier.floatValue = 1; } DrawPropertiesExcluding(audioObj, _dontIncludeMe_3); if (GUILayout.Button("Use Logarithmic Rolloff Curve", EditorStyles.miniButton)) { rollOffCurve.animationCurveValue = new AnimationCurve(new Keyframe[] { new Keyframe(0, 0, 0, 0), new Keyframe(0.2f, 0.015f, 0.09f, 0.09f), new Keyframe(0.6f, 0.1f, 0.3916f, 0.3916f), new Keyframe(0.8f, 0.25f, 1.33f, 1.33f), new Keyframe(0.9f, 0.5f, 5f, 5f), new Keyframe(0.95f, 1f, 14.26f, 14.26f) }); } DrawPropertiesExcluding(audioObj, _dontIncludeMe_4); audioObj.ApplyModifiedProperties(); if (target != null) target.name = Path.GetFileName(AssetDatabase.GetAssetPath(target)).Replace(".asset", ""); } float GetMinDistanceValue(SerializedProperty _property) { float minDistance = 0; foreach (var targetObject in audioObj.targetObjects) { SerializedObject iteratedObject = new SerializedObject(targetObject); SerializedProperty iteratedProperty = iteratedObject.FindProperty(_property.propertyPath); if (iteratedProperty.floatValue > minDistance) { minDistance = iteratedProperty.floatValue; } } return minDistance; } void CheckIdentifier() { if (Selection.activeObject != audioObj.targetObject) return; showError = false; if (!string.IsNullOrEmpty(identifier.stringValue)) { foreach (var itemTest in globalAudioObjects) { if (itemTest != (audioObj.targetObject as AudioObject) && itemTest.identifier == (audioObj.targetObject as AudioObject).identifier) { showError = true; } } } } public static void PlayClip(AudioClip clip) { if (Application.isPlaying) return; Assembly assembly = typeof(AudioImporter).Assembly; System.Type audioUtilType = assembly.GetType("UnityEditor.AudioUtil"); System.Type[] typeParams = { typeof(AudioClip), typeof(int), typeof(bool) }; object[] objParams = { clip, 0, false }; MethodInfo method = audioUtilType.GetMethod("PlayClip", typeParams); method.Invoke(null, BindingFlags.Static | BindingFlags.Public, null, objParams, null); } public static void StopClip(AudioClip clip) { Assembly unityEditorAssembly = typeof(AudioImporter).Assembly; System.Type audioUtilClass = unityEditorAssembly.GetType("UnityEditor.AudioUtil"); MethodInfo method = audioUtilClass.GetMethod( "StopClip", BindingFlags.Static | BindingFlags.Public, null, new System.Type[] { typeof(AudioClip) }, null ); method.Invoke( null, new object[] { clip } ); } #if UNITY_2017_2_OR_NEWER void PlayModeChange(PlayModeStateChange state) { if (state == PlayModeStateChange.EnteredPlayMode || state == PlayModeStateChange.ExitingEditMode) { StopAllClips(); } } #endif void PlayModeChangeOlder() { if (EditorApplication.isPlayingOrWillChangePlaymode || EditorApplication.isPlaying) { StopAllClips(); } } public static void StopAllClips() { Assembly unityEditorAssembly = typeof(AudioImporter).Assembly; System.Type audioUtilClass = unityEditorAssembly.GetType("UnityEditor.AudioUtil"); MethodInfo method = audioUtilClass.GetMethod( "StopAllClips", BindingFlags.Static | BindingFlags.Public ); method.Invoke( null, null ); } public static object[] DropZone() { EventType eventType = Event.current.type; bool isAccepted = false; if (eventType == EventType.DragUpdated || eventType == EventType.DragPerform) { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; if (eventType == EventType.DragPerform) { DragAndDrop.AcceptDrag(); isAccepted = true; } Event.current.Use(); } return isAccepted ? DragAndDrop.objectReferences : null; } } #endif } }
namespace SciVacancies.Captcha.CaptchaStores { public interface ICaptchaStore { void DeleteCaptcha(string captchaId); string GetCaptcha(string captchaId); void PutCaptcha(string captchaId, string captchaText); } }
using System; using System.IO; using System.Windows.Media.Imaging; namespace Appnotics.Slideshow { public class Photo : MediaObject { // required for serialization public Photo() { } public Photo(string path) { Path = path; SelectedOpacity = 0; MixmatchUsed = false; ImageName = Path; } public new void Init() { fi = new FileInfo(Path); try { using (var stream = File.OpenRead(Path)) { Image = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); } Metadata = new ExifMetadata(Image); } catch (Exception e) { Error = e.Message; Uri b = new Uri("pack://application:,,/Resources/broken.png"); Image = BitmapFrame.Create(b); IsBroken = true; } if (thumbnailImageLarge == null) InitLargeThumbnail(); if (thumbnailImage == null) InitThumbnail(); IsInitialised = true; HasFull = true; OnPropertyChanged("Image"); OnPropertyChanged("HasFull"); } public bool InitThumbnail() { if (Image != null) thumbnailImage = InitFromBitmap(Image, 200, 200); else if (thumbnailImageLarge != null) thumbnailImage = InitFromBitmap(thumbnailImageLarge, 200, 200); else thumbnailImage = InitFromFile(200, 200); if (thumbnailImage == null) { Uri b = new Uri("pack://application:,,/Resources/broken.png"); thumbnailImageLarge = BitmapFrame.Create(b); } else HasThumb = true; OnPropertyChanged("thumbnailImage"); OnPropertyChanged("HasThumb"); return true; } public bool InitLargeThumbnail() { if (Image != null) thumbnailImageLarge = InitFromBitmap(Image, 600, 600); else thumbnailImageLarge = InitFromFile(600, 600); if (thumbnailImageLarge == null) { Uri b = new Uri("pack://application:,,/Resources/broken.png"); thumbnailImageLarge = BitmapFrame.Create(b); } else HasLargeThumb = true; OnPropertyChanged("thumbnailImageLarge"); OnPropertyChanged("HasLargeThumb"); return true; } private BitmapFrame InitFromFile(int w, int h) { try { using (var stream = File.OpenRead(Path)) { // Create source BitmapImage myBitmapImage = new BitmapImage(); // BitmapImage.UriSource must be in a BeginInit/EndInit block myBitmapImage.BeginInit(); myBitmapImage.StreamSource = stream; // To save significant application memory, set the DecodePixelWidth or // DecodePixelHeight of the BitmapImage value of the image source to the desired // height or width of the rendered image. If you don't do this, the application will // cache the image as though it were rendered as its normal size rather then just // the size that is displayed. // Note: In order to preserve aspect ratio, set DecodePixelWidth // or DecodePixelHeight but not both. myBitmapImage.DecodePixelWidth = 200; myBitmapImage.EndInit(); } } catch (Exception e) { Error = e.Message; } BitmapFrame b = null; fi = new FileInfo(Path); try { using (var stream = File.OpenRead(Path)) { b = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); } Metadata = new ExifMetadata(b); } catch (Exception e) { Error = e.Message; Uri brok = new Uri("pack://application:,,/Resources/broken.png"); b = BitmapFrame.Create(brok); IsBroken = true; } return b; } private BitmapFrame InitFromBitmap(BitmapFrame b, int w, int h) { try { int desiredHeight = h; int desiredWidth = w; int newHeight; int newWidth; if (Metadata != null && (Metadata.ImageOrientation == RotationMode.Left || Metadata.ImageOrientation == RotationMode.Right)) { newHeight = desiredWidth; newWidth = newHeight * (int)b.Width / (int)b.Height; if (newWidth > desiredHeight) { newWidth = desiredHeight; newHeight = newWidth * (int)b.Height / (int)b.Width; } } else { newHeight = desiredHeight; newWidth = desiredHeight * (int)b.Width / (int)b.Height; if (newWidth > desiredWidth) { newWidth = desiredWidth; newHeight = newWidth * (int)b.Height / (int)b.Width; } } BitmapFrame thumb = CreateResizedImage(Image, newWidth, newHeight, 0); return thumb; } catch (Exception e) { Error = e.Message; } return null; } } }
namespace Witsml.Data.Measures { public class WitsmlMeasuredDepthCoord : MeasureWithDatum { } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace WebAppMedOffices.Models { [Table("DuracionTurnoEspecialidades")] public class DuracionTurnoEspecialidad { [Key] public int Id { get; set; } [Index("DuracionTurnoEspecialidad_MedicoId_EspecialidadId_Index", IsUnique = true, Order = 1)] [Display(Name = "Médico")] public int MedicoId { get; set; } [Index("DuracionTurnoEspecialidad_MedicoId_EspecialidadId_Index", IsUnique = true, Order = 2)] [Display(Name = "Especialidad")] public int EspecialidadId { get; set; } [Required(ErrorMessage = "Debes introducir una {0}")] [Display(Name = "Duración")] public int Duracion { get; set; } public virtual Medico Medico { get; set; } public virtual Especialidad Especialidad { get; set; } } }
using AsyncClasses; using Common.Exceptions; using System; using System.IO; using System.ServiceModel; namespace Contracts.Callback { [ServiceKnownType(typeof(TableLoader))] [ServiceKnownType(typeof(MLATableLoader))] [ServiceKnownType(typeof(ContentOpsTableLoader))] [ServiceKnownType(typeof(ScreenerTableLoader))] [ServiceKnownType(typeof(PromotionsTableLoader))] [ServiceKnownType(typeof(AsyncDataLoadException))] public interface IAsyncServiceCallback { [OperationContract(IsOneWay = true)] void Completed(MemoryStream data, int instance, Exception e, bool cancelled, object userState = null); [OperationContract(IsOneWay = true)] void ReportProgress(int total, int current, string notFound, int instance, MemoryStream data, bool cancelled, object userState); } }