text
stringlengths
13
6.01M
using System.Collections.Generic; using System.Threading.Tasks; using Core.Entities; namespace Core.Abstract { public interface ITrainInfoProvider { Task<string> GetRequestIdAsync(TicketRequest ticketRequest); Task<IEnumerable<Train>> GetTrainsAsync(TicketRequest ticketRequest); Task<IEnumerable<Station>> GetStationsAsync(string pattern); Task<IEnumerable<Wagon>> GetTrainInfoAsync(Train train); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AxiDiscountEngine.Model; using AxisPosCore; using AxisPosCore.Common; using KartObjects; using System.Diagnostics; using KartObjects.Entities; using KartObjects.Entities.Documents; namespace AxisPosCore { public class FBConnectionHandler : IConnectionHandler { bool InnerInit; public FBConnectionHandler(bool innerInit) { InnerInit = innerInit; } public void LoadPacket() { List<ReplData> replData = Loader.DbLoad<ReplData>(string.Format("LastLoadTime>'{0:dd.MM.yyyy HH:mm:ss}' ", DataDictionary.SPos.ActualDate)); if (replData != null) if (replData.Exists(q => q.NameEntity.Trim() == "POINTOFSALES")) { //Запоминаем дату актуальности перед импортом LastLoadTime = (DateTime)Loader.DataContext.ExecuteScalar("select * from v_servertime"); Stopwatch sw = new Stopwatch(); sw.Start(); List<PointOfSale> PointOfSales = Loader.DbLoad<PointOfSale>(string.Format("ActualDate>'{0:dd.MM.yyyy HH:mm:ss}' and id={1}", DataDictionary.SActualDate, DataDictionary.SPos.Id)); if (PointOfSales != null) { WriteLog("Новый пакет точка продаж 1 запись"); AxisDataPacket packet = new AxisDataPacket(DataDictionary.SLastPacketNumber + 1, Settings.AppDir); packet.InitPacket(PointOfSales, DataDictionary.SActualDate, false); WriteLog("Создание пакета " + packet.Number + " за " + KartObjects.Helper.formatSwString(sw)); packet.SavePacket(); DataDictionary.MergePacket(packet); sw.Stop(); WriteLog("Пакет " + packet.Number + " принят за " + KartObjects.Helper.formatSwString(sw)); } DataDictionary.SPos.ActualDate = LastLoadTime; } else DataDictionary.SPos.ActualDate = LastLoadTime; //Есть товары, на самом деле репликация реализована //на основании таблицы cardparam_strong, moddate котрой апдейтися каждый раз // при изменении как самой карточки так и штрихкодов, ассортиментных карточек и прочее if (replData != null) { if (replData.Exists(q => q.NameEntity.Trim() == "GOODS")) { //Запоминаем дату актуальности перед импортом LastLoadTime = (DateTime)Loader.DataContext.ExecuteScalar("select * from v_servertime"); Stopwatch sw = new Stopwatch(); sw.Start(); var list = Loader.DbLoad<GoodDepart>(string.Format("ModificationTime>'{0:dd.MM.yyyy HH:mm:ss}' and IdDepartment={1}", DataDictionary.SActualDate, DataDictionary.SPos.IdStore)); if (list != null) { List<Good> goods = list.ConvertAll(new Converter<GoodDepart, Good>(DataDictionary.ConvertGd)); WriteLog("Новый пакет товары " + goods.Count.ToString() + " записей"); AxisDataPacket packet = new AxisDataPacket(DataDictionary.SLastPacketNumber + 1, Settings.AppDir); packet.InitPacket(goods, DataDictionary.SActualDate, InnerInit); WriteLog("Создание пакета " + packet.Number + " за " + KartObjects.Helper.formatSwString(sw)); packet.SavePacket(); DataDictionary.MergePacket(packet); sw.Stop(); WriteLog("Пакет " + packet.Number + " принят за " + KartObjects.Helper.formatSwString(sw)); } if (!InnerInit) { #region Штрихкоды var list1 = Loader.DbLoad<BarcodeDepart>(string.Format("ModificationTime>'{0:dd.MM.yyyy HH:mm:ss} and IdDepartment={1}'", DataDictionary.SActualDate, DataDictionary.SPos.IdStore)); if (list1 != null) { List<Barcode> barcodes = list1.ConvertAll(new Converter<BarcodeDepart, Barcode>(DataDictionary.ConvertBc)); sw.Restart(); WriteLog("Новый пакет штрихкода " + barcodes.Count.ToString() + " записей"); AxisDataPacket packetbc = new AxisDataPacket(DataDictionary.SLastPacketNumber + 1, Settings.AppDir); packetbc.InitPacket(barcodes, DataDictionary.SActualDate, false); WriteLog("Создание пакета " + packetbc.Number + " за " + KartObjects.Helper.formatSwString(sw)); packetbc.SavePacket(); DataDictionary.MergePacket(packetbc); sw.Stop(); WriteLog("Пакет " + packetbc.Number + " принят за " + KartObjects.Helper.formatSwString(sw)); } #endregion #region Ассортимент List<Assortment> assortments = Loader.DbLoad<Assortment>(string.Format("ModificationTime>'{0:dd.MM.yyyy HH:mm:ss}'", DataDictionary.SActualDate)); if (assortments != null) { WriteLog("Новый пакет ассортимент " + assortments.Count.ToString() + " записей"); AxisDataPacket packetass = new AxisDataPacket(DataDictionary.SLastPacketNumber + 1, Settings.AppDir); packetass.InitPacket(assortments, DataDictionary.SActualDate, false); WriteLog("Создание пакета " + packetass.Number + " за " + KartObjects.Helper.formatSwString(sw)); packetass.SavePacket(); DataDictionary.MergePacket(packetass); sw.Stop(); WriteLog("Пакет " + packetass.Number + " принят за " + KartObjects.Helper.formatSwString(sw)); } #endregion } } if (replData.Exists(q => q.NameEntity.Trim() == "POSDEVICES")) { //Запоминаем дату актуальности перед импортом LastLoadTime = (DateTime)Loader.DataContext.ExecuteScalar("select * from v_servertime"); Stopwatch sw = new Stopwatch(); sw.Start(); List<POSDevice> PosDevices = Loader.DbLoad<POSDevice>(string.Format("ModificationTime>'{0:dd.MM.yyyy HH:mm:ss}' and idPointOfSale={1}", DataDictionary.SActualDate, DataDictionary.SPos.Id)); if (PosDevices != null) { WriteLog("Новый пакет устройства" + PosDevices.Count.ToString() + " записей"); AxisDataPacket packet = new AxisDataPacket(DataDictionary.SLastPacketNumber + 1, Settings.AppDir); packet.InitPacket(PosDevices, DataDictionary.SActualDate, false); WriteLog("Создание пакета " + packet.Number + " за " + KartObjects.Helper.formatSwString(sw)); packet.SavePacket(); DataDictionary.MergePacket(packet); sw.Stop(); WriteLog("Пакет " + packet.Number + " принят за " + KartObjects.Helper.formatSwString(sw)); } } if (replData.Exists(q => q.NameEntity.Trim() == "CASHIERS")) { //Запоминаем дату актуальности перед импортом LastLoadTime = (DateTime)Loader.DataContext.ExecuteScalar("select * from v_servertime"); Stopwatch sw = new Stopwatch(); sw.Start(); List<CashierDepart> list = Loader.DbLoad<CashierDepart>(string.Format("ModificationTime>'{0:dd.MM.yyyy HH:mm:ss}' and IdDepartment={1}", DataDictionary.SActualDate, DataDictionary.SPos.IdStore)); if (list != null) { List<Cashier> Cashiers = list.ConvertAll(new Converter<CashierDepart, Cashier>(DataDictionary.ConvertCashier)); WriteLog("Новый пакет кассиры " + Cashiers.Count.ToString() + " записей"); AxisDataPacket packet = new AxisDataPacket(DataDictionary.SLastPacketNumber + 1, Settings.AppDir); packet.InitPacket(Cashiers, DataDictionary.SActualDate, false); WriteLog("Создание пакета " + packet.Number + " за " + KartObjects.Helper.formatSwString(sw)); packet.SavePacket(); DataDictionary.MergePacket(packet); sw.Stop(); WriteLog("Пакет " + packet.Number + " принят за " + KartObjects.Helper.formatSwString(sw)); } } //Права кассиров if (replData.Exists(q => q.NameEntity.Trim() == "CASHIERPOSACTIONS")) { LastLoadTime = (DateTime)Loader.DataContext.ExecuteScalar("select * from v_servertime"); Stopwatch sw = new Stopwatch(); sw.Start(); List<CashierPOSAction> CashierPOSActions = Loader.DbLoad<CashierPOSAction>(string.Format("ModificationTime>'{0:dd.MM.yyyy HH:mm:ss}'", DataDictionary.SActualDate)); if (CashierPOSActions != null) { WriteLog("Новый пакет права кассиров " + CashierPOSActions.Count.ToString() + " записей"); AxisDataPacket packet = new AxisDataPacket(DataDictionary.SLastPacketNumber + 1, Settings.AppDir); packet.InitPacket(CashierPOSActions, DataDictionary.SActualDate, false); WriteLog("Создание пакета " + packet.Number + " за " + KartObjects.Helper.formatSwString(sw)); packet.SavePacket(); DataDictionary.MergePacket(packet); sw.Stop(); WriteLog("Пакет " + packet.Number + " принят за " + KartObjects.Helper.formatSwString(sw)); } } if (replData.Exists(q => q.NameEntity.Trim() == "SELLERS")) { //Запоминаем дату актуальности перед импортом LastLoadTime = (DateTime)Loader.DataContext.ExecuteScalar("select * from v_servertime"); Stopwatch sw = new Stopwatch(); sw.Start(); List<SellerDepart> SellersDepart = Loader.DbLoad<SellerDepart>(string.Format("ModificationTime>'{0:dd.MM.yyyy HH:mm:ss}' and IdDepartment={1}", DataDictionary.SActualDate, DataDictionary.SPos.IdStore)); if (SellersDepart != null) { List<Seller> Sellers = SellersDepart.ConvertAll(new Converter<SellerDepart, Seller>(DataDictionary.ConvertSeller)); WriteLog("Новый пакет продавцы " + Sellers.Count.ToString() + " записей"); AxisDataPacket packet = new AxisDataPacket(DataDictionary.SLastPacketNumber + 1, Settings.AppDir); packet.InitPacket(Sellers, DataDictionary.SActualDate, false); WriteLog("Создание пакета " + packet.Number + " за " + KartObjects.Helper.formatSwString(sw)); packet.SavePacket(); DataDictionary.MergePacket(packet); sw.Stop(); WriteLog("Пакет " + packet.Number + " принят за " + KartObjects.Helper.formatSwString(sw)); } } //Дисконтные карты if (replData.Exists(q => q.NameEntity.Trim() == "DISCOUNTCARDS")) { //Запоминаем дату актуальности перед импортом LastLoadTime = (DateTime)Loader.DataContext.ExecuteScalar("select * from v_servertime"); Stopwatch sw = new Stopwatch(); sw.Start(); List<DiscountCard> DiscountCards = Loader.DbLoad<DiscountCard>(string.Format("ModificationTime>'{0:dd.MM.yyyy HH:mm:ss}'", DataDictionary.SActualDate)); if (DiscountCards != null) { WriteLog("Новый пакет дисконтные карты " + DiscountCards.Count.ToString() + " записей"); AxisDataPacket packet = new AxisDataPacket(DataDictionary.SLastPacketNumber + 1, Settings.AppDir); packet.InitPacket(DiscountCards, DataDictionary.SActualDate, false); WriteLog("Создание пакета " + packet.Number + " за " + KartObjects.Helper.formatSwString(sw)); packet.SavePacket(); DataDictionary.MergePacket(packet); sw.Stop(); WriteLog("Пакет " + packet.Number + " принят за " + KartObjects.Helper.formatSwString(sw)); } } //Типы оплат if (replData.Exists(q => q.NameEntity.Trim() == "PAYTYPES")) { LoadPacket<PayType>(string.Format("ModificationTime>'{0:dd.MM.yyyy HH:mm:ss}' and IdPOSGroup={1}", DataDictionary.SActualDate, DataDictionary.SPos.IdPOSGroup)); } //Кассовые параметры if (replData.Exists(q => q.NameEntity.Trim() == "POSPARAMETERS")) { LoadPacket<POSParameter>(string.Format("ModificationTime>'{0:dd.MM.yyyy HH:mm:ss}' and IdPOSGroup={1}", DataDictionary.SActualDate, DataDictionary.SPos.IdPOSGroup)); } //Раскладки клавиатуры if (replData.Exists(q => q.NameEntity.Trim() == "POSBUTTONACTIONS")) { LoadPacket<POSButtonAction>(string.Format("ModificationTime>'{0:dd.MM.yyyy HH:mm:ss}' and IdPOSGroup={1}", DataDictionary.SActualDate, DataDictionary.SPos.IdPOSGroup)); } //Скидки if (replData.Exists(q => q.NameEntity.Trim() == "POSDISCOUNTS")) { LoadPacket<PosDiscount>(string.Format("ModificationTime>'{0:dd.MM.yyyy HH:mm:ss}' and IdPOSGroup={1}", DataDictionary.SActualDate, DataDictionary.SPos.IdPOSGroup)); } //Заголовок чека if (replData.Exists(q => q.NameEntity.Trim() == "ReceiptHeader")) { LoadPacket<HeaderString>(string.Format("ModificationTime>'{0:dd.MM.yyyy HH:mm:ss}' and IdPOSGroup={1}", DataDictionary.SActualDate, DataDictionary.SPos.IdPOSGroup)); } //Заголовок чека if (replData.Exists(q => q.NameEntity.Trim() == "CUSTOMPROMOACTIONS")) { } DataDictionary.SActualDate = LastLoadTime; } } /// <summary> /// Запрос данных пакета с сервера /// </summary> /// <typeparam name="LoadType">Тип данных</typeparam> /// <param name="query">строка запроса</param> private void LoadPacket<LoadType>(string query) where LoadType : Entity, new() { //Запоминаем дату актуальности перед импортом LastLoadTime = (DateTime)Loader.DataContext.ExecuteScalar("select * from v_servertime"); var sw = new Stopwatch(); sw.Start(); List<LoadType> LoadedData = null; try { LoadedData = Loader.DbLoad<LoadType>(query); } catch (Exception) { WriteLog("Ошибка выполнения запроса " + typeof(LoadType).ToString()); throw; } if (LoadedData != null) { GenPacket(LoadedData, sw); } } private void GenPacket<LoadType>(List<LoadType> LoadedData, Stopwatch sw) where LoadType : Entity, new() { WriteLog("Новый пакет " + LoadedData[0].FriendlyName + " " + LoadedData.Count.ToString() + " записей"); AxisDataPacket packet = new AxisDataPacket(DataDictionary.SLastPacketNumber + 1, Settings.AppDir); packet.InitPacket(LoadedData, DataDictionary.SActualDate, false); WriteLog("Создание пакета " + packet.Number + " за " + KartObjects.Helper.formatSwString(sw)); packet.SavePacket(); DataDictionary.MergePacket(packet); sw.Stop(); WriteLog("Пакет " + packet.Number + " принят за " + KartObjects.Helper.formatSwString(sw)); } public void WriteLog(string text) { POSEnvironment.Log.WriteToLog(text); } public Receipt LoadReceipt(long IdPOSDevice, int NumShift, int NumReceipt) { Receipt receipt = null; var v = Loader.DbLoad<Receipt>("isdeleted=0", 0, IdPOSDevice, NumShift, NumReceipt); if (v != null) { receipt = v[0]; receipt.ReceiptSpecRecords = Loader.DbLoad<ReceiptSpecRecord>("", 0, receipt.Id); ///Загружаем с сервера продавцов foreach (ReceiptSpecRecord r in receipt.ReceiptSpecRecords) { if (r.IdSeller != null) { var sellers = Loader.DbLoad<SellerDepart>("Id=" + r.IdSeller); if (sellers != null) r.Seller = sellers[0]; } } receipt.Payment = Loader.DbLoad<Payment>("", 0, receipt.Id); //Загружаем оплаты с сервера foreach (Payment p in receipt.Payment) { var pts = from pt in DataDictionary.SPayTypes where pt.Id == p.IdPayType select pt; if (pts != null) p.PayType = pts.SingleOrDefault(); } ///Загружаем с сервера кассира var cashiers = Loader.DbLoad<CashierDepart>("Id=" + receipt.IdCashier); if (cashiers != null) receipt.Cashier = cashiers[0]; } return receipt; } public void SaveReceipt(Receipt r) { //Чек Saver.SaveToDb<Receipt>(r as Receipt); //Спецификация if ((r as Receipt).ReceiptSpecRecords != null) foreach (ReceiptSpecRecord rsr in (r as Receipt).ReceiptSpecRecords) { if (rsr.IdGood == 0) rsr.IdGood = DataDictionary.GetIdGoodByBarcode(rsr.Barcode); if (rsr.Barcode != "") rsr.IdAssortment = DataDictionary.GetIdAssortByBarcode(rsr.Barcode); Saver.SaveToDb<ReceiptSpecRecord>(rsr); //Скидки спецификации if (rsr.Discounts.Count > 0) foreach (ReceiptDiscount d in rsr.Discounts) { Saver.SaveToDb<ReceiptDiscount>(d); } } //Оплаты if ((r as Receipt).Payment != null) foreach (Payment p in (r as Receipt).Payment) { Saver.SaveToDb<Payment>(p); //Сохраняем оплаты картами foreach (CardPayment cp in p.CardPayments) { Saver.SaveToDb<CardPayment>(cp); } } (r as Receipt).ReceiptStatus = ReceiptStatus.onServer; Saver.DataContext.ExecuteNonQuery("execute procedure SP_REFRESH_ACTUAL_DATE"); } public DateTime LastLoadTime { get; set; } public void SaveZReport(ZReport z) { Saver.SaveToDb<ZReport>(z); foreach (ZReportPayment zp in z.ZReportPayments) { //Накопительные счетчики Saver.SaveToDb<ZReportPayment>(zp); } } public Receipt LoadSoftReceipt(string SystemCardCode) { Receipt receipt = new Receipt(); var v = Loader.DbLoad<SoftReceiptSpecRecord>(SystemCardCode, 0, receipt.Id); foreach (SoftReceiptSpecRecord item in v) { receipt.ReceiptSpecRecords.Add(item); } return receipt; } public int Balance(string track2, out decimal res) { throw new NotImplementedException(); } public int GiftCardSale(decimal value, string track2, int receiptnum, int shiftnum, ref long IdClmTran, ref long rrn) { throw new NotImplementedException(); } public int AddBonusBySumm(decimal value, string track2, int receiptnum, int shiftnum, ref long IdClmTran, ref long rrn, long IdGood) { throw new NotImplementedException(); } public int ReturnAddedBonuses(decimal value, long rrn, int receiptnum, int shiftnum) { throw new NotImplementedException(); } public int EmgCancel(int p) { throw new NotImplementedException(); } public int Purchase(decimal p1, string p2) { throw new NotImplementedException(); } public int Return(decimal p1, string p2) { throw new NotImplementedException(); } public long? TransactionNumber { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public long? TransactionRRN { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public decimal TransactionSum { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public DiscountCard GetDiscountCardByCode(string code) { throw new NotImplementedException(); } public DiscountCard GenNewCard(string MACAddress) { throw new NotImplementedException(); } public bool SetExtDiscountRelation(DiscountCard ExtDiscountRelation) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; namespace COM_ports { public static class Exstencion { public static string GetPort(this string name) { return new string(name.SkipWhile(t => t != '(').Skip(1).TakeWhile(t => t != ')').ToArray()); } } }
using System; using System.Collections.Generic; using System.Text; namespace _01._Nikulden_s_Charity { class Program { static void Main(string[] args) { var encrypted = new StringBuilder(Console.ReadLine()); var command = Console.ReadLine(); while (command != "Finish") { var tokens = command.Split(); if (tokens[0] == "Replace") { encrypted.Replace(tokens[1], tokens[2]); Console.WriteLine(encrypted); } else if (tokens[0] == "Cut") { var startIndex = int.Parse(tokens[1]); var endIndex = int.Parse(tokens[2]); if (IsIndexValid(startIndex, encrypted) && IsIndexValid(endIndex, encrypted)) { encrypted.Remove(startIndex, endIndex - startIndex + 1); Console.WriteLine(encrypted); } else { Console.WriteLine("Invalid indexes!"); command = Console.ReadLine(); continue; } } else if (tokens[0] == "Make") { if (tokens[1] == "Upper") { encrypted = new StringBuilder(encrypted.ToString().ToUpper()); Console.WriteLine(encrypted); } else { encrypted = new StringBuilder(encrypted.ToString().ToLower()); Console.WriteLine(encrypted); } } else if (tokens[0] == "Check") { var message = tokens[1]; if (encrypted.ToString().Contains(message)) { Console.WriteLine($"Message contains {message}"); } else { Console.WriteLine($"Message doesn't contain {message}"); } } else if (tokens[0] == "Sum") { var startIndex = int.Parse(tokens[1]); var endIndex = int.Parse(tokens[2]); if (IsIndexValid(startIndex, encrypted) && IsIndexValid(endIndex, encrypted)) { int sum = 0; foreach (var symbol in encrypted.ToString().Substring(startIndex, endIndex - startIndex + 1)) { sum += (int)symbol; } Console.WriteLine(sum); } else { Console.WriteLine("Invalid indexes!"); command = Console.ReadLine(); continue; } } command = Console.ReadLine(); } } static bool IsIndexValid(int index, StringBuilder enumbrable) { if (index < 0 || index >= enumbrable.Length) { return false; } return true; } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using System.Threading.Tasks; using WebsiteManagerPanel.Framework.Extensions; using WebsiteManagerPanel.Models; namespace WebsiteManagerPanel.Framework.Middleware { public class LoginMiddleware { private readonly RequestDelegate _next; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IApplicationBuilder _app; public LoginMiddleware(RequestDelegate next, IHttpContextAccessor httpContextAccessor, IOptions<MiddlewareOption> options) { _next = next; _httpContextAccessor = httpContextAccessor; _app = options.Value.App; } public async Task Invoke(HttpContext context) { var user = _httpContextAccessor.HttpContext.Session.GetObjectFromJson<SessionViewModel>("User"); if(user==null) _app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Auth}/{action=Login}"); }); await _next(context); } } }
 using ND.FluentTaskScheduling.AddConfirmEmailTask; using ND.FluentTaskScheduling.TimingSendEmailTask; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static Random random = new Random(); static void Main(string[] args) { //using (FlightOrderDBEntities db = new FlightOrderDBEntities()) //{ // DateTime start = Convert.ToDateTime("2016-01-01"); // DateTime end = Convert.ToDateTime("2017-01-01"); // List<tb_orders> ordList=db.tb_orders.Where(x => x.createTime >= start && x.createTime < end && x.isOnline==4 && !x.remarkTravel.Contains("旅游")).Take(500).ToList(); // List<tb_orders> ordList2 = db.tb_orders.Where(x => x.createTime >= start && x.delDegree==1 && x.createTime < end && x.isOnline == 4 && x.remarkTravel.Contains("旅游")).ToList(); // StringBuilder strSql = new StringBuilder(); // foreach (var tbOrderse in ordList) // { // tb_orders ord= weightRandom(ordList2); // ord.hotelName = tbOrderse.hotelName; // ord.incomeTotal = tbOrderse.incomeTotal; // ord.incomeFirst = tbOrderse.incomeFirst; // ord.expendFirst = tbOrderse.expendFirst; // ord.expendTotal = tbOrderse.expendTotal; // strSql.AppendLine("update dbo.tb_orders set delDegree=0 , hotename='" + tbOrderse.hotelName + "',incomeTotal='" + tbOrderse.incomeTotal + "',incomeFirst='" + tbOrderse.incomeFirst + "',expendFirst='" + tbOrderse.expendFirst + "',expendTotal='" + tbOrderse.expendTotal + "' where ordernum='" + ord.orderNum + "'"); // } // string ss=ordList.Sum(x => x.incomeTotal).ToString(); // File.WriteAllText("e://1.txt",strSql.ToString()); // Console.WriteLine(ss); // Console.ReadKey(); //} //AlarmHelper.Alarm(1, AlarmType.Email, "514935323@qq.com", "你定新账号", "新订单号为123456"); //TimingSendEmailTask task = new TimingSendEmailTask(); //TimingSendEmailTask.OnProcessing += TimingSendEmailTask_OnProcessing; //task.RunTask(); AddConfirmEmailTask tsk = new AddConfirmEmailTask(); AddConfirmEmailTask.OnProcessing += AddConfirmEmailTask_OnProcessing; tsk.RunTask(); Console.ReadKey(); } static void AddConfirmEmailTask_OnProcessing(object sender, string e) { Console.WriteLine(e); } static void TimingSendEmailTask_OnProcessing(object sender, string e) { Console.WriteLine(e); } #region 加权随机算法 public static tb_orders weightRandom(List<tb_orders> list) { //獲取ip列表list int randomPos = random.Next(0,list.Count); return list[randomPos]; } #endregion } }
using System; using System.Collections.Generic; using System.Dynamic; using System.Globalization; using System.Text; using Xunit; namespace TalkExamplesTest.EncondingSamples { public class ASCIISamples { [Fact] public void Sample1() { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); var text = "Aqui tem uma maçã"; //var normalizedString1 = text.Normalize(NormalizationForm.FormC); //var normalizedString2 = text.Normalize(NormalizationForm.FormD); //var normalizedString3 = text.Normalize(NormalizationForm.FormKC); //var normalizedString4 = text.Normalize(NormalizationForm.FormKD); //Console.WriteLine(normalizedString1 +" "+ normalizedString2 + " " + normalizedString3 + " " + normalizedString4); //var stringBuilder = new StringBuilder(); //foreach (var c in normalizedString2) //{ // var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c); // if (unicodeCategory != UnicodeCategory.NonSpacingMark) // { // stringBuilder.Append(c); // } //} byte[] tempBytes; tempBytes = System.Text.Encoding.GetEncoding("ISO-8859-8").GetBytes(text); string result = System.Text.Encoding.UTF8.GetString(tempBytes); //var result = stringBuilder.ToString().Normalize(NormalizationForm.FormC); var expected = "Aqui tem uma maca"; Assert.Equal(expected, result); } } }
using UnityEngine; using SoulHunter.Base; using SoulHunter.Player; public class Loot : MonoBehaviour { [HideInInspector] public int soulPower; bool colliding; [SerializeField] GameObject particle; private void OnCollisionEnter2D(Collision2D collision) { if (colliding) { return; } if (collision.transform.CompareTag("Player")) { colliding = true; DataManager.Instance.soulsCollected += soulPower; Instantiate(particle, new Vector2(transform.position.x, transform.position.y + 1), Quaternion.identity); AudioManager.PlaySound(AudioManager.Sound.CollectSoul, transform.position); collision.transform.GetComponent<PlayerBase>().Heal(); Destroy(gameObject); colliding = false; } } }
namespace ValidUsernames { using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; public class StartUp { public static void Main() { var input = Console.ReadLine() .Split(new char[] { ' ', '\\', '/', '(', ')' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim()) .ToArray(); var pattern = @"\b[a-zA-Z]\w{2,24}\b"; var validUsers = new List<string>(); foreach (var word in input) { var match = Regex.Match(word, pattern); if (match.Success) { validUsers.Add(word); } } var bestIndex = 0; var bestCount = 0; var count = 0; for (int i = 0; i < validUsers.Count - 1; i++) { count = validUsers[i].Length + validUsers[i + 1].Length; if (count > bestCount) { bestCount = count; bestIndex = i; } } Console.WriteLine(validUsers[bestIndex]); Console.WriteLine(validUsers[bestIndex + 1]); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Ecommerce.Models { public class CartIndexViewModel { public CartViewModel Cart { get; set; } public string ReturnUrl { get; set; } } }
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; using System; namespace Hayaa.Security.Client { public class AppInstanceAuthorityFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { AppInstanceAuthority.AppInstanceAuthOnActionExecuting(context); } } }
using Alabo.Cloud.Support.Domain.Entities; using Alabo.Domains.Entities; using Alabo.Domains.Services; using MongoDB.Bson; using System.Collections.Generic; namespace Alabo.Cloud.Support.Domain.Services { public interface IWorkOrderService : IService<WorkOrder, ObjectId> { ServiceResult Delete(ObjectId id); PagedList<WorkOrder> GetPageList(object query); List<WorkOrder> GetWorkOrdersList(); ServiceResult AddWorkOrder(WorkOrder view); ServiceResult UpdateWorkOrder(WorkOrder view); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace eMAM.UI.Areas.SuperAdmin.Models { public interface IUserViewModelMapper<TEntity, TViewModel> { Task<TViewModel> MapFrom(TEntity entity); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Reflection; using System.Threading; using IRAP.Global; using IRAP.Client.Global.GUI.Dialogs; using IRAP.Client.User; using IRAP.Entity.MDM; using IRAP.WCF.Client.Method; namespace IRAP.Client.GUI.CAS { public partial class frmCustomAndonForm : IRAP.Client.Global.GUI.frmCustomFuncBase { private string className = MethodBase.GetCurrentMethod().DeclaringType.FullName; protected static ProductionLineForStationBound currentProductionLine = null; public frmCustomAndonForm() { InitializeComponent(); lblProductionLine.Parent = lblFuncName; } /// <summary> /// 当前站点所绑定的产线 /// </summary> /// <returns></returns> protected ProductionLineForStationBound GetBoundAndonHost() { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; List<ProductionLineForStationBound> lines = new List<ProductionLineForStationBound>(); IRAPMDMClient.Instance.ufn_GetList_StationBoundProductionLines( IRAPUser.Instance.CommunityID, IRAPUser.Instance.SysLogID, ref lines, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode == 0) { foreach (ProductionLineForStationBound line in lines) { if (line.BoundToAndonHost) { WriteLog.Instance.Write( string.Format( "当前站点绑定产线:({0}){1}", line.T134LeafID, line.T134NodeName), strProcedureName); return line; } } WriteLog.Instance.Write("当前站点没有绑定任何产线!", strProcedureName); return null; } else { ShowMessageBox.Show( errText, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); ShowMessageBox.Show(error.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } protected void RefreshCurrentProductionLine() { currentProductionLine = GetBoundAndonHost(); if (currentProductionLine != null) { if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") { lblProductionLine.Text = string.Format( "Current production line: {0}", currentProductionLine.T134NodeName); if (currentProductionLine.IsStoped) { lblProductionLine.ForeColor = Color.Red; lblProductionLine.Text += " (Stopped)"; } else { lblProductionLine.ForeColor = Color.Green; } } else { lblProductionLine.Text = string.Format( "当前产线:{0}", currentProductionLine.T134NodeName); if (currentProductionLine.IsStoped) { lblProductionLine.ForeColor = Color.Red; lblProductionLine.Text += " (已停线)"; } else { lblProductionLine.ForeColor = Color.Green; } } } else { lblProductionLine.ForeColor = Color.Green; if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") lblProductionLine.Text = "Current production line: None"; else lblProductionLine.Text = "当前产线:无"; } } private void frmCustomAndonForm_Activated(object sender, EventArgs e) { RefreshCurrentProductionLine(); } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using FiiiCoin.Wallet.Win.Biz.Services; using FiiiCoin.Wallet.Win.Models; using System.Collections.ObjectModel; namespace FiiiCoin.Wallet.Win.Biz.Monitor { public class TradeRecodesMonitor : ServiceMonitorBase<ObservableCollection<TradeRecordInfo>> { private static TradeRecodesMonitor _default; public static TradeRecodesMonitor Default { get { if (_default == null) _default = new TradeRecodesMonitor(); return _default; } } protected override ObservableCollection<TradeRecordInfo> ExecTaskAndGetResult() { var result = new ObservableCollection<TradeRecordInfo>(); var tradeRecordsResult = FiiiCoinService.Default.GetListTransactions("*", 0, true, 5); if (!tradeRecordsResult.IsFail) { return tradeRecordsResult.Value; } else return null; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace nogometPI { public partial class frmPrijava : Form { public frmPrijava() { InitializeComponent(); txtKorisnickoIme.Focus(); } private void btnOdustani_Click(object sender, EventArgs e) { this.Close(); } private void btnPrijava_Click(object sender, EventArgs e) { try { korisniciTableAdapter.FillByPrijava(sql25907DataSet.korisnici, txtKorisnickoIme.Text, mtxtLozinka.Text); if (sql25907DataSet.korisnici.Count != 1) { MessageBox.Show("Prijava nije uspjela!"); txtKorisnickoIme.Text = ""; mtxtLozinka.Text = ""; txtKorisnickoIme.Focus(); } else { frmMain.prijavljeniKorisnik = txtKorisnickoIme.Text; frmMain.logKorisnik.Text = "Prijavljeni ste kao: " + txtKorisnickoIme.Text; frmMain.staticPrijava.Enabled = false; frmMain.staticOdjava.Enabled = true; if (txtKorisnickoIme.Text == "admin") { frmMain.staticUpravljanjeKorisnicima.Enabled = true; frmMain.staticUpravljanjeKorisnicima.Visible = true; } this.Close(); } } catch (Exception) { MessageBox.Show("Greška sa spajanjem na bazu."); } } private void frmPrijava_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'sql25907DataSet.korisnici' table. You can move, or remove it, as needed. this.korisniciTableAdapter.Fill(this.sql25907DataSet.korisnici); // TODO: This line of code loads data into the 'sql25907DataSet.korisnici' table. You can move, or remove it, as needed. } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; namespace WPFUserInterface { public static class DemoMethods { public static List<string> PrepData() { List<string> output = new List<string>(); output.Add("https://www.yahoo.com"); output.Add("https://www.google.com"); output.Add("https://www.microsoft.com"); output.Add("https://www.cnn.com"); output.Add("https://www.amazon.com"); output.Add("https://www.facebook.com"); output.Add("https://www.twitter.com"); output.Add("https://www.codeproject.com"); output.Add("https://www.stackoverflow.com"); output.Add("https://en.wikipedia.org/wiki/.NET_Framework"); return output; } public static List<WebsiteDataModel> RunDownloadSync(System.Windows.Controls.ProgressBar dashboardProgress) { List<string> websites = PrepData(); List<WebsiteDataModel> output = new List<WebsiteDataModel>(); foreach (string site in websites) { WebsiteDataModel results = DownloadWebsite(site); output.Add(results); dashboardProgress.Dispatcher.Invoke(() => dashboardProgress.Value = output.Count * 100 / websites.Count, DispatcherPriority.Background); } return output; } public static async Task<List<WebsiteDataModel>> RunDownloadAsync(IProgress<ProgressReportModel> progress) { List<string> websites = PrepData(); List<WebsiteDataModel> output = new List<WebsiteDataModel>(); ProgressReportModel report = new ProgressReportModel(); foreach (string site in websites) { WebsiteDataModel results = await DownloadWebsiteAsync(site); output.Add(results); report.PercentageComplete = output.Count * 100 / websites.Count; report.SitesDownloaded = output; progress.Report(report); } return output; } public static async Task<List<WebsiteDataModel>> RunDownloadParallelAsync(IProgress<ProgressReportModel> progress) { List<string> websites = PrepData(); List<WebsiteDataModel> output = new List<WebsiteDataModel>(); ProgressReportModel report = new ProgressReportModel(); ParallelOptions parallelOptions = new ParallelOptions(); parallelOptions.MaxDegreeOfParallelism = 6; await Task.Run(() => { Parallel.ForEach<string>(websites, parallelOptions, (site) => { WebsiteDataModel results = DownloadWebsite(site); output.Add(results); report.PercentageComplete = output.Count * 100 / websites.Count; report.SitesDownloaded = output; progress.Report(report); }); }); return output; } private static async Task <WebsiteDataModel> DownloadWebsiteAsync(string websiteURL) { WebsiteDataModel output = new WebsiteDataModel(); WebClient client = new WebClient(); output.WebsiteUrl = websiteURL; output.WebsiteData = await client.DownloadStringTaskAsync(websiteURL); return output; } private static WebsiteDataModel DownloadWebsite(string websiteURL) { WebsiteDataModel output = new WebsiteDataModel(); WebClient client = new WebClient(); output.WebsiteUrl = websiteURL; output.WebsiteData = client.DownloadString(websiteURL); return output; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HackerFerret.ScormHelper.Extensions { public static class StringExtensions { public static bool IsNumericString(this string val) { var retval = false; if (string.IsNullOrWhiteSpace(val)) { return retval; } var tempNum = 0; retval = int.TryParse(val, out tempNum); return retval; } public static bool IsDateString(this string val) { var retval = false; if (string.IsNullOrWhiteSpace(val)) { return retval; } var tempDate = DateTime.Now; retval = DateTime.TryParse(val, out tempDate); return retval; } public static bool IsValidUrl(string url) { if (String.IsNullOrWhiteSpace(url)) { return false; } Uri uriResult; bool isUrl = Uri.TryCreate(url, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps); return isUrl; } } }
using System; using System.Collections.Generic; namespace EnsureThat { public static class EnsureThatComparableExtensions { public static Param<T> Is<T>(this in Param<T> param, T expected) where T : IComparable<T> { Ensure.Comparable.Is(param.Value, expected, param.Name); return param; } public static Param<T> Is<T>(this in Param<T> param, T expected, IComparer<T> comparer) where T : IComparable<T> { Ensure.Comparable.Is(param.Value, expected, comparer, param.Name); return param; } public static Param<T> IsNot<T>(this in Param<T> param, T expected) where T : IComparable<T> { Ensure.Comparable.IsNot(param.Value, expected, param.Name); return param; } public static Param<T> IsNot<T>(this in Param<T> param, T expected, IComparer<T> comparer) where T : IComparable<T> { Ensure.Comparable.IsNot(param.Value, expected, comparer, param.Name); return param; } public static Param<T> IsLt<T>(this in Param<T> param, T limit) where T : IComparable<T> { Ensure.Comparable.IsLt(param.Value, limit, param.Name); return param; } public static Param<T> IsLt<T>(this in Param<T> param, T limit, IComparer<T> comparer) where T : IComparable<T> { Ensure.Comparable.IsLt(param.Value, limit, comparer, param.Name); return param; } public static Param<T> IsLte<T>(this in Param<T> param, T limit) where T : IComparable<T> { Ensure.Comparable.IsLte(param.Value, limit, param.Name); return param; } public static Param<T> IsLte<T>(this in Param<T> param, T limit, IComparer<T> comparer) where T : IComparable<T> { Ensure.Comparable.IsLte(param.Value, limit, comparer, param.Name); return param; } public static Param<T> IsGt<T>(this in Param<T> param, T limit) where T : IComparable<T> { Ensure.Comparable.IsGt(param.Value, limit, param.Name); return param; } public static Param<T> IsGt<T>(this in Param<T> param, T limit, IComparer<T> comparer) where T : IComparable<T> { Ensure.Comparable.IsGt(param.Value, limit, comparer, param.Name); return param; } public static Param<T> IsGte<T>(this in Param<T> param, T limit) where T : IComparable<T> { Ensure.Comparable.IsGte(param.Value, limit, param.Name); return param; } public static Param<T> IsGte<T>(this in Param<T> param, T limit, IComparer<T> comparer) where T : IComparable<T> { Ensure.Comparable.IsGte(param.Value, limit, comparer, param.Name); return param; } public static Param<T> IsInRange<T>(this in Param<T> param, T min, T max) where T : IComparable<T> { Ensure.Comparable.IsInRange(param.Value, min, max, param.Name); return param; } public static Param<T> IsInRange<T>(this in Param<T> param, T min, T max, IComparer<T> comparer) where T : IComparable<T> { Ensure.Comparable.IsInRange(param.Value, min, max, comparer, param.Name); return param; } } }
using ApartmentApps.Portal.Controllers; namespace ApartmentApps.Api.Modules { public class ComponentViewModel : BaseViewModel { //public string Col { get; set; } public string Stretch { get; set; } public decimal Row { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace CarRental.API.BL.Models.RentalLocations { public class CreateRentalLocationModel { public string Name { get; set; } public string City { get; set; } public string Address { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; //passt die Position der Stage dem Spieler an public class GameAreaScript : MonoBehaviour { bool isStart; void Start () { isStart = true; } void Update () { if(BodySourceView.PlayerMovement.y != 0 && isStart) { //-2 Vector3 temp = new Vector3(3.5f, BodySourceView.PlayerMovementHead.y, -65.7f); this.gameObject.transform.position = temp; isStart = false; } } }
using UnityEngine; using System.Collections; public class LoadingLevelCave : MonoBehaviour { public GUIText loadingText; private float timer = 0.0f; // Use this for initialization void Start() { } // Update is called once per frame void Update() { } void OnTriggerEnter(Collider col) { if (col.gameObject.tag == "Player") { loadingText.SendMessage("showMessage", "loading next level"); Application.LoadLevel("Level 2 Cave"); Debug.Log("level 2 loaded"); } } }
using UnityEngine; using System.Collections; public class Poop : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void Kill(){ transform.parent.gameObject.GetComponent<PooManager>().GeneratePoo(); Destroy(gameObject); } }
using System; using System.Collections.Generic; using System.Text; namespace ResidentAppCross.iOS.Views.TableSources { public class TestDataItem { public virtual string Icon => "OfficerIcon"; public virtual string Title { get; set; } public bool Moveable { get; set; } public bool Editable { get; set; } public bool Focusable { get; set; } = true; } }
using Microsoft.AspNet.Identity; using myFinPort.Extensions; using myFinPort.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace myFinPort.Helpers { public class TransactionsHelper { private ApplicationDbContext db = new ApplicationDbContext(); public int GetTransactionsCount() { return db.Transactions.ToList().Count; } public List<Transaction> GetUserTransactions() { var userId = HttpContext.Current.User.Identity.GetUserId(); return db.Transactions.Where(t => t.OwnerId == userId).ToList(); } public List<Transaction> GetHHTransactions() { var hhId = HttpContext.Current.User.Identity.GetHouseholdId(); var userId = HttpContext.Current.User.Identity.GetUserId(); var transactions = db.BankAccounts.Where ( b => b.HouseholdId == hhId && b.OwnerId == userId ).SelectMany(b => b.Transactions).ToList(); return transactions; } public int GetHHTransactionsCount() { return GetHHTransactions().Count; } } }
using UnityEngine; public class SamplePrefab : MonoBehaviour { public int IntValue; public float FloatValue; public Vector3 Vector3Value; }
namespace SafeManipulation { using System; using System.Linq; public class StartUp { public static void Main() { var array = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .ToArray(); while (true) { var command = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .ToArray(); try { if (command[0] == "END") { break; } if (command[0] == "Reverse") { Array.Reverse(array); continue; } if (command[0] == "Distinct") { array = array.Distinct().ToArray(); continue; } var index = int.Parse(command[1]); var word = command[2]; array[index] = word; } catch (Exception) { Console.WriteLine("Invalid input!"); continue; } } Console.WriteLine(String.Join(", ", array)); } } }
using System; using System.Linq; using System.Collections.Generic; namespace Append_lists { class Program { static void Main(string[] args) { var textList = Console.ReadLine().Split('|').ToList(); textList.Reverse(); foreach (var text in textList) { var textArr = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); var joined = string.Join(" ", textArr); Console.Write(joined + " "); } } } }
using System; namespace gView.Core.Framework.Exceptions { public class TokenRequiredException : Exception { public TokenRequiredException() : base("Token required (499)") { } public TokenRequiredException(string message) : base("Token required (499): " + message) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Serialization.Configuration; using Serialization.Providers; using Serialization.Mappers; using System.Xml.Serialization; using System.Text.RegularExpressions; using CasePlasa.Entities; using TopDown.TopFramework.Common.Extensions; namespace Serialization { class Program { static void Main(string[] args) { TextMappingConfiguration config = new TextMappingConfiguration("textmapping.cfg.xml"); var serializerFactory = config.BuildSerializerFactory(); var serializer = serializerFactory.CreateSerializer(); var list = serializer.Deserialize<ClienteEntity>(@"C:\Documents and Settings\jonathas\My Documents\Downloads\CLIENTES.TXT", new SeparatedValuesProvider('#'), true); foreach (var item in list) { item.CodTitular = int.Parse(item.CodTitular).ToString(); item.Opcionais.ForEach(o => o.Cliente = item); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using System; using System.IO; using System.Text; using UnityEngine.UI; public class StageOption : MonoBehaviour { public static string level = "Easy"; public static string num = "Puzzle:3X3"; //public static int val; // Start is called before the first frame update void Start() { GameObject.Find("Canvas/Stage Level").GetComponent<Text>().text = level; GameObject.Find("Canvas/PuzzleSize").GetComponent<Text>().text = num; } // Update is called once per frame void Update() { //Stagetype追本溯源 } public void Stageoption(int val) { if (val == 0) { StageLoad.Stagetype = 1; GameObject.Find("Canvas/Stage Level").GetComponent<Text>().text = "Easy"; level = GameObject.Find("Canvas/Stage Level").GetComponent<Text>().text; puzzlesetting.puzzletype = 3; GameObject.Find("Canvas/PuzzleSize").GetComponent<Text>().text = "Puzzle:3X3"; num = GameObject.Find("Canvas/PuzzleSize").GetComponent<Text>().text; } if (val == 1) { StageLoad.Stagetype = 1; GameObject.Find("Canvas/Stage Level").GetComponent<Text>().text = "Easy"; level = GameObject.Find("Canvas/Stage Level").GetComponent<Text>().text; puzzlesetting.puzzletype = 4; GameObject.Find("Canvas/PuzzleSize").GetComponent<Text>().text = "Puzzle:4X4"; num = GameObject.Find("Canvas/PuzzleSize").GetComponent<Text>().text; } if (val == 2) { StageLoad.Stagetype = 1; GameObject.Find("Canvas/Stage Level").GetComponent<Text>().text = "Easy"; level = GameObject.Find("Canvas/Stage Level").GetComponent<Text>().text; puzzlesetting.puzzletype = 5; GameObject.Find("Canvas/PuzzleSize").GetComponent<Text>().text = "Puzzle:5X5"; num = GameObject.Find("Canvas/PuzzleSize").GetComponent<Text>().text; } if (val == 3) { StageLoad.Stagetype = 2; GameObject.Find("Canvas/Stage Level").GetComponent<Text>().text = "Hard"; level = GameObject.Find("Canvas/Stage Level").GetComponent<Text>().text; puzzlesetting.puzzletype = 3; GameObject.Find("Canvas/PuzzleSize").GetComponent<Text>().text = "Puzzle:3X3"; num = GameObject.Find("Canvas/PuzzleSize").GetComponent<Text>().text; } if (val == 4) { StageLoad.Stagetype = 2; GameObject.Find("Canvas/Stage Level").GetComponent<Text>().text = "Hard"; level = GameObject.Find("Canvas/Stage Level").GetComponent<Text>().text; puzzlesetting.puzzletype = 4; GameObject.Find("Canvas/PuzzleSize").GetComponent<Text>().text = "Puzzle:4X4"; num = GameObject.Find("Canvas/PuzzleSize").GetComponent<Text>().text; } if (val == 5) { StageLoad.Stagetype = 2; GameObject.Find("Canvas/Stage Level").GetComponent<Text>().text = "Hard"; level = GameObject.Find("Canvas/Stage Level").GetComponent<Text>().text; puzzlesetting.puzzletype = 5; GameObject.Find("Canvas/PuzzleSize").GetComponent<Text>().text = "Puzzle:5X5"; num = GameObject.Find("Canvas/PuzzleSize").GetComponent<Text>().text; } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using EdjCase.JsonRpc.Client; using EdjCase.JsonRpc.Core; using FiiiCoin.DTO; using FiiiCoin.Utility; using FiiiCoin.Utility.Api; using System; using System.Collections.Generic; using System.Net.Http.Headers; using System.Threading.Tasks; namespace FiiiCoin.ServiceAgent { public class Accounts { public async Task<AccountInfoOM[]> GetAddressesByTag(string tag = "") { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("GetAddressesByTag", new[] { tag }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } AccountInfoOM[] responseValue = response.GetResult<AccountInfoOM[]>(); return responseValue; } public async Task<AccountInfoOM> GetAccountByAddress(string address) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("GetAccountByAddress", new[] { address }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } AccountInfoOM responseValue = response.GetResult<AccountInfoOM>(); return responseValue; } public async Task<AccountInfoOM> GetNewAddress(string tag) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("GetNewAddress", new[] { tag }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } AccountInfoOM responseValue = response.GetResult<AccountInfoOM>(); return responseValue; } public async Task<AccountInfoOM> GetDefaultAccount() { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithNoParameters("GetDefaultAccount", 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } AccountInfoOM responseValue = response.GetResult<AccountInfoOM>(); return responseValue; } public async Task SetDefaultAccount(string address) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("SetDefaultAccount", new[] { address }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } } public async Task<AddressInfoOM> ValidateAddress(string address) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("ValidateAddress", new[] { address }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } AddressInfoOM responseValue = response.GetResult<AddressInfoOM>(); return responseValue; } public async Task SetAccountTag(string address, string tag) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("SetAccountTag", new List<object> { address, tag }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } } /// <summary> /// 分类获取账号,1:所有找零账户,2:所有创建账户,3:所有观察者账户,0或者其他:所有账户信息 /// </summary> /// <param name="category"></param> /// <returns></returns> public async Task<OMBase> GetPageAccountCategory(int category, int pageSize = 0, int pageCount = int.MaxValue, bool isSimple = true) { AuthenticationHeaderValue authHeaderValue = null; RpcClient client = new RpcClient(new Uri(WalletNetwork.NetWork), authHeaderValue, null, null, "application/json"); RpcRequest request = RpcRequest.WithParameterList("GetPageAccountCategory", new List<object> { category }, 1); RpcResponse response = await client.SendRequestAsync(request); if (response.HasError) { throw new ApiCustomException(response.Error.Code, response.Error.Message); } if (isSimple) return response.GetResult<PageAccountSimpleOM>(); else return response.GetResult<PageAccountDetailOM>(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Mvc; namespace API.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } [Authorize] // GET api/values/5 [HttpGet("{id}")] public ActionResult<string> Get(int id) { var currentUser = HttpContext.User; var cluster = currentUser.Claims.FirstOrDefault(claim => claim.Type == "cluster")?.Value; var app = currentUser.Claims.FirstOrDefault(claim => claim.Type == "app")?.Value; return $"Cluster: {cluster} \nApp: {app}"; } // POST api/values [HttpPost] public void Post([FromBody] string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody] string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
using System; using System.Collections.Generic; using System.Linq; 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.Shapes; namespace seconddeel { /// <summary> /// Interaction logic for Oefening1.xaml /// </summary> public partial class Oefening1 : Window { public List<Persoon> personLijst = new List<Persoon>(); public class Persoon { public string Voornaam { get; set; } public string Achternaam { get; set; } public string Afbeelding { get; set; } //public Persoon(string voornaam, string achternaam) //{ // Voornaam = voornaam; // Achternaam = achternaam; //} //public string FullName //{ // get // { // return $"{ Voornaam} {Achternaam}"; // } //} } public Oefening1() { InitializeComponent(); cbPersonen.ItemsSource = personLijst; personLijst.Add(new Persoon() { Voornaam = "Bhavana", Achternaam = "Saravanakumar", Afbeelding = @"C:\Users\Latha\source\repos\WPF\WpfApp2\Bhavana.jpg" }); personLijst.Add(new Persoon() { Voornaam = "Atchaya", Achternaam = "Saravanakumar",Afbeelding = @"C:\Users\Latha\source\repos\WPF\WpfApp2\Atchaya.jpg" }); personLijst.Add(new Persoon() { Voornaam = "Latha", Achternaam = "Sowdi", Afbeelding = @"C:\Users\Latha\source\repos\WPF\WpfApp2\Latha.jpg" }); personLijst.Add(new Persoon() { Voornaam = "Saravanakumar", Achternaam = "Bala", Afbeelding = @"C:\Users\Latha\source\repos\WPF\WpfApp2\Saravana.jpg" }); } private void btnSubmit1_Click(object sender, RoutedEventArgs e) { } private void cbPersonen_SelectionChanged(object sender, SelectionChangedEventArgs e) { Persoon selected = (Persoon)cbPersonen.SelectedItem; imgCombobox.DataContext = selected; } } }
using UnityEngine; using System.Collections; public interface HasRect { Rect rectangle { get; } }
using Microsoft.SharePoint; using Microsoft.SharePoint.Administration; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace BELCORP.GestorDocumental.CON_CorregirCaducados { class Program { static string urlSitioPrincipal = ConfigurationManager.AppSettings["URL_Sitio_Principal"]; static string urlSitioPublicados = urlSitioPrincipal + "/publicados"; static string cadena_conexion = ConfigurationManager.AppSettings["BELCORP_GD_SQL"]; static string proceso = "BELCORP.GestorDocumental.CON_CorregirCaducados"; static void Main(string[] args) { grabarLog("============================================="); grabarLog("Se inicia proceso"); grabarLog("============================================="); iniciarProceso(); grabarLog("============================================="); grabarLog("Se termina proceso"); grabarLog("============================================="); } private static void iniciarProceso() { SPSecurity.RunWithElevatedPrivileges(delegate () { SPListItemCollection splic = ObtenerInformacionLista(urlSitioPrincipal, "Tipos Documentales"); if (splic != null) { int cantidadListas = splic.Count; int contador = 0; foreach (SPListItem splitem in splic) { contador++; string nombreBiblioteca = splitem["Biblioteca"].ToString(); drawTextProgressBar(contador, cantidadListas); try { SPListItemCollection documentos = ObtenerInformacionLista(urlSitioPublicados, nombreBiblioteca); if (documentos != null) { if (documentos.Count > 0) { List<VersionBE> listVersionBE = new List<VersionBE>(); foreach (SPListItem documento in documentos) { VersionBE objVersionBE = new VersionBE() { Biblioteca = nombreBiblioteca, Codigo = SharePointUtil.ObtenerValorStringSPField(documento, "CodigoDocumento"), Version = SharePointUtil.ObtenerValorIntSPField(documento, "Version"), Estado = SharePointUtil.ObtenerValorStringSPField(documento, "EstadoPasoFlujo"), FechaCaducidad = SharePointUtil.ObtenerValorDateTimeSPField(documento, "FechaCaducidad"), FechaPublicacion = SharePointUtil.ObtenerValorDateTimeSPField(documento, "FechaPublicacion") }; listVersionBE.Add(objVersionBE); } List<DocumentoBE> listDocumentoBE = listVersionBE.GroupBy(x => new { Codigo = x.Codigo }) .Select(group => new DocumentoBE { Biblioteca = nombreBiblioteca, Codigo = group.Key.Codigo, Versiones = listVersionBE.Where(item => item.Codigo.Equals(group.Key.Codigo)).ToList(), UltimaVersion = listVersionBE.Where(item => item.Codigo.Equals(group.Key.Codigo)).OrderByDescending(x => x.Version).FirstOrDefault() }).ToList(); if (listDocumentoBE != null) { if (listDocumentoBE.Count > 0) { List<DocumentoBE> listDocumentoBECaducados = listDocumentoBE.Where(item => item.UltimaVersion.Estado.Equals("Caducado")).ToList(); if (listDocumentoBECaducados != null) { if (listDocumentoBECaducados.Count > 0) { foreach (DocumentoBE documentoBECaducado in listDocumentoBECaducados) { try { if (documentoBECaducado.UltimaVersion.FechaCaducidad.Year == 1) { asignarEstadoPublicado3(documentoBECaducado); } else { if (documentoBECaducado.UltimaVersion.FechaCaducidad > DateTime.Now) { asignarEstadoPublicado2(documentoBECaducado); } else { if (!(documentoBECaducado.UltimaVersion.FechaCaducidad > documentoBECaducado.UltimaVersion.FechaPublicacion)) { asignarEstadoPublicado4(documentoBECaducado); } else { bool tieneTareaElDocumentoHaCaducadoComoAccionMasReciente = verificarTieneTareaElDocumentoHaCaducadoComoAccionMasReciente(documentoBECaducado.Codigo, documentoBECaducado.UltimaVersion.Version, cadena_conexion); if (!tieneTareaElDocumentoHaCaducadoComoAccionMasReciente) { asignarEstadoCaducado1(documentoBECaducado); } else { bool tieneTareaSeActualizoFechaCaducidad = verificarTieneTareaSeActualizoFechaCaducidad(documentoBECaducado.Codigo, documentoBECaducado.UltimaVersion.Version, cadena_conexion); if (!tieneTareaSeActualizoFechaCaducidad) { asignarEstadoPublicado2(documentoBECaducado); } else { bool tieneComentarioEnTareaSeActualizoFechaCaducidad = verificarTieneComentarioEnTareaSeActualizoFechaCaducidad(documentoBECaducado.Codigo, documentoBECaducado.UltimaVersion.Version, cadena_conexion); if (!tieneComentarioEnTareaSeActualizoFechaCaducidad) { asignarEstadoPublicado2(documentoBECaducado); } else { asignarEstadoCaducado1(documentoBECaducado); } } } } } } } catch (Exception ex) { string parametros = string.Format("Error en Biblioteca publicados={0}, CodigoDocumento={1}, Version={2}, Error={3}, StackTrace={4}", nombreBiblioteca, documentoBECaducado.Codigo, documentoBECaducado.UltimaVersion.Version, ex.Message, ex.StackTrace); grabarLog(parametros); } Thread.Sleep(1500); } } } } } } } } catch (Exception ex) { string parametros = string.Format("Error en Biblioteca publicados={0}, Error={1}, StackTrace={2}", nombreBiblioteca, ex.Message, ex.StackTrace); grabarLog(parametros); } Console.WriteLine(nombreBiblioteca); } } }); Console.WriteLine("Se terminó el proceso. Presione cualquier tecla para salir"); Console.Read(); } #region funciones public static SPListItemCollection ObtenerInformacionLista( string pe_strUrlSitio, string pe_strNombreLista, string pe_strQuery = null, string pe_strViewFields = null, string pe_strProjectedFields = null, string pe_strJoinFields = null, uint pe_uintRowLimit = 0, bool? pe_boolViewFieldsOnly = null, string pe_strViewAttributes = null, string pe_strListItemPosition = null) { SPListItemCollection vr_objSPListItemCollection = null; try { SPSecurity.RunWithElevatedPrivileges(delegate () { using (SPSite objSPSite = new SPSite(pe_strUrlSitio)) { using (SPWeb objSPWeb = objSPSite.OpenWeb()) { SPList objSPList = objSPWeb.Lists[pe_strNombreLista]; SPQuery objQuery = new SPQuery(); if (!string.IsNullOrEmpty(pe_strQuery)) objQuery.Query = pe_strQuery; if (pe_uintRowLimit > 0) objQuery.RowLimit = pe_uintRowLimit; if (!string.IsNullOrEmpty(pe_strProjectedFields)) objQuery.ProjectedFields = pe_strProjectedFields; if (!string.IsNullOrEmpty(pe_strJoinFields)) objQuery.Joins = pe_strJoinFields; if (!string.IsNullOrEmpty(pe_strViewFields)) objQuery.ViewFields = pe_strViewFields; if (pe_boolViewFieldsOnly.HasValue) objQuery.ViewFieldsOnly = pe_boolViewFieldsOnly.Value; if (!string.IsNullOrEmpty(pe_strViewAttributes)) objQuery.ViewAttributes = pe_strViewAttributes; if (!string.IsNullOrEmpty(pe_strListItemPosition)) { SPListItemCollectionPosition objSPListItemCollectionPosition = new SPListItemCollectionPosition(pe_strListItemPosition); objQuery.ListItemCollectionPosition = objSPListItemCollectionPosition; } vr_objSPListItemCollection = objSPList.GetItems(objQuery); } } }); return vr_objSPListItemCollection; } catch (Exception ex) { throw ex; } } public static bool verificarTieneTareaElDocumentoHaCaducadoComoAccionMasReciente(string codigo, int version, string pe_CadenaConexion = null) { bool resultado = false; //Se declara la variable que almacenará la cadena de conexion a usar string strCadenaConexion = pe_CadenaConexion; //Se ejecuta con privilegios elevados para que no se genere error de autenticacion de usuario SPSecurity.RunWithElevatedPrivileges(delegate () { using (SqlConnection objSqlConnection = new SqlConnection(strCadenaConexion)) { try { //Se establecen el commando a ejecutar y sus parametros SqlCommand objSqlCommand = new SqlCommand("dbo.USP_VerificarTieneTareaElDocumentoHaCaducadoComoAccionMasReciente", objSqlConnection); objSqlCommand.CommandType = CommandType.StoredProcedure; if (version != 0) objSqlCommand.Parameters.AddWithValue("@Version", version); else objSqlCommand.Parameters.AddWithValue("@Version", DBNull.Value); if (!string.IsNullOrEmpty(codigo)) objSqlCommand.Parameters.AddWithValue("@CodigoDocumento", codigo); else objSqlCommand.Parameters.AddWithValue("@CodigoDocumento", DBNull.Value); objSqlConnection.Open(); //Se ejecuta el commando using (SqlDataReader oSqlDataReader = objSqlCommand.ExecuteReader()) { while (oSqlDataReader.Read()) { string nombreColumna = string.Empty; int indiceColumna = 0; nombreColumna = "Resultado"; if (DataRecord.HasColumn(oSqlDataReader, nombreColumna)) { indiceColumna = oSqlDataReader.GetOrdinal(nombreColumna); resultado = oSqlDataReader.IsDBNull(indiceColumna) ? false : oSqlDataReader.GetBoolean(indiceColumna); } } } } catch (Exception) { //Se arroja la excepcion a la capa superior throw; } finally { //Se cierra la conexion objSqlConnection.Close(); } } }); return resultado; } public static bool verificarTieneTareaSeActualizoFechaCaducidad(string codigo, int version, string pe_CadenaConexion = null) { bool resultado = false; //Se declara la variable que almacenará la cadena de conexion a usar string strCadenaConexion = pe_CadenaConexion; //Se ejecuta con privilegios elevados para que no se genere error de autenticacion de usuario SPSecurity.RunWithElevatedPrivileges(delegate () { using (SqlConnection objSqlConnection = new SqlConnection(strCadenaConexion)) { try { //Se establecen el commando a ejecutar y sus parametros SqlCommand objSqlCommand = new SqlCommand("dbo.USP_VerificarTieneTareaSeActualizoFechaCaducidad", objSqlConnection); objSqlCommand.CommandType = CommandType.StoredProcedure; if (version != 0) objSqlCommand.Parameters.AddWithValue("@Version", version); else objSqlCommand.Parameters.AddWithValue("@Version", DBNull.Value); if (!string.IsNullOrEmpty(codigo)) objSqlCommand.Parameters.AddWithValue("@CodigoDocumento", codigo); else objSqlCommand.Parameters.AddWithValue("@CodigoDocumento", DBNull.Value); objSqlConnection.Open(); //Se ejecuta el commando using (SqlDataReader oSqlDataReader = objSqlCommand.ExecuteReader()) { while (oSqlDataReader.Read()) { string nombreColumna = string.Empty; int indiceColumna = 0; nombreColumna = "Resultado"; if (DataRecord.HasColumn(oSqlDataReader, nombreColumna)) { indiceColumna = oSqlDataReader.GetOrdinal(nombreColumna); resultado = oSqlDataReader.IsDBNull(indiceColumna) ? false : oSqlDataReader.GetBoolean(indiceColumna); } } } } catch (Exception) { //Se arroja la excepcion a la capa superior throw; } finally { //Se cierra la conexion objSqlConnection.Close(); } } }); return resultado; } public static bool verificarTieneComentarioEnTareaSeActualizoFechaCaducidad(string codigo, int version, string pe_CadenaConexion = null) { bool resultado = false; //Se declara la variable que almacenará la cadena de conexion a usar string strCadenaConexion = pe_CadenaConexion; //Se ejecuta con privilegios elevados para que no se genere error de autenticacion de usuario SPSecurity.RunWithElevatedPrivileges(delegate () { using (SqlConnection objSqlConnection = new SqlConnection(strCadenaConexion)) { try { //Se establecen el commando a ejecutar y sus parametros SqlCommand objSqlCommand = new SqlCommand("dbo.USP_VerificarTieneComentarioEnTareaSeActualizoFechaCaducidad", objSqlConnection); objSqlCommand.CommandType = CommandType.StoredProcedure; if (version != 0) objSqlCommand.Parameters.AddWithValue("@Version", version); else objSqlCommand.Parameters.AddWithValue("@Version", DBNull.Value); if (!string.IsNullOrEmpty(codigo)) objSqlCommand.Parameters.AddWithValue("@CodigoDocumento", codigo); else objSqlCommand.Parameters.AddWithValue("@CodigoDocumento", DBNull.Value); objSqlConnection.Open(); //Se ejecuta el commando using (SqlDataReader oSqlDataReader = objSqlCommand.ExecuteReader()) { while (oSqlDataReader.Read()) { string nombreColumna = string.Empty; int indiceColumna = 0; nombreColumna = "Resultado"; if (DataRecord.HasColumn(oSqlDataReader, nombreColumna)) { indiceColumna = oSqlDataReader.GetOrdinal(nombreColumna); resultado = oSqlDataReader.IsDBNull(indiceColumna) ? false : oSqlDataReader.GetBoolean(indiceColumna); } } } } catch (Exception) { //Se arroja la excepcion a la capa superior throw; } finally { //Se cierra la conexion objSqlConnection.Close(); } } }); return resultado; } public static void eliminarTareaSeActualizoFechaCaducidad(string codigo, int version, string pe_CadenaConexion = null) { //Se declara la variable que almacenará la cadena de conexion a usar string strCadenaConexion = pe_CadenaConexion; //Se ejecuta con privilegios elevados para que no se genere error de autenticacion de usuario SPSecurity.RunWithElevatedPrivileges(delegate () { using (SqlConnection objSqlConnection = new SqlConnection(strCadenaConexion)) { try { //Se establecen el commando a ejecutar y sus parametros SqlCommand objSqlCommand = new SqlCommand("dbo.USP_EliminarTareaSeActualizoFechaCaducidad", objSqlConnection); objSqlCommand.CommandType = CommandType.StoredProcedure; if (version != 0) objSqlCommand.Parameters.AddWithValue("@Version", version); else objSqlCommand.Parameters.AddWithValue("@Version", DBNull.Value); if (!string.IsNullOrEmpty(codigo)) objSqlCommand.Parameters.AddWithValue("@CodigoDocumento", codigo); else objSqlCommand.Parameters.AddWithValue("@CodigoDocumento", DBNull.Value); objSqlConnection.Open(); //Se ejecuta el commando objSqlCommand.ExecuteNonQuery(); } catch (Exception) { //Se arroja la excepcion a la capa superior throw; } finally { //Se cierra la conexion objSqlConnection.Close(); } } }); } public static void asignarEstadoCaducado1(DocumentoBE objDocumentoBE) { string metodo = "asignarEstadoCaducado1"; string parametros = string.Format("Biblioteca en publicados={0}, CodigoDocumento={1}, Version={2}", objDocumentoBE.Biblioteca, objDocumentoBE.Codigo, objDocumentoBE.UltimaVersion.Version); grabarLog(string.Concat("Proceso: " + proceso, " Metodo: " + metodo, " Parametros: " + parametros)); cambiarEstadoACaducado(objDocumentoBE.UltimaVersion); grabarLog(string.Concat("Proceso: " + proceso, " Metodo: " + metodo + ".cambiarEstadoACaducado", " Parametros: " + parametros)); cambiarEstadoObsoletoOtrasVersiones(objDocumentoBE); grabarLog(string.Concat("Proceso: " + proceso, " Metodo: " + metodo + ".cambiarEstadoObsoletoOtrasVersiones", " Parametros: " + parametros)); } public static void asignarEstadoPublicado2(DocumentoBE objDocumentoBE) { string metodo = "asignarEstadoPublicado2"; string parametros = string.Format("Biblioteca en publicados={0}, CodigoDocumento={1}, Version={2}", objDocumentoBE.Biblioteca, objDocumentoBE.Codigo, objDocumentoBE.UltimaVersion.Version); grabarLog(string.Concat("Proceso: " + proceso, " Metodo: " + metodo, " Parametros: " + parametros)); cambiarEstadoAPublicado(objDocumentoBE.UltimaVersion, true); grabarLog(string.Concat("Proceso: " + proceso, " Metodo: " + metodo + ".cambiarEstadoAPublicado", " Parametros: " + parametros)); cambiarEstadoObsoletoOtrasVersiones(objDocumentoBE); grabarLog(string.Concat("Proceso: " + proceso, " Metodo: " + metodo + ".cambiarEstadoObsoletoOtrasVersiones", " Parametros: " + parametros)); eliminarTareaSeActualizoFechaCaducidad(objDocumentoBE.Codigo, objDocumentoBE.UltimaVersion.Version, cadena_conexion); grabarLog(string.Concat("Proceso: " + proceso, " Metodo: " + metodo + ".eliminarTareaSeActualizoFechaCaducidad", " Parametros: " + parametros)); } public static void asignarEstadoPublicado3(DocumentoBE objDocumentoBE) { string metodo = "asignarEstadoPublicado3"; string parametros = string.Format("Biblioteca en publicados={0}, CodigoDocumento={1}, Version={2}", objDocumentoBE.Biblioteca, objDocumentoBE.Codigo, objDocumentoBE.UltimaVersion.Version); grabarLog(string.Concat("Proceso: " + proceso, " Metodo: " + metodo, " Parametros: " + parametros)); cambiarEstadoAPublicado(objDocumentoBE.UltimaVersion, false); grabarLog(string.Concat("Proceso: " + proceso, " Metodo: " + metodo + ".cambiarEstadoAPublicado", " Parametros: " + parametros)); cambiarEstadoObsoletoOtrasVersiones(objDocumentoBE); grabarLog(string.Concat("Proceso: " + proceso, " Metodo: " + metodo + ".cambiarEstadoObsoletoOtrasVersiones", " Parametros: " + parametros)); } public static void asignarEstadoPublicado4(DocumentoBE objDocumentoBE) { string metodo = "asignarEstadoPublicado4"; string parametros = string.Format("Biblioteca en publicados={0}, CodigoDocumento={1}, Version={2}", objDocumentoBE.Biblioteca, objDocumentoBE.Codigo, objDocumentoBE.UltimaVersion.Version); grabarLog(string.Concat("Proceso: " + proceso, " Metodo: " + metodo, " Parametros: " + parametros)); cambiarEstadoAPublicado(objDocumentoBE.UltimaVersion, true); grabarLog(string.Concat("Proceso: " + proceso, " Metodo: " + metodo + ".cambiarEstadoAPublicado", " Parametros: " + parametros)); cambiarEstadoObsoletoOtrasVersiones(objDocumentoBE); grabarLog(string.Concat("Proceso: " + proceso, " Metodo: " + metodo + ".cambiarEstadoObsoletoOtrasVersiones", " Parametros: " + parametros)); } public static void cambiarEstadoAPublicado(VersionBE objVersionBE, bool borrarFechaCaducidad) { SPSecurity.RunWithElevatedPrivileges(() => { using (SPSite objSPSite = new SPSite(urlSitioPublicados)) { using (SPWeb objSPWeb = objSPSite.OpenWeb()) { objSPWeb.AllowUnsafeUpdates = true; if (objSPWeb.ParserEnabled) { objSPWeb.ParserEnabled = false; objSPWeb.Update(); } SPList oList = objSPWeb.Lists[objVersionBE.Biblioteca]; SPQuery oSPQuery = new SPQuery(); oSPQuery.Query = "<Where><And><Eq><FieldRef Name='CodigoDocumento' /><Value Type='Text'>"+ objVersionBE.Codigo + "</Value></Eq><Eq><FieldRef Name='Version' /><Value Type='Number'>"+ objVersionBE.Version + "</Value></Eq></And></Where>"; SPListItemCollection items = oList.GetItems(oSPQuery); if (items!=null) { if (items.Count > 0) { foreach (SPListItem item in items) { if (borrarFechaCaducidad) item["FechaCaducidad"] = null; item["EstadoPasoFlujo"] = "Publicado"; item["Sincronizado"] = false; item.SystemUpdate(false); } } } } } }); } public static void cambiarEstadoObsoletoOtrasVersiones(DocumentoBE objDocumentoBE) { SPSecurity.RunWithElevatedPrivileges(() => { using (SPSite objSPSite = new SPSite(urlSitioPublicados)) { using (SPWeb objSPWeb = objSPSite.OpenWeb()) { objSPWeb.AllowUnsafeUpdates = true; if (objSPWeb.ParserEnabled) { objSPWeb.ParserEnabled = false; objSPWeb.Update(); } foreach (VersionBE objVersionBE in objDocumentoBE.Versiones) { if (objDocumentoBE.UltimaVersion.Version != objVersionBE.Version) { SPList oList = objSPWeb.Lists[objVersionBE.Biblioteca]; SPQuery oSPQuery = new SPQuery(); oSPQuery.Query = "<Where><And><Eq><FieldRef Name='CodigoDocumento' /><Value Type='Text'>" + objVersionBE.Codigo + "</Value></Eq><Eq><FieldRef Name='Version' /><Value Type='Number'>" + objVersionBE.Version + "</Value></Eq></And></Where>"; SPListItemCollection items = oList.GetItems(oSPQuery); if (items != null) { if (items.Count > 0) { foreach (SPListItem item in items) { item["EstadoPasoFlujo"] = "Obsoleto"; item["Sincronizado"] = false; item.SystemUpdate(false); } } } } } } } }); } public static void cambiarEstadoACaducado(VersionBE objVersionBE) { SPSecurity.RunWithElevatedPrivileges(() => { using (SPSite objSPSite = new SPSite(urlSitioPublicados)) { using (SPWeb objSPWeb = objSPSite.OpenWeb()) { objSPWeb.AllowUnsafeUpdates = true; if (objSPWeb.ParserEnabled) { objSPWeb.ParserEnabled = false; objSPWeb.Update(); } SPList oList = objSPWeb.Lists[objVersionBE.Biblioteca]; SPQuery oSPQuery = new SPQuery(); oSPQuery.Query = "<Where><And><Eq><FieldRef Name='CodigoDocumento' /><Value Type='Text'>" + objVersionBE.Codigo + "</Value></Eq><Eq><FieldRef Name='Version' /><Value Type='Number'>" + objVersionBE.Version + "</Value></Eq></And></Where>"; SPListItemCollection items = oList.GetItems(oSPQuery); if (items != null) { if (items.Count > 0) { foreach (SPListItem item in items) { item["EstadoPasoFlujo"] = "Caducado"; item["Sincronizado"] = false; item.SystemUpdate(false); } } } } } }); } private static void drawTextProgressBar(int progress, int total) { //draw empty progress bar Console.CursorLeft = 0; Console.Write("["); //start Console.CursorLeft = 32; Console.Write("]"); //end Console.CursorLeft = 1; float onechunk = 30.0f / total; //draw filled part int position = 1; for (int i = 0; i < onechunk * progress; i++) { Console.BackgroundColor = ConsoleColor.Green; Console.CursorLeft = position++; Console.Write(" "); } //draw unfilled part for (int i = position; i <= 31; i++) { Console.BackgroundColor = ConsoleColor.Gray; Console.CursorLeft = position++; Console.Write(" "); } //draw totals Console.CursorLeft = 35; Console.BackgroundColor = ConsoleColor.Black; Console.Write(progress.ToString() + "/" + total.ToString() + " "); //blanks at the end remove any excess } private static void grabarLog(string mensaje) { string urlLog = AppDomain.CurrentDomain.BaseDirectory + @"\Log" + DateTime.Now.ToString("yyyyMMdd") + ".txt"; StreamWriter log; if (!File.Exists(urlLog)) { log = new StreamWriter(urlLog, true, Encoding.UTF8); } else { log = File.AppendText(urlLog); } // Write to the file: log.WriteLine(DateTime.Now + " " + mensaje); // Close the stream: log.Close(); } #endregion } class DocumentoBE { public string Biblioteca { get; set; } public string Codigo { get; set; } public List<VersionBE> Versiones { get; set; } public VersionBE UltimaVersion { get; set; } } class VersionBE { public string Biblioteca { get; set; } public string Codigo { get; set; } public int Version { get; set; } public string Estado { get; set; } public DateTime FechaCaducidad { get; set; } public DateTime FechaPublicacion { get; set; } } class SharePointUtil { public static string ObtenerValorStringSPField( SPListItem pe_ojSPListItem, string pe_strCampo) { string vr_strValorCadena = null; if (pe_ojSPListItem[pe_strCampo] != null && pe_strCampo != null) { vr_strValorCadena = Convert.ToString(pe_ojSPListItem[pe_strCampo]).Trim(); } return vr_strValorCadena; } public static int ObtenerValorIntSPField( SPListItem pe_ojSPListItem, string pe_strCampo) { int vr_intValor = 0; if (pe_ojSPListItem[pe_strCampo] != null && pe_strCampo != null) { vr_intValor = Convert.ToInt32(Convert.ToDouble(pe_ojSPListItem[pe_strCampo])); } return vr_intValor; } public static DateTime ObtenerValorDateTimeSPField( SPListItem pe_ojSPListItem, string pe_strCampo) { DateTime vr_dateValor = DateTime.MinValue; if (pe_ojSPListItem[pe_strCampo] != null && pe_strCampo != null) { vr_dateValor = Convert.ToDateTime(pe_ojSPListItem[pe_strCampo]); } return vr_dateValor; } } public static class DataRecord { public static bool HasColumn(this IDataRecord r, string columnName) { try { return r.GetOrdinal(columnName) >= 0; } catch (IndexOutOfRangeException) { return false; } } } public class Logging { public static string RegistrarMensajeLogSharePointConParametros( string pe_strNombreCategoria, string pe_strNombreComponente, string pe_strParametros, Exception pe_objException) { //Se crea un GUID DE REFERENCIA del log a escribir string vr_strGUID = Guid.NewGuid().ToString("D").ToUpper(); //Se obtiene la excepcion base Exception objExceptionBase = pe_objException.GetBaseException(); //Se registra el log con privilegios elevados SPSecurity.RunWithElevatedPrivileges(delegate () { string strMensaje = string.Format("GUID DE REFERENCIA:{0}. COMPONENTE:{1}. PARAMETROS:{2}. MENSAJE DE ERROR:{3}. STACKTRACE:{4}", vr_strGUID, pe_strNombreComponente, pe_strParametros, objExceptionBase.Message, objExceptionBase.StackTrace); SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(pe_strNombreCategoria, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, strMensaje, null); }); //Se retorna el GUID generado de referencia al log return vr_strGUID; } public static string RegistrarMensajeLogSharePointConParametros( string pe_strNombreCategoria, string pe_strNombreComponente, string pe_strParametros) { //Se crea un GUID DE REFERENCIA del log a escribir string vr_strGUID = Guid.NewGuid().ToString("D").ToUpper(); //Se registra el log con privilegios elevados SPSecurity.RunWithElevatedPrivileges(delegate () { string strMensaje = string.Format("GUID DE REFERENCIA:{0}. COMPONENTE:{1}. PARAMETROS:{2}", vr_strGUID, pe_strNombreComponente, pe_strParametros); SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(pe_strNombreCategoria, TraceSeverity.High, EventSeverity.Error), TraceSeverity.High, strMensaje, null); }); //Se retorna el GUID generado de referencia al log return vr_strGUID; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IPTables.Net.Exceptions; namespace IPTables.Net.Iptables.IpSet { public class IpSetTypeHelper { /// <summary> /// Concert a set type in enum format to a string /// </summary> /// <param name="type"></param> /// <returns></returns> public static String TypeToString(IpSetType type) { String mode; if ((type & IpSetType.Hash) == IpSetType.Hash) { mode = "hash:"; } else if ((type & IpSetType.Bitmap) == IpSetType.Bitmap) { mode = "bitmap:"; } else { return null; } List<String> types = new List<string>(); if ((type & IpSetType.Ip) == IpSetType.Ip) { types.Add("ip"); } if ((type & IpSetType.Net) == IpSetType.Net) { types.Add("net"); } if ((type & IpSetType.Port) == IpSetType.Port) { types.Add("port"); } if ((type & IpSetType.Ip2) == IpSetType.Ip2) { types.Add("ip"); } if (types.Count == 0) return null; return mode + string.Join(",", types); } /// <summary> /// Convert a set type in string format to enum type /// </summary> /// <param name="str"></param> /// <returns></returns> public static IpSetType StringToType(String str) { IpSetType ret = 0; var parts = str.Split(new char[] { ':' }); if (parts[0] == "hash") { ret |= IpSetType.Hash; } else if (parts[0] == "bitmap") { ret |= IpSetType.Bitmap; } else { throw new IpTablesNetException(String.Format("Unknown set type: {0}", str)); } var types = parts[1].Split(','); foreach (var t in types) { if (t == "ip") { if ((ret & IpSetType.Ip) == IpSetType.Ip) ret |= IpSetType.Ip2; else ret |= IpSetType.Ip; } else if (t == "port") ret |= IpSetType.Port; else if (t == "net") ret |= IpSetType.Net; else throw new IpTablesNetException(String.Format("Unknown set type: {0}", str)); } return ret; } /// <summary> /// Return the format component of a ipset type (e.g hash) /// </summary> /// <param name="str"></param> /// <returns></returns> public static string TypeFormat(String str) { var parts = str.Split(new char[] {':'}); return parts[0]; } /// <summary> /// return the components in an ipset type (e.g ip, port) /// </summary> /// <param name="str"></param> /// <returns></returns> public static IEnumerable<string> TypeComponents(String str) { var parts = str.Split(new char[] { ',', ':' }); return parts.Skip(1); } } }
using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Text.RegularExpressions; using System.Data; using System.Web; namespace CommonLibrary { public static class Common { //json字符串过滤 public static string FilterJason(string var) { try { var = Regex.Replace(var, "(?<=\")\\d+(?=\")", "_$&"); var = var.Replace("\"", "'"); } catch { } return var; } //转换为int;异常为0 public static int ToInt(string var) { try { int intVar = int.Parse(var.Trim()); return intVar; } catch { } return 0; } public static int ToInt(string var, int defaultValue) { try { int intVar = int.Parse(var.Trim()); return intVar; } catch { } return defaultValue; } public static int ToInt(object var) { try { int intVar = int.Parse(var.ToString()); return intVar; } catch { } return 0; } //转换为short;异常为0 public static short ToShort(string var) { try { short shortVar = short.Parse(var.Trim()); return shortVar; } catch { } return 0; } //转换为bool类型 public static object ToBool(object var, object defaultValue) { object boolTemp = false; try { boolTemp = bool.Parse(var.ToString()); } catch { if (var.ToString().Trim() == "1" || var.ToString().Trim().ToLower() == "true") boolTemp = true; else boolTemp = defaultValue; } return boolTemp; } public static bool ToBool(object var) { bool boolTemp = false; try { boolTemp = bool.Parse(var.ToString()); } catch { if (var.ToString().Trim() == "1" || var.ToString().Trim() == "True") boolTemp = true; else boolTemp = false; } return boolTemp; } //转换为byte;异常为0 public static byte ToByte(string var) { try { byte byteVar = byte.Parse(var.Trim()); return byteVar; } catch { return 0; } } //字符串型参数传递,转换 public static string ToString(object var) { try { string strVar = Convert.ToString(var); return strVar; } catch { } return ""; } public static string ToString(object var, string defaultValue) { try { if (var == null) { return defaultValue; } else { string strVar = Convert.ToString(var); return strVar; } } catch { } return defaultValue; } //参数过滤转换 public static string ToParaString(string var) { string strVar = ""; return strVar; } //转换decimal;异常为0 public static decimal ToDecimal(string var) { try { decimal decimalVar = decimal.Parse(var.Trim()); return decimalVar; } catch { return 0; } } //转换double;异常为0 public static double ToDouble(string var) { try { double decimalVar = double.Parse(var.Trim()); return decimalVar; } catch { return 0; } } //转换double,保留小数位数 public static double ToDouble(string var, int num) { try { double decimalVar = double.Parse(var.Trim()); return Math.Round(decimalVar, num); } catch { return 0; } } //转换date;异常为null public static DateTime? ToDateTime(string var) { DateTime? dtmVar = null; try { dtmVar = DateTime.Parse(var.Trim()); } catch { dtmVar = null; } return dtmVar; } //转换date;异常为defaultDateTime public static DateTime ToDateTime(string var, DateTime defaultDateTime) { try { DateTime dtmVar = DateTime.Parse(var.Trim()); return dtmVar; } catch { return defaultDateTime; } } //转换date;异常为1900-1-1 public static DateTime DateTimeParse(string var) { try { DateTime dtmVar = DateTime.Parse(var.Trim()); return dtmVar; } catch { return DateTime.Parse("1900-1-1"); } } //Date转换string;异常为"" public static string ToDateString(DateTime? var) { try { string strVar = var.Value.ToString("yyyy-MM-dd"); return strVar; } catch { return ""; } } //Date转换string;异常为"" public static string ToDateTimeString(DateTime var) { try { string strVar = var.ToString("yyyy-MM-dd HH:mm"); return strVar; } catch { return ""; }; } //Date转换string;异常为"" public static string ToDateTimeString(string var) { try { DateTime dtVar = DateTime.Parse(var); string strVar = dtVar.ToString("yyyy-MM-dd HH:mm"); return strVar; } catch { return ""; }; } public static string ToIds(string var) { string[] arr = var.Split(','); string strRet = ""; for (int i = 0; i < arr.Length; i++) { if (IsInt(arr[i])) strRet += arr[i] + ","; } if (strRet.Length > 1) strRet = strRet.Substring(0, strRet.Length - 1); return strRet; } public static bool IsInt(string var) { try { int i = int.Parse(var); return true; } catch { return false; } } public static bool IsDouble(string var) { try { double d = double.Parse(var); return true; } catch { return false; } } public static bool IsNumber(string var) { try { double n = double.Parse(var); if (var.IndexOf(".") > -1) return false; return true; } catch { return false; } } public static bool IsMobile(string var) { if (var.Trim() == "") return false; return Regex.IsMatch(var, @"^(13|14|15|16|18|19)\d{9}$"); } public static bool IsDate(object var) { DateTime dtDate; try { dtDate = DateTime.Parse(var.ToString()); return true; } catch { return false; } } public static bool IsValidChar(string var) { if ("abcdefghijklmnopqrstuvwxyz_-.0123456789".IndexOf(var.ToLower()) < 0) return false; return true; } private static bool IsEnglishChar(string var) { if ("abcdefghijklmnopqrstuvwxyz".IndexOf(var.ToLower()) < 0) return false; return true; } public static bool IsEnglish(string var) { for (int i = 0; i < var.Length; i++) { if (!IsEnglishChar(var.Substring(i, 1))) return false; } return true; } //判断是否是正确的email地址 private static bool IsEmailText(string email) { if (email.Length < 1) return false; if (email.Substring(0, 1) == "." || In(email.Substring(email.Length - 1, 1), ".,_,-")) return false; if (email.IndexOf("..") > 0) return false; if (email.IndexOf("--") > 0) return false; if (email.IndexOf("__") > 0) return false; string strChar = ""; for (int i = 0; i < email.Length; i++) { strChar = email.Substring(i, 1); if (!IsValidChar(strChar)) return false; } return true; } public static bool IsEmaill(string email) { string[] arr; arr = email.Split('@'); if (arr.Length != 2) return false; if (!IsEmailText(arr[0])) return false; if (!IsEmailText(arr[1])) return false; string[] arrRight; arrRight = arr[1].Split('.'); if (arrRight.Length < 2) return false; if (arrRight[arrRight.Length - 1].Length < 2 || arrRight[arrRight.Length - 1].Length > 4) return false; if (!IsEnglish(arrRight[arrRight.Length - 1])) return false; return true; } //判断是否是合法密码 public static bool IsPassWord(string passWord) { string strPasswordPattern = @"^[A-Za-z0-9-_.]{6,20}$"; Regex reg = new Regex(strPasswordPattern, RegexOptions.IgnoreCase); if (reg.Match(passWord).Success) return true; return false; } // 转换成用于显示的纯文本 // 源字符串: xi'an;改为:xi&acute;an public static string ToText(string input) { if (!string.IsNullOrWhiteSpace(input)) { input = Regex.Replace(input, "\r\n", "\n"); input = input.Replace(" ", "&nbsp; "); input = Regex.Replace(input, "\r", "<br />"); input = Regex.Replace(input, "\n", "<br />"); input = input.Replace("'", "&acute;"); input = input.Replace("\"", "&quot;"); return input; } else return ""; } //控制页面代码显示 //用于js变量输出的字符串 //源字符串:<p style="...">...</p>;改为:<p style=\"...\">...</p> public static string JsEncode(string input) { if (input.Trim() != "") { input = input.Replace(@"\", @"\\"); input = input.Replace("\"", "\\\""); input = input.Replace("'", @"\'"); input = input.Replace("\t", "\\t"); input = input.Replace("\r", "\\r"); input = input.Replace("\n", "\\n"); input = input.Replace("\f", "\\f"); input = input.Replace("\b", "\\b"); } return input; } public static string Encode(string input) { input = input.Replace("\"\"", "&#34;"); input = input.Replace("\'", "&#39;"); return input; } // 页面上直接输出文本内容,支持标签 public static string ToHtml(string input) { if (!string.IsNullOrWhiteSpace(input)) { input = Regex.Replace(input, "\r\n", "\n"); input = input.Replace(" ", "&nbsp; "); input = input.Replace(" >", "&nbsp;>"); //input = Regex.Replace(input, "\r", "<br />"); //input = Regex.Replace(input, "\n", "<br />"); input = input.Replace("\r", "<br />"); input = input.Replace("\n", "<br />"); input = input.Replace("'", "'"); input = input.Replace("\"", "“"); return input; } else return ""; } public static string ToBriefView(string input) { if (!string.IsNullOrWhiteSpace(input)) { input = Regex.Replace(input, "\r\n", "\n"); input = input.Replace("\r", " "); input = input.Replace("\n", " "); input = input.Replace("'", "'"); input = input.Replace("\"", "“"); return input; } else return ""; } //标签过滤,用于 企业页面查看企业简介 public static string PageBriefFilter(string str) { if (str.Trim() != "") { str = str.Replace("&gt;", ">"); str = str.Replace("&lt;", "<"); str = str.Replace("\n\r", "\n"); str = str.Replace("\r\n", "\n"); str = Regex.Replace(str, @"<b[^>]*?>", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, @"<strong[^>]*?>", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "<p[^>]*?>", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "<div[^>]*?>", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "<font[^>]*?>", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "<span[^>]*?>", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "<img[^>]*?>", "", RegexOptions.IgnoreCase); str = Regex.Replace(str, "</[^>]*?>", "", RegexOptions.IgnoreCase); str = str.Replace("<", "&lt;"); str = str.Replace(" ", "&nbsp; "); } return str; } //用于企业会员中心去掉标签 public static string CenterBriefFilter(string Str) { if (!string.IsNullOrWhiteSpace(Str)) { Str = Str.Replace("&gt;", ">"); Str = Str.Replace("&lt;", "<"); Str = Str.Replace("\r\n", "\n"); Str = Str.Replace("\n\r", "\n"); Str = Regex.Replace(Str, "<b[^>]+>", ""); Str = Regex.Replace(Str, "<B[^>]+>", ""); Str = Regex.Replace(Str, "<b>", ""); Str = Regex.Replace(Str, "<B>", ""); Str = Regex.Replace(Str, "<strong>", ""); Str = Regex.Replace(Str, "<p>", ""); Str = Regex.Replace(Str, "<div>", ""); Str = Regex.Replace(Str, "<STRONG>", ""); Str = Regex.Replace(Str, "<P>", ""); Str = Regex.Replace(Str, "<DIV>", ""); Str = Regex.Replace(Str, "<strong[^>]+>", ""); Str = Regex.Replace(Str, "<STRONG[^>]+>", ""); Str = Regex.Replace(Str, "<font[^>]+>", ""); Str = Regex.Replace(Str, "<FONT[^>]+>", ""); Str = Regex.Replace(Str, "<span[^>]+>", ""); Str = Regex.Replace(Str, "<SPAN[^>]+>", ""); Str = Regex.Replace(Str, "<p[^>]+>", ""); Str = Regex.Replace(Str, "<P[^>]+>", ""); Str = Regex.Replace(Str, "<div[^>]+>", ""); Str = Regex.Replace(Str, "<DIV[^>]+>", ""); Str = Regex.Replace(Str, "</[^>]+>", ""); Str = Str.Replace("<", "&lt;"); Str = Str.Replace(" ", "&nbsp; "); } return Str; } /// 将字符串转换为纯文本。用于关键词搜索 public static string AbstractText(string Str) { if (!string.IsNullOrWhiteSpace(Str)) { Str = Str.Replace("&nbsp;", ""); Str = Regex.Replace(Str, "\r", " "); Str = Regex.Replace(Str, "\n", " "); Str = Str.Replace("<br>", ""); Str = Str.Replace("<br />", ""); Str = Str.Replace("<p>", ""); Str = Str.Replace("</p>", ""); Str = Str.Replace("<div>", ""); Str = Str.Replace("</div>", ""); Str = Regex.Replace(Str, "<[^>]+>", ""); Str = Str.Replace(">", "&gt;"); Str = Str.Replace("<", "&lt;"); return Str.Trim(); } else return ""; } //转换输入的文本为数据库标准。主要是转换<> public static string ToSqlChars(string input) { if (!string.IsNullOrWhiteSpace(input)) { input = input.Replace("<", "&lt;"); input = input.Replace(">", "&gt;"); return input; } return ""; } /// 截取指定字节长度的字符串 /// <param name="str">原字符串</param> /// <param name="len">截取字节长度</param> public static string ByteLeft(string str, int len) { string result = string.Empty; // 最终返回的结果 if (string.IsNullOrEmpty(str)) { return result; } int byteLen = System.Text.Encoding.Default.GetByteCount(str); // 单字节字符长度 int charLen = str.Length; // 把字符平等对待时的字符串长度 int byteCount = 0; // 记录读取进度 int pos = 0; // 记录截取位置 if (byteLen > len) { for (int i = 0; i < charLen; i++) { if (Convert.ToInt32(str.ToCharArray()[i]) > 255) // 按中文字符计算加2 byteCount += 2; else// 按英文字符计算加1 byteCount += 1; if (byteCount > len) // 超出时只记下上一个有效位置 { pos = i; break; } else if (byteCount == len)// 记下当前位置 { pos = i + 1; break; } } if (pos >= 0) result = str.Substring(0, pos); } else { result = str; } try { if (result.Substring(result.Length - 1, 1).Equals("(") || result.Substring(result.Length - 1, 1).Equals("(")) { result = result.Substring(0, result.Length - 1); } } catch { } return result; } public static string Left(string input, int length) { if (input.Length > length) return input.Substring(0, length); else return input; } public static string Right(string input, int length) { if (input.Length > length) return input.Substring(input.Length - length, length); else return input; } /// 截取指定字节长度的字符串 /// <param name="str">原字符串</param> /// <param name="startIndex">起始位置</param> /// <param name="len">截取字节长度</param> public static string CutByteString(string str, int startIndex, int len) { string result = string.Empty; //最终返回的结果 if (string.IsNullOrEmpty(str)) { return result; } int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度 int charLen = str.Length; // 把字符平等对待时的字符串长度 if (startIndex == 0) { return ByteLeft(str, len); } else if (startIndex >= byteLen) { return result; } else //startIndex < byteLen { int AllLen = startIndex + len; int byteCountStart = 0; // 记录读取进度 int byteCountEnd = 0; // 记录读取进度 int startpos = 0; // 记录截取位置&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; int endpos = 0; // 记录截取位置 for (int i = 0; i < charLen; i++) { if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2 byteCountStart += 2; else // 按英文字符计算加1 byteCountStart += 1; if (byteCountStart > startIndex) // 超出时只记下上一个有效位置 { startpos = i; AllLen = startIndex + len - 1; break; } else if (byteCountStart == startIndex)// 记下当前位置 { startpos = i + 1; break; } } if (startIndex + len <= byteLen)//截取字符在总长以内 { for (int i = 0; i < charLen; i++) { if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2 byteCountEnd += 2; else // 按英文字符计算加1 byteCountEnd += 1; if (byteCountEnd > AllLen)// 超出时只记下上一个有效位置 { endpos = i; break; } else if (byteCountEnd == AllLen)// 记下当前位置 { endpos = i + 1; break; } } endpos = endpos - startpos; } else if (startIndex + len > byteLen)//截取字符超出总长 { endpos = charLen - startpos; } if (endpos >= 0) { result = str.Substring(startpos, endpos); } } return result; } static ArrayList arrayShieldWord = new ArrayList(); public static bool HasShieldWord(string strText) { SetShieldWord(); for (int i = 0; i < arrayShieldWord.Count; i++) { if (strText.Contains(arrayShieldWord[i].ToString())) return true; } return false; } private static void SetShieldWord() { if (arrayShieldWord.Count == 0) { arrayShieldWord.Add("ktv"); arrayShieldWord.Add("酒吧"); arrayShieldWord.Add("公关"); arrayShieldWord.Add("少爷"); arrayShieldWord.Add("俱乐部"); arrayShieldWord.Add("夜场"); arrayShieldWord.Add("鸭子"); arrayShieldWord.Add("小姐"); arrayShieldWord.Add("特服"); arrayShieldWord.Add("会所"); arrayShieldWord.Add("同性恋"); arrayShieldWord.Add("vip"); } } public static bool In(string strChecked, string[] arrkey) { for (int i = 0; i < arrkey.Length; i++) { if (strChecked == arrkey[i]) return true; } return false; } public static bool In(string strChecked, string key) { string[] arrKey = key.Split(','); return In(strChecked, arrKey); } public static string IIF(bool flag, string first, string second) { if (flag) return first; else return second; } public static int IIF(bool flag, int first, int second) { if (flag) return first; else return second; } public static string IIF(bool flag, string first, int second) { if (flag) return first; else return second.ToString(); } public static string GenSqlParam(string parm) { if (string.IsNullOrWhiteSpace(parm)) return null; else return parm; } //Sean增加 Escape + UnEscape 20120704 //在C#后台实现JavaScript的函数escape()的字符串转换 //些方法支持汉字 public static string Escape(string s) { StringBuilder sb = new StringBuilder(); byte[] byteArr = System.Text.Encoding.Unicode.GetBytes(s); for (int i = 0; i < byteArr.Length; i += 2) { sb.Append("%u"); sb.Append(byteArr[i + 1].ToString("X2"));//把字节转换为十六进制的字符串表现形式 sb.Append(byteArr[i].ToString("X2")); } return sb.ToString(); } //把JavaScript的escape()转换过去的字符串解释回来 //些方法支持汉字 public static string UnEscape(string s) { string str = ""; try { str = s.Remove(0, 2);//删除最前面两个"%u" string[] strArr = str.Split(new string[] { "%u" }, StringSplitOptions.None);//以子字符串"%u"分隔 byte[] byteArr = new byte[strArr.Length * 2]; for (int i = 0, j = 0; i < strArr.Length; i++, j += 2) { byteArr[j + 1] = Convert.ToByte(strArr[i].Substring(0, 2), 16); //把十六进制形式的字串符串转换为二进制字节 byteArr[j] = Convert.ToByte(strArr[i].Substring(2, 2), 16); } str = System.Text.Encoding.Unicode.GetString(byteArr); //把字节转为unicode编码 } catch { str = s; } return str; } //Sean 增加结束 //20121220 Nick增加 用户 JS传值的 解码 //public static string UnEscapeJs(string s) //{ // string str = ""; // try // { // str = Microsoft.JScript.GlobalObject.unescape(s); // } // catch { } // return str; //} /// lambo 增加 20120802 /// 获取指定日期是周几 public static string GetDayOfWeek(DateTime dtm) { switch (dtm.DayOfWeek) { case DayOfWeek.Sunday: return "周日"; case DayOfWeek.Monday: return "周一"; case DayOfWeek.Tuesday: return "周二"; case DayOfWeek.Wednesday: return "周三"; case DayOfWeek.Thursday: return "周四"; case DayOfWeek.Friday: return "周五"; case DayOfWeek.Saturday: return "周六"; default: return ""; } } public static string CalcAge(string birthday) { if (birthday.Trim() == "") { return ""; } int intDifYear = 0, intDifMonth = 0; try { intDifYear = DateTime.Now.Year - Common.ToInt(birthday.Substring(0, 4)); intDifMonth = DateTime.Now.Month - Common.ToInt(birthday.Substring(4, 2)); if (intDifMonth < 0) { return (intDifYear - 1).ToString() + "岁"; } else { return intDifYear.ToString() + "岁"; } } catch { return ""; } } public static string GenParam(string var) { if (string.IsNullOrWhiteSpace(var)) return null; if (var.Trim() != "") { var = var.Replace(" ", ","); } return var; } public static string GetRowValue(DataRow row, string key) { if (null == row) return ""; return row[key].ToString(); } // 将html标签去掉,用于显示企业简介和职位要求、岗位职责 public static string HtmlFilter(string Str) { if (!string.IsNullOrWhiteSpace(Str)) { Str = Str.Replace("<p></p>\r", ""); Str = Str.Replace("</p>\r", ""); Str = Str.Replace("<P></P>\r", ""); Str = Str.Replace("</P>\r", ""); Str = Str.Replace("\n\r", "\n"); Str = Str.Replace("\r\n", "\n"); Str = Str.Replace("<br>\n", "\n"); Str = Str.Replace("<br>", "\n"); Str = Str.Replace("<br />", "\n"); Str = Str.Replace("<p></p>", ""); Str = Str.Replace("</p>", ""); Str = Str.Replace("<strong>", ""); Str = Str.Replace("<div>", "\n"); Str = Str.Replace("<BR>\n", "\n"); Str = Str.Replace("<BR>", "\n"); Str = Str.Replace("<BR />", "\n"); Str = Str.Replace("<P></P>", ""); Str = Str.Replace("</P>", ""); Str = Str.Replace("<P>", "\n"); Str = Str.Replace("<p>", "\n"); Str = Str.Replace("<strong>", ""); Str = Str.Replace("<div>", "\n"); Str = Regex.Replace(Str, "<font[^>]+>", ""); Str = Regex.Replace(Str, "<FONT[^>]+>", ""); Str = Regex.Replace(Str, "<P[^>]+>", ""); Str = Regex.Replace(Str, "<p[^>]+>", ""); Str = Regex.Replace(Str, "</[^>]+>", ""); Str = Regex.Replace(Str, "<b[^>]+>", ""); Str = Regex.Replace(Str, "<b>", ""); Str = Str.Replace(">", "&gt;"); Str = Str.Replace("<", "&lt;"); Str = Str.Replace(" ", "&nbsp; "); return Str; } else return ""; } // max 2013-07-25 将我们的招聘人数转换为招聘人数的薪水 public static string ToNeedNumber(int NeedNumber) { string strNeedNumber = ""; switch (NeedNumber) { case 0: strNeedNumber = "不限"; break; case 1: strNeedNumber = "1人"; break; case 2: strNeedNumber = "2人"; break; case 3: strNeedNumber = "3-5人"; break; case 4: strNeedNumber = "6-10人"; break; case 5: strNeedNumber = "11-20人"; break; case 6: strNeedNumber = "21-50人"; break; case 7: strNeedNumber = "51-100人"; break; case 8: strNeedNumber = "101-200人"; break; case 9: strNeedNumber = "200人以上"; break; } return strNeedNumber; } // max 2013-07-25 将我们的薪水转换为北大青鸟的薪水 public static string ToBdqnSalary(int dcSalaryID) { string strBdqnSalary = ""; switch (dcSalaryID) { case 4: strBdqnSalary = "2000元-3000元"; break; case 5: case 6: strBdqnSalary = "3000元-5000元"; break; case 7: strBdqnSalary = "5000元-8000元"; break; case 8: strBdqnSalary = "8000元-10000元"; break; case 9: case 10: case 11: strBdqnSalary = "一万元以上"; break; default: strBdqnSalary = "面议"; break; } return strBdqnSalary; } // max 2013-07-25 将我们的行业转换为北大青鸟的行业 public static string ToBdqnIndustry(string CategoryIDs) { string strBdqnIndustry = ""; string[] ArrCategory = CategoryIDs.Split(','); for (int i = 0; i < ArrCategory.Length; i++) { switch (ArrCategory[i]) { case "1": strBdqnIndustry = strBdqnIndustry + ",IT|互联网|通信|电子"; break; case "2": strBdqnIndustry = strBdqnIndustry + ",金融|银行|保险"; break; case "3": strBdqnIndustry = strBdqnIndustry + ",房产|建筑|物业"; break; case "4": strBdqnIndustry = strBdqnIndustry + ",广告|传媒|印刷出版"; break; case "5": strBdqnIndustry = strBdqnIndustry + ",消费零售|贸易|交通物流"; break; case "6": strBdqnIndustry = strBdqnIndustry + ",加工制造"; break; case "7": strBdqnIndustry = strBdqnIndustry + ",管理咨询"; break; case "10": strBdqnIndustry = strBdqnIndustry + ",政府|非营利机构|科研"; break; default: strBdqnIndustry = strBdqnIndustry + ",其他"; break; } } strBdqnIndustry = strBdqnIndustry.Substring(1, strBdqnIndustry.Length - 1); return strBdqnIndustry; } // max 2013-07-25 将我们的企业规模转换为北大青鸟的企业规模业 public static string ToBdqnCompanySize(string CompanySizeID) { string strBdqnCompanySize = "0-50人"; switch (CompanySizeID) { case "1": strBdqnCompanySize = "0-50人"; break; case "2": strBdqnCompanySize = "50-100人"; break; case "3": case "4": strBdqnCompanySize = "100-500人"; break; case "5": case "6": strBdqnCompanySize = "500人以上"; break; } return strBdqnCompanySize; } public static int ToOurNationID(string Nation) { int NationID = 11; string[] arrNation = { "汉族", "壮族", "满族", "回族", "苗族", "维吾尔族", "土家族", "彝族", "蒙古族", "藏族" }; int[] arrNationID = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; for (int i = 0; i < arrNation.Length; i++) { if (arrNation[i] == Nation) { NationID = arrNationID[i]; } } return NationID; } public static int ToOurRelatedWorkYears(string RelatedWorkYears) { int RelatedWorkYearsID = 0; switch (RelatedWorkYears) { case "无": RelatedWorkYearsID = 0; break; case "一年": case "两年": RelatedWorkYearsID = 1; break; case "三年": case "四年": case "五年": RelatedWorkYearsID = 2; break; case "五年以上": RelatedWorkYearsID = 3; break; } return RelatedWorkYearsID; } public static int ToOurEmployType(string EmployType) { int EmployTypeID = 1; switch (EmployType) { case "实习": EmployTypeID = 4; break; case "全职": EmployTypeID = 1; break; case "全职/实习": EmployTypeID = 2; break; case "兼职": EmployTypeID = 3; break; } return EmployTypeID; } public static int ToOurdcSalary(string dcSalary) { int dcSalaryID = 4; switch (dcSalary) { case "2000-3000": dcSalaryID = 4; break; case "3000-5000": dcSalaryID = 5; break; case "5000-8000": dcSalaryID = 6; break; case "8000-10000": dcSalaryID = 8; break; case "10000以上": dcSalaryID = 9; break; case "面议": dcSalaryID = 0; break; } return dcSalaryID; } // max 2013-08-07 将北大青鸟的职位类别转换为我们的职位类别ID public static int ToOurJobTypeID(string strJobType) { int JobTypeID = 2410; string[] arrJobType = { "软件测试", "PHP方向开发", "JAVA方向开发", ".NET方向开发", "Android方向开发", "网络运维", "网络安全", "网络营销", "售前/售后支持", "系统集成", "手机软件开发", "系统架构", "数据库", "系统管理", "网站运营", "SEO优化", "SEM竞价", "计算机/网络/技术类", "贸易/运输类", "销售类", "人力资源类", "法律类", "教育类", "行政后勤类", "保险类", "翻译类", "金融类", "其他" }; int[] arrJobTypeID = { 2613, 2410, 2410, 2410, 2410, 2313, 2317, 1122, 1414, 2215, 2410, 2414, 2412, 2217, 2313, 2316, 2316, 2410, 5521, 1121, 2012, 4210, 4110, 2112, 3110, 4419, 3025, 5627 }; for (int i = 0; i < arrJobType.Length; i++) { if (arrJobType[i] == strJobType) { JobTypeID = arrJobTypeID[i]; break; } } return JobTypeID; } // max 2013-08-07 将北大青鸟的职位类别转换为我们的职位类别ID public static int ToOurIndustryID(string strIndustry) { int IndustryID = 31; string[] arrIndustry = { "IT|互联网|通信|电子", "金融|银行|保险", "房产|建筑|物业 ", "广告|传媒|印刷出版", "消费零售|贸易|交通物流", "加工制造", "管理咨询", "政府|非赢利机构|科研", "其他" }; int[] arrIndustryID = { 31, 36, 8, 25, 41, 16, 48, 27, 100 }; for (int i = 0; i < arrIndustry.Length; i++) { if (arrIndustry[i] == strIndustry) { IndustryID = arrIndustryID[i]; break; } } return IndustryID; } public static string AddXX(string text) { try { if (!string.IsNullOrWhiteSpace(text.Trim())) { return "/" + text; } } catch (Exception) { return ""; } return ""; } public static int ToOurDegreeID(string Degree) { int DegreeID = 11; string[] arrDegree = { "中专", "专科", "本科", "硕士", "博士" }; int[] arrDegreeID = { 4, 5, 6, 7, 8 }; for (int i = 0; i < arrDegree.Length; i++) { if (arrDegree[i] == Degree) { DegreeID = arrDegreeID[i]; } } return DegreeID; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class SoundManager : MonoBehaviour { // Singleton // public static SoundManager instance { get; protected set; } void Awake () { if (instance == null) { instance = this; } else if (instance != this) { Destroy (gameObject); } DontDestroyOnLoad (gameObject); LoadAllSounds (); RegisterSounds (); } // Singleton // public static bool soundIsOff = false; public static bool musicIsOff = false; Dictionary<string,AudioClip> stringAudioClipMap; Dictionary<string,AudioSource> stringAudioSourceLoopMap; Dictionary<string,AudioClip> stringAudioClipMusicMap; AudioSource[] audioSources = new AudioSource[10]; int nextAudioSource = 0; AudioSource[] audioSources_loop = new AudioSource[5]; int nextAudioSource_loop = 0; AudioSource[] audioSources_music = new AudioSource[2]; int currentMusicChannel = 0; void OnDestroy() { cb_setMusic -= SetMusic; cb_setSound -= SetSound; cb_playSound -= PlaySound; cb_stopSound -= StopSound; cb_leftRoom_start -= StopLoopSounds; cb_enteredRoom_start -= ActivateLoopSounds; EventsHandler.cb_roomCreated -= SwitchMusic; EventsHandler.cb_shadowStateChanged -= SwitchShadowStateMusic; } // Update is called once per frame void Update () { } public void RegisterSounds() { cb_setMusic += SetMusic; cb_setSound += SetSound; cb_playSound += PlaySound; cb_stopSound += StopSound; cb_leftRoom_start += StopLoopSounds; cb_enteredRoom_start += ActivateLoopSounds; EventsHandler.cb_roomCreated += SwitchMusic; EventsHandler.cb_shadowStateChanged += SwitchShadowStateMusic; } // Loading Sounds // public void LoadAllSounds() { for (int i = 0; i < audioSources.Length; i++) { audioSources [i] = gameObject.AddComponent<AudioSource> (); } for (int i = 0; i < audioSources_loop.Length; i++) { audioSources_loop [i] = gameObject.AddComponent<AudioSource> (); } for (int i = 0; i < audioSources_music.Length; i++) { audioSources_music [i] = gameObject.AddComponent<AudioSource> (); audioSources_music [i].loop = true; } AudioClip[] clipList_sound = Resources.LoadAll<AudioClip> ("Audio/SoundEffects"); AudioClip[] clipList_music = Resources.LoadAll<AudioClip> ("Audio/Music"); stringAudioClipMap = new Dictionary<string, AudioClip> (); stringAudioSourceLoopMap = new Dictionary<string, AudioSource> (); stringAudioClipMusicMap = new Dictionary<string, AudioClip> (); // Populate clipList foreach (AudioClip clip in clipList_sound) { stringAudioClipMap.Add (clip.name, clip); } foreach (AudioClip clip in clipList_music) { stringAudioClipMusicMap.Add (clip.name, clip); } } // ------ SET SOUND AND MUSIC ------ // // Set music on/off in settings public void SetMusic(bool musicOff) { foreach (AudioSource audioSource in audioSources_music) { audioSource.mute = musicOff; } musicIsOff = musicOff; } // Set sound on/off in settings public void SetSound(bool soundOff) { foreach (AudioSource audioSource in audioSources) { audioSource.mute = soundOff; } foreach (AudioSource audioSource in audioSources_loop) { audioSource.mute = soundOff; } soundIsOff = soundOff; } // ------ MUSIC ------ // // SWITCH BETWEEN ROOMS MUSIC public void SwitchMusic(Room nextRoom) { if (audioSources_music [currentMusicChannel].clip == null) { if (stringAudioClipMusicMap.ContainsKey(nextRoom.myMusic)) { audioSources_music [currentMusicChannel].clip = stringAudioClipMusicMap [nextRoom.myMusic]; audioSources_music [currentMusicChannel].Play (); } return; } if (nextRoom.roomState == RoomState.Mirror) { if (nextRoom.myMirrorRoom.inTheShadow == true) { // SHADOW ROOM if (audioSources_music [currentMusicChannel].clip.name == nextRoom.myMirrorRoom.myShadowMusic) { return; } } else { // MIRROR ROOM if (audioSources_music [currentMusicChannel].clip.name == nextRoom.myMusic) { return; } } } else { // REAL ROOM if (audioSources_music [currentMusicChannel].clip.name == nextRoom.myMusic) { return; } } string clipName = nextRoom.myMusic; float fadeSpeed = NavigationManager.fadeSpeed; // if next room is in shadow state if (nextRoom.roomState == RoomState.Mirror) { if (nextRoom.myMirrorRoom.inTheShadow == true) { clipName = nextRoom.myMirrorRoom.myShadowMusic; } } if (stringAudioClipMusicMap.ContainsKey (clipName) == false) { Debug.LogError ("couldn't find clip name"); return; } StartCoroutine (CrossFadeMusic (clipName,fadeSpeed)); } // SWITCH SHADOW STATE MUSIC public void SwitchShadowStateMusic(bool intoShadows) { Room myRoom = RoomManager.instance.myRoom; string clipName; float fadeSpeed = NavigationManager.fadeSpeed * 2; if (myRoom.roomState == RoomState.Real) { return; } if (myRoom.myMirrorRoom == null) { return; } if (myRoom.myMusic == myRoom.myMirrorRoom.myShadowMusic) { return; } if (intoShadows == true) { clipName = myRoom.myMirrorRoom.myShadowMusic; } else { clipName = myRoom.myMusic; } if (stringAudioClipMusicMap.ContainsKey (clipName) == false) { Debug.LogError ("couldn't find clip name"); return; } StartCoroutine (CrossFadeMusic (clipName,fadeSpeed)); } // -- CROSS FADE MUSIC -- // IEnumerator CrossFadeMusic(string nextClip, float fadeSpeed) { int nextMusicChannel = currentMusicChannel == 0 ? 1 : 0; audioSources_music [nextMusicChannel].clip = stringAudioClipMusicMap [nextClip]; audioSources_music [nextMusicChannel].Play (); float i = 0; while (i < 1) { audioSources_music[currentMusicChannel].volume = 1-i; audioSources_music [nextMusicChannel].volume = i; i += Time.deltaTime / fadeSpeed; yield return new WaitForFixedUpdate (); } audioSources_music[currentMusicChannel].volume = 0; audioSources_music [currentMusicChannel].Stop (); audioSources_music [nextMusicChannel].volume = 1; currentMusicChannel = nextMusicChannel; } // ------ SOUND ------ // public void PlaySound(string soundName, int numberOfPlays) { if (numberOfPlays == 0) { audioSources_loop[nextAudioSource_loop].clip = stringAudioClipMap [soundName]; StartCoroutine(PlaySoundList (audioSources_loop [nextAudioSource_loop], numberOfPlays)); nextAudioSource_loop ++; } else { audioSources[nextAudioSource].clip = stringAudioClipMap [soundName]; StartCoroutine(PlaySoundList (audioSources [nextAudioSource], numberOfPlays)); nextAudioSource ++; } } public void StopSound(string soundName) { if (stringAudioSourceLoopMap.ContainsKey (soundName)) { stringAudioSourceLoopMap [soundName].Stop (); stringAudioSourceLoopMap.Remove (soundName); } } // play sound a unmber of times. If the number is 0, play sound in loop. IEnumerator PlaySoundList(AudioSource audioSource, int n) { if (n == 0) { // PLAY IN LOOP audioSource.loop = true; audioSource.Play (); stringAudioSourceLoopMap.Add (audioSource.clip.name, audioSource); yield return null; } else { int i = 0; while (i < n) { audioSource.Play (); i++; yield return new WaitForSeconds (audioSource.clip.length); } } } // When leaving a room, stopping loop sounds public void StopLoopSounds() { StartCoroutine(FadeOutLoopSounds()); } // ---- FADE IN & OUT ---- // IEnumerator FadeOutLoopSounds() { float i = 1; while (i > 0) { foreach (AudioSource audioSource in audioSources_loop) { audioSource.volume = i; } i -= Time.deltaTime / NavigationManager.fadeSpeed; yield return new WaitForFixedUpdate (); } foreach (AudioSource audioSource in audioSources_loop) { audioSource.Stop(); } stringAudioSourceLoopMap.Clear(); } public void ActivateLoopSounds() { StartCoroutine(FadeInLoopSounds()); } IEnumerator FadeInLoopSounds() { float i = 0; while (i < 1) { foreach (AudioSource audioSource in audioSources_loop) { audioSource.volume = i; } i += Time.deltaTime / NavigationManager.fadeSpeed; yield return new WaitForFixedUpdate (); } foreach (AudioSource audioSource in audioSources_loop) { audioSource.volume = 1; } } // ------------- STATIC EVENTS ------------- // public static Action<string,int> cb_playSound; public static void Invoke_cb_playSound(string soundName, int numberOfPlays) { if(cb_playSound != null) { cb_playSound (soundName,numberOfPlays); } } public static Action<string> cb_stopSound; public static void Invoke_cb_stopSound(string soundName) { if(cb_stopSound != null) { cb_stopSound (soundName); } } public static Action cb_leftRoom_start; public static void Invoke_cb_leftRoom_start() { if(cb_leftRoom_start != null) { cb_leftRoom_start (); } } public static Action cb_enteredRoom_start; public static void Invoke_cb_enteredRoom_start() { if(cb_enteredRoom_start != null) { cb_enteredRoom_start (); } } public static Action<bool> cb_setSound; public static void Invoke_cb_setSound(bool soundOff) { if(cb_setSound != null) { cb_setSound (soundOff); } } public static Action<bool> cb_setMusic; public static void Invoke_cb_setMusic(bool musicOff) { if(cb_setMusic != null) { cb_setMusic (musicOff); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GoldCollision : MonoBehaviour { [HideInInspector] public GameMode gameMode; void Start () { gameMode = GameObject.FindObjectOfType<GameMode>(); } void Update () { } private void OnTriggerExit(Collider other) { var player = other.gameObject.GetComponent<PlayerController>(); if (player) { gameMode.goldNumber++; Destroy(gameObject); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DotNetCoreIdentity.Domain.Identity; using DotNetCoreIdentity.Domain.RolesClaims; using DotNetCoreIdentity.Web.ViewModels.Manage; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; namespace DotNetCoreIdentity.Web.Account.Controllers { [Authorize(Roles = "Admin")] [Route("Manage")] [Area("Account")] public class ManageController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly RoleManager<IdentityRole> _roleManager; private readonly SignInManager<ApplicationUser> _signInManager; public ManageController( UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, SignInManager<ApplicationUser> signInManager ) { _userManager = userManager; _roleManager = roleManager; _signInManager = signInManager; } [Route("")] [Route("Index")] public IActionResult Index() { List<UserViewModel> users = _userManager.Users .Select(x => new UserViewModel { Id = x.Id, Email = x.Email, FirstName = x.FirstName, LastName = x.LastName, FullName = x.FirstName + " " + x.LastName, NationalIdNumber = x.NationalIdNumber }) .ToList(); // tum kullanicilar listelensin return View(users); } [Route("Users/Detail/{userId}")] public async Task<IActionResult> UserDetail(string userId) { var user = await _userManager.FindByIdAsync(userId); var model = new UserViewModel { Email = user.Email, FirstName = user.FirstName, LastName = user.LastName, Id = user.Id, FullName = user.FirstName + " " + user.LastName, NationalIdNumber = user.NationalIdNumber }; ViewBag.UserRoles = "Role sahip degil"; var userRoles = await _userManager.GetRolesAsync(user); if (userRoles.Any()) { ViewBag.UserRoles = string.Join(", ", userRoles); } return View(model); } [Route("Roles")] public IActionResult Roles() { // tum roller listelensin List<RoleViewModel> roles = _roleManager.Roles .Select(x => new RoleViewModel { Id = x.Id, Name = x.Name }).ToList(); // belki component yapabiliriz return View(roles); } [Route("Roles/Create")] public IActionResult CreateRole() { // yeni rol olusturma // rolesList component bunun view'inda yer alabilir return View(); } [HttpPost] [Route("Roles/Create")] public async Task<IActionResult> CreateRole(RoleViewModel model) { // model valid mi if (ModelState.IsValid) { // bu rol var mi test edelim var roles = await _roleManager.FindByNameAsync(model.Name); if (roles != null) { ModelState.AddModelError(string.Empty, "Bu isimde bir rol mevcut!"); return View(model); } // yoksa olusturalim var result = await _roleManager.CreateAsync(new IdentityRole { Name = model.Name }); // rol listesine yonlendirelim if (result.Succeeded) return RedirectToAction("Roles"); else { ModelState.AddModelError(string.Empty, "Kayıt esnasında bir hata oluştu!"); var roleCreationErrors = result.Errors.Select(x => x.Description); ModelState.AddModelError(string.Empty, string.Join(", ", roleCreationErrors)); } } return View(model); } [Route("Roles/Edit/{id}")] public async Task<IActionResult> EditRole(string id) { ViewBag.IsRoleEditable = await CheckRoleIsEditable(id); var role = await _roleManager.FindByIdAsync(id); RoleViewModel model = new RoleViewModel { Id = role.Id, Name = role.Name }; return View(model); } [Route("Roles/Edit/{id}")] [HttpPost] public async Task<IActionResult> EditRole(RoleViewModel model) { if (ModelState.IsValid) { bool isRoleEditable = await CheckRoleIsEditable(model.Id); if (!isRoleEditable) { ModelState.AddModelError(string.Empty, "Düzenlenmesine izin verilmeyen bir role işlem yapamazsınız!"); ViewBag.IsRoleEditable = isRoleEditable; return View(model); } var updatedRole = await _roleManager.FindByIdAsync(model.Id); updatedRole.Name = model.Name; updatedRole.NormalizedName = model.Name.ToUpperInvariant(); var update = await _roleManager.UpdateAsync(updatedRole); if (update.Succeeded) { return RedirectToAction("Roles", "Manage"); } } ViewBag.IsRoleEditable = true; ModelState.AddModelError(string.Empty, "Eyvah! Bir hata oluştu.."); return View(model); } [Route("Roles/Delete/{id}")] public async Task<IActionResult> DeleteRole(string id) { var role = await _roleManager.FindByIdAsync(id); ViewBag.ErrorMessage = string.Empty; // Herhangi bir kullanici bu role sahip mi veya bu bir sistem rolümü kontrol et bool isEditableRole = await CheckRoleIsEditable(id); if (!isEditableRole) { // hata mesajini ilet ViewBag.ErrorMessage = "Bu bir sistem rolüdür silinemez"; } else { var usersInThisRole = await _userManager.GetUsersInRoleAsync(role.Name); if (usersInThisRole.Any()) { // hata mesajini ilet string[] usersHas = usersInThisRole.Select(x => x.UserName).ToArray(); var usersInThisRoleCommaSeperated = string.Join(", ", usersHas); ViewBag.ErrorMessage = $"Bu role sahip kullanicilar var: {usersInThisRoleCommaSeperated}"; } } // silinecek rolü roleManager'dan model değişkenine ata ve return View(model) yap var model = new RoleViewModel { Id = role.Id, Name = role.Name }; return View(model); } [HttpPost] [Route("Roles/Delete/{id}")] public async Task<IActionResult> DeleteRole(string id, RoleViewModel model) { // Herhangi bir kullanici bu role sahip mi veya bu bir sistem rolümü kontrol et var role = await _roleManager.FindByIdAsync(model.Id); model.Name = role.Name; ViewBag.ErrorMessage = string.Empty; bool hasError = false; bool isEditableRole = await CheckRoleIsEditable(id); if (!isEditableRole) { // hata mesajini ilet ViewBag.ErrorMessage = "Bu bir sistem rolüdür silinemez"; hasError = true; } else { var usersInThisRole = await _userManager.GetUsersInRoleAsync(role.Name); if (usersInThisRole.Any()) { // hata mesajini ilet string[] usersHas = usersInThisRole.Select(x => x.UserName).ToArray(); var usersInThisRoleCommaSeperated = string.Join(", ", usersHas); ViewBag.ErrorMessage = $"Bu role sahip kullanicilar var: {usersInThisRoleCommaSeperated}"; hasError = true; } } if (!hasError) { // rolü sil var result = await _roleManager.DeleteAsync(role); if (result.Succeeded) { // başarılıysa rol listesine gönder return RedirectToAction("Roles"); } ModelState.AddModelError(string.Empty, "Bir hata oluştu tekrar deneyin"); } return View(model); } [HttpGet] [Route("Roles/Assign/{userId}")] public IActionResult AssignRole(string userId) { List<SelectListItem> roleList = _roleManager.Roles .Select(x => new SelectListItem { Value = x.Id, Text = x.Name, Selected = false }).ToList(); AssignRoleViewModel model = new AssignRoleViewModel { UserId = userId, RoleList = roleList }; return View(model); } [HttpPost] [Route("Roles/Assign/{userId}")] public async Task<IActionResult> AssignRole(AssignRoleViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByIdAsync(model.UserId); var role = await _roleManager.FindByIdAsync(model.RoleId); var assignRole = await _userManager.AddToRoleAsync(user, role.Name); if (assignRole.Succeeded) { return RedirectToAction("Index"); } else { ModelState.AddModelError(string.Empty, "Kayıt esnasında bir hata oluştu!"); var roleAssignationErrors = assignRole.Errors.Select(x => x.Description); ModelState.AddModelError(string.Empty, string.Join(", ", roleAssignationErrors)); } } return View(model); } [Route("Roles/Revoke/{userId}")] public async Task<IActionResult> RevokeRole(string userId) { AssignRoleViewModel model = new AssignRoleViewModel(); model.UserId = userId; var user = await _userManager.FindByIdAsync(userId); var userRolesStrList = await _userManager.GetRolesAsync(user); if (userRolesStrList.Any()) { var userRoles = _roleManager.Roles.Where(x => userRolesStrList.Contains(x.Name)).ToList(); model.RoleList = userRoles.Select(x => new SelectListItem { Selected = false, Text = x.Name, Value = x.Id }).ToList(); } else { model.RoleList = new List<SelectListItem>(); } return View(model); } [HttpPost] [Route("Roles/Revoke/{userId}")] public async Task<IActionResult> RevokeRole(AssignRoleViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByIdAsync(model.UserId); var role = await _roleManager.FindByIdAsync(model.RoleId); var result = await _userManager.RemoveFromRoleAsync(user, role.Name); if (result.Succeeded) { return RedirectToAction("UserDetail", new { userId = model.UserId }); } ModelState.AddModelError(string.Empty, "Bir hata oluştu, lütfen tekrar deneyiniz!"); } return View(model); } // Role detayi // Rolun adi ve idsi // ViewBag.UsersInRole icinde bu role sahip olan kullanicilar [Route("Roles/{roleId}")] public async Task<IActionResult> RoleDetail(string roleId) { // bu id'ye ait rol var mi onu kontrol et var role = await _roleManager.FindByIdAsync(roleId); if (role == null) { return RedirectToAction("Error", "Home"); } // varsa rolu alalim // RoleViewModele donusturelim RoleViewModel model = new RoleViewModel { Id = role.Id, Name = role.Name }; // Bu role sahip kullanicilar var mi kontrol edelim var usersInRole = await _userManager.GetUsersInRoleAsync(role.Name); // varsayılan olarak ViewBag.UsersInRole icerisine "bu role sahip bir kullanici yok" mesaji yerlestirecegiz ViewBag.UsersInRole = "Bu role sahip herhangi bir kullanici bulunamadi!"; // varsa ViewBag.UsersInRole string.Join ile atacagiz if (usersInRole.Any()) { string[] usersArr = usersInRole.Select(x => x.UserName).ToArray(); string usersMsg = string.Join(", ", usersArr); ViewBag.UsersInRole = "Bu role sahip kullanicilar: " + usersMsg; } return View(model); } private async Task<bool> CheckRoleIsEditable(string roleId) { var role = await _roleManager.FindByIdAsync(roleId); return !Enum.GetNames(typeof(SystemRoles)).Contains(role.Name); } } }
namespace SoftUniStore.Client.Api { using System.Text; using Common.Constants; using Common.Providers; public class HtmlBuilder { public static string GetHtmlTemplate(string content) { StringBuilder sb = new StringBuilder(); sb.Append(HtmlsProvider.htmls[HtmlNames.Header]); sb.Append(content); sb.Append(HtmlsProvider.htmls[HtmlNames.Footer]); return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MyForum.Web.Models.Categories { public class CategoriesListAllViewModel { public List<CategoriesAllViewModel> Categories { get; set; } } }
using Alabo.Domains.Services; using MongoDB.Bson; namespace Alabo.Industry.Shop.Orders.Dtos { public interface IDeliverService : IService<Deliver, ObjectId> { } }
using System; using System.Linq; class MaximalSum { static void Main() { string[] str = Console.ReadLine().Split(); int iRow = int.Parse(str[0]); int iCol = int.Parse(str[1]); int newRows = 3; int newCols = 3; int[,] matrix = new int[iRow + 1, iCol + 1]; for (int i = 0; i < iRow; i++) { int[] numbers = Console.ReadLine() .Trim() .Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries) .Select(s => int.Parse(s)) .ToArray(); for (int l = 0; l < iCol; l++) { matrix[i, l] = numbers[l]; } } int maxSum = 0; int startRow = 0; int startCol = 0; for (int row = 0; row < matrix.GetLength(0) - (newRows - 1); row++) { for (int col = 0; col < matrix.GetLength(1) - (newCols - 1); col++) { int sum = 0; for (int tempRow = row; tempRow < row + newRows; tempRow++) { for (int tempCol = col; tempCol < col + newCols; tempCol++) { sum += matrix[tempRow, tempCol]; } } if (sum > maxSum) { maxSum = sum; startRow = row; startCol = col; } } } Console.WriteLine("Sum = {0}", maxSum); for (int row = startRow; row < startRow + newRows; row++) { for (int col = startCol; col < startCol + newCols; col++) { Console.Write("{0,-4}", matrix[row, col]); } Console.WriteLine(); } } }
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Description; using System.Web.Http.ModelBinding; using SignInCheckIn.Models; using SignInCheckIn.Services.Interfaces; //using Crossroads.ApiVersioning; namespace SignInCheckIn.Controllers { [RoutePrefix("api")] public class HelloWorldController : ApiController { private readonly IHelloWorldService _helloWorldService; public HelloWorldController(IHelloWorldService helloWorldService) { _helloWorldService = helloWorldService; } [HttpPost] [ResponseType(typeof(HelloWorldOutputDto))] //[VersionedRoute(template: "hello/greet", minimumVersion: "1.0.0", maximumVersion: "2.0.0", deprecated: true)] [Route("hello/greet")] public IHttpActionResult Greet([FromBody] HelloWorldInputDto input) { if (input == null) { ModelState.Add(new KeyValuePair<string, ModelState>("input", new ModelState())); ModelState["input"].Errors.Add("input cannot be null"); } if (!ModelState.IsValid) { return BadRequest(ModelState); } return Ok(_helloWorldService.Greet(input)); } [HttpPost] [ResponseType(typeof(HelloWorldOutputDto))] //[VersionedRoute("hello/greet", "2.0.0")] public IHttpActionResult Greet([FromBody] HelloWorldV2InputDto input) { if (input == null) { ModelState.Add(new KeyValuePair<string, ModelState>("input", new ModelState())); ModelState["input"].Errors.Add("input cannot be null"); } else { if (string.IsNullOrWhiteSpace(input.FirstName)) { ModelState.Add(new KeyValuePair<string, ModelState>("input.FirstName", new ModelState())); ModelState["input.FirstName"].Errors.Add("FirstName is required"); } if (string.IsNullOrWhiteSpace(input.LastName)) { ModelState.Add(new KeyValuePair<string, ModelState>("input.LastName", new ModelState())); ModelState["input.LastName"].Errors.Add("LastName is required"); } } if (!ModelState.IsValid) { return BadRequest(ModelState); } return Ok(_helloWorldService.Greet(input)); } } }
namespace BuildingGame { class Item { ItemType type; int amount; public enum ItemType { Holz, Stein, Werkzeug }; public Item(ItemType type, int amount) { this.type = type; this.amount = amount; } public string GetName() { if (Type == ItemType.Holz) return "Holz"; if (Type == ItemType.Stein) return "Stein"; return "NaN"; } public ItemType Type { get { return type; } set { type = value; } } public int Amount { get { return amount; } set { amount = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; namespace Balloon_Cup { class CardSlot : CardShape { /// <summary> /// A slot's position above or below the tile /// </summary> public enum Position { Above, Below, Middle } /// <summary> /// The slot's position above or below the tile /// </summary> public Position SlotPosition; /// <summary> /// The card currently occupying the slot /// </summary> public Card CurrentCard { get; protected set; } /// <summary> /// The tile that this cardslot belongs to /// </summary> public Tile OwnerTile; /// <summary> /// True if this slot is empty /// </summary> public bool Empty { get { return (CurrentCard == null)? true : false; } } /// <summary> /// Creates a new cardslot /// </summary> /// <param name="ownerTile">The tile that this cardslot belongs to</param> /// <param name="x">The x position of the cardslot</param> /// <param name="y">The y position of the cardslot</param> /// <param name="slotPos">The cardslot's position above or below the tile</param> public CardSlot(Tile ownerTile, int x, int y, Position slotPos) : base(x, y) { OwnerTile = ownerTile; SlotPosition = slotPos; } /// <summary> /// Draws the card slot at its position /// </summary> /// <param name="g">The graphics object to draw the cardslot on</param> public override void Draw(Graphics g) { if (CurrentCard == null) g.DrawRectangle(Pens.Black, _rekt); else CurrentCard.Draw(g); } /// <summary> /// Sets this cardslot's current card /// </summary> /// <param name="c">The card to place in this cardslot</param> public void SetCard(Card c) { CurrentCard = c; CurrentCard.Move(this.X, this.Y); } /// <summary> /// Empties this cardslot of its current card /// </summary> public void EmptySlot() { CurrentCard = null; } /// <summary> /// Prints out this cardslots position relative to a tile /// </summary> /// <returns>This cardslots position relative to a tile</returns> public override string ToString() { return "CardSlot " + SlotPosition.ToString() + " " + OwnerTile; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; [RequireComponent(typeof(VoxelRenderer))] public class World : MonoBehaviour { public GameObject pfMineralVoxel; public GameObject pfFactory; public GameObject pfDriller; public int maxPickables = 100; public int maxRobots = 20; public Vector3 gravity = new Vector3(0,-9.81f,0); VoxelEngine.World voxels; public VoxelEngine.World Voxels { get { return voxels; } set { voxels = value; GetComponent<VoxelRenderer>().SetWorld(value); } } List<Entity> entities = new List<Entity>(); public IEnumerable<Robot> FindRobots() { return entities .Select(e => e.robot) .Where(r => r != null); } public IEnumerable<Entity> FindTopObjects(Vector3 pos, float r) { foreach(var x in entities) { if((x.transform.position - pos).magnitude >= r) { continue; } if(!x.falling && !x.pickable && !Voxels.IsTopVoxelOrHigher(x.transform.position.ToInt3())) { continue; } yield return x; } } public IEnumerable<Entity> FindTopObjects() { foreach(var x in entities) { if(!x.falling && !x.pickable && !Voxels.IsTopVoxelOrHigher(x.transform.position.ToInt3())) { continue; } yield return x; } } public WorldGroup WorldGroup { get; set; } public GameObject Building { get; private set; } public ResourceDropoff ResourceDropoff { get; private set; } public void BuildFactory() { PlaceBuilding(pfFactory); } public void BuildDriller() { PlaceBuilding(pfDriller); } void PlaceBuilding(GameObject pf) { if(Building) { return; } Building = (GameObject)Instantiate(pf); ResourceDropoff = Building.GetComponent<ResourceDropoff>(); int h = Voxels.GetTopVoxelHeight(Int3.Zero); Building.transform.parent = this.transform; Building.transform.localPosition = new Vector3(0,h+1,0); Add(Building.GetComponent<Entity>()); } bool _allowProduction; bool _allowProductionMaxNotReached = true; public bool AllowProduction { get { return _allowProduction && _allowProductionMaxNotReached; } set { _allowProduction = true; } } bool _allowMining; bool _allowMiningMaxNotReached = true; public bool AllowMining { get { return _allowMining && _allowMiningMaxNotReached; } set { _allowMining = true; } } public bool AllowHarvesting { get; set; } public void Add(Entity wi) { wi.world = this; entities.Add(wi); UpdateAllowMiningMaxNotReached(); } public void Remove(Entity wi) { entities.Remove(wi); wi.world = null; UpdateAllowMiningMaxNotReached(); } void UpdateAllowMiningMaxNotReached() { int curr1 = entities.Select(x => x.pickable).Where(x => x != null).Count(); _allowMiningMaxNotReached = (curr1 <= maxPickables); int curr2 = entities.Select(x => x.robot).Where(x => x != null && x.entity.Team == WorldGroup.Team).Count(); _allowProductionMaxNotReached = (curr2 <= maxRobots); } public void DestroyVoxel(Int3 v) { if(Voxels.Get(v).solid == VoxelEngine.Voxel.Solidness.Ultra) { return; } Voxels.Set(v, VoxelEngine.Voxel.Empty); // place mineral for voxel below GameObject go = (GameObject)Instantiate(pfMineralVoxel); go.transform.parent = this.transform; go.transform.localPosition = (v - Int3.Z).ToVector3() + new Vector3(0.5f,0.5f,0.5f); Add(go.GetComponent<Entity>()); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
using Common.Business; using Common.Extensions; using Common.Log; using Entity; using LFP.Common.DataAccess; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; namespace AsyncClasses.Mappers { public static class MPDRowMapper { #region Private Fields private static string mSCCPath = String.Empty; #endregion #region Public Methods public static DataRow MapMPDData(this DataRow row, DataRow input, DateTime scheduleDate, DataColumnCollection columns, string connectionString, string userName, int clipCompId, int previewRId, bool fldf = false) { DataAccess dataAccess = new DataAccess(connectionString, userName); Logging.ConnectionString = @"Data Source=NBISQL2K8\NBISQL2K8;Initial Catalog=movie_rebuild_a_don;Integrated Security=True;Min Pool Size=0;Max Pool Size=100;Connect Timeout=360;Load Balance Timeout=0"; string monthlyProdFolder = @"\\nfmsanshare1\Monthly_Production\Schedules_Adult\"; string sccFolder = @"\\nas-evs4\SCC_SRT\"; bool hasCompCC1 = false; bool hasCompCC2 = false; try { int id = Convert.ToInt32(input["id"]); string channel = input["channel"].ToString(); string compType = GetCompType(connectionString, id); int altHDId = dataAccess.GetAltHDId(id); if (altHDId == 0) altHDId = id; string type = input["type"].ToString(); string billingId = ""; if (!String.IsNullOrEmpty(row["billing_id_str"].ToString())) billingId = row["billing_id_str"].ToString().Trim(); else { if (row["billing_id_int"].GetType() != typeof(DBNull)) { int idInt = Convert.ToInt32(row["billing_id_int"]); if (idInt > 0) billingId = idInt.ToString(); } } bool isPreview = type.Contains("Preview"); int altSDHDId = dataAccess.GetAltHDId(id); Tuple<string, string> structure = GetStructures(id, connectionString); string structure1 = structure.Item1; string structure2 = structure.Item2; int clipId = 0; List<int> clipIds = CommonMapping.GetClipIds(id, connectionString); if (fldf) clipId = clipIds[0]; List<string> clipTypes = new List<string>(4); List<int> altClipIds = new List<int>(4); string[] clipStatuses = new string[4]; foreach (int clip in clipIds) { clipTypes.Add(dataAccess.GetAssetType(clip)); altClipIds.Add(dataAccess.GetAltSDHDId(clip)); } bool useMainIdForConformingStatus = true; string[] structures = { "Double-Feature", "Multiple Asset", "4 Pack" }; if (type.Equals("Short Clip Comp") || (type.Equals("Clip Comp") && (structures.Contains(structure1) || structures.Contains(structure2)))) useMainIdForConformingStatus = false; if (useMainIdForConformingStatus) { for (int i = 0; i < 3; i++) { clipIds[i] = 0; altClipIds[i] = 0; } } string conformStatus = ""; string foreignBrand = ""; string product = ""; List<ScheduleVODHistory> vodHistory = GetVODHistory(connectionString, id, channel, scheduleDate); if (vodHistory.Count > 0) { ScheduleVODHistory history = vodHistory[0]; foreignBrand = history.Category_1; if (!String.IsNullOrEmpty(history.Category_1_With_ID.Trim())) foreignBrand = history.Category_1_With_ID; product = history.Product; if (channel.Equals("VOD OTHER Cablevision Standard XXX") || channel.Equals("VOD OTHER Cablevision Standard XXX HD")) product = history.Category_2; if (channel.Equals("VOD TVN TW Adult XX") || channel.Equals("VOD TVN TW Adult XX+")) product = GetCategories(connectionString, id, channel, scheduleDate); product = GetProduct(channel, product); } MSProd record = GetRecord(connectionString, id, scheduleDate, channel); foreach (DataColumn column in columns) { string name = column.ColumnName; switch (name) { case "ID": row[name] = id; break; case "Alt. HD/SD ID": row[name] = altSDHDId; break; case "Aspect Ratio": row[name] = CommonMapping.GetAspectRatio(altHDId, connectionString); break; case "Asset ID From XML": row[name] = GetAssetIdFromXml(connectionString, id, channel, scheduleDate); break; case "Billing ID": row[name] = billingId; break; case "Broadcast Title": row[name] = CommonMapping.GetBroadcastTitle("", id, connectionString, true); break; case "Channel": row[name] = channel; break; case "Country Code": row[name] = GetCountryCode(connectionString, channel); break; case "Channel ID": row[name] = GetChannelId(connectionString, channel); break; case "Comp Type": row[name] = compType; break; case "Comp ID 1": if (clipIds[0] > 0) row[name] = clipIds[0]; break; case "Comp ID 2": if (clipIds[1] > 0) row[name] = clipIds[1]; break; case "Comp ID 3": if (clipIds[2] > 0) row[name] = clipIds[2]; break; case "Comp ID 4": if (clipIds[3] > 0) row[name] = clipIds[3]; break; case "Comp ID 1 Source": if (clipIds[0] > 0) { if (File.Exists(monthlyProdFolder + clipIds[0].ToString().PadLeft(8, '0') + ".mov")) row[name] = clipIds[0].ToString().PadLeft(8, '0'); break; } if (altClipIds[0] > 0) { if (File.Exists(monthlyProdFolder + altClipIds[0].ToString().PadLeft(8, '0') + ".mov")) row[name] = altClipIds[0].ToString().PadLeft(8, '0'); } break; case "Comp ID 2 Source": if (clipIds[1] > 0) { if (File.Exists(monthlyProdFolder + clipIds[1].ToString().PadLeft(8, '0') + ".mov")) row[name] = clipIds[1].ToString().PadLeft(8, '0'); break; } if (altClipIds[1] > 0) { if (File.Exists(monthlyProdFolder + altClipIds[1].ToString().PadLeft(8, '0') + ".mov")) row[name] = altClipIds[1].ToString().PadLeft(8, '0'); } break; case "Comp ID 3 Source": if (clipIds[2] > 0) { if (File.Exists(monthlyProdFolder + clipIds[2].ToString().PadLeft(8, '0') + ".mov")) row[name] = clipIds[2].ToString().PadLeft(8, '0'); break; } if (altClipIds[2] > 0) { if (File.Exists(monthlyProdFolder + altClipIds[2].ToString().PadLeft(8, '0') + ".mov")) row[name] = altClipIds[2].ToString().PadLeft(8, '0'); } break; case "Comp ID 4 Source": if (clipIds[3] > 0) { if (File.Exists(monthlyProdFolder + clipIds[3].ToString().PadLeft(8, '0') + ".mov")) row[name] = clipIds[3].ToString().PadLeft(8, '0'); break; } if (altClipIds[3] > 0) { if (File.Exists(monthlyProdFolder + altClipIds[3].ToString().PadLeft(8, '0') + ".mov")) row[name] = altClipIds[3].ToString().PadLeft(8, '0'); } break; case "Comp SCC 1": if (clipIds[0] > 0) { if (File.Exists(sccFolder + clipIds[0].ToString().PadLeft(8, '0') + ".scc")) { row[name] = "Y"; hasCompCC1 = true; } } break; case "Comp SCC 2": if (clipIds[1] > 0) { if (File.Exists(sccFolder + clipIds[1].ToString().PadLeft(8, '0') + ".scc")) { row[name] = "Y"; hasCompCC2 = true; } } break; case "Comp SCC 3": if (clipIds[2] > 0) { if (File.Exists(sccFolder + clipIds[2].ToString().PadLeft(8, '0') + ".scc")) row[name] = "Y"; } break; case "Comp SCC 4": if (clipIds[3] > 0) { if (File.Exists(sccFolder + clipIds[3].ToString().PadLeft(8, '0') + ".scc")) row[name] = "Y"; } break; case "Conform Status": if (useMainIdForConformingStatus) row[name] = dataAccess.GetStatus(id, type, channel); else { int statusInt = 0; conformStatus = ""; GetConformStatusById(dataAccess, channel, clipIds, clipTypes, ref conformStatus, ref statusInt); row[name] = statusInt.ToString(); } break; case "Contract Title": row[name] = CommonMapping.GetBroadcastTitle("", id, connectionString, true, true); break; case "Delivered": row[name] = "0"; if (record.Delivered.HasValue) { if (record.Delivered.Value == 1 && record.Delivered_Date.HasValue) row[name] = "1|" + record.Delivered_Date.Value.ToString(Constants.DateFormat); } break; case "Delivery Confirmed": row[name] = "0"; if (record.DeliveryConfirmed.HasValue) { if (record.DeliveryConfirmed.Value == 1 && record.DeliveryConfirmed_Date.HasValue) row[name] = "1|" + record.DeliveryConfirmed_Date.Value.ToString(Constants.DateFormat); } break; case "Foreign Brand": row[name] = foreignBrand; break; case "FTP Verified": row[name] = "0"; if (record.FTPVerified.HasValue) { if (record.FTPVerified.Value == 1 && record.FTPVerified_Date.HasValue) row[name] = "1|" + record.FTPVerified_Date.Value.ToString(Constants.DateFormat); } break; case "Header IDs In Order": row[name] = GetHeaderIds(connectionString, id, channel, scheduleDate); break; case "HD": row[name] = "N"; if (input["hd"].GetType() != typeof(DBNull)) { if (Convert.ToInt32(input["hd"]) == 1) row[name] = "Y"; } break; case "ID Source": if (id > 0) { if (File.Exists(monthlyProdFolder + id.ToString().PadLeft(8, '0') + ".mov")) row[name] = id.ToString().PadLeft(8, '0'); break; } if (altSDHDId > 0) { if (File.Exists(monthlyProdFolder + altSDHDId.ToString().PadLeft(8, '0') + ".mov")) row[name] = altSDHDId.ToString().PadLeft(8, '0'); } break; case "Image": if (ImageQCComplete(connectionString, id, scheduleDate)) row[name] = "Y"; if (!ChannelUsesImages(channel)) //The specified channels are always "Y". row[name] = "Y"; break; case "Language QC": if (HasLanguageQC(connectionString, altHDId)) row[name] = "Y"; break; case "License Start": row[name] = input["lic_start"]; break; case "LTO Status": row[name] = CheckLTOStatus(connectionString, id, type, dataAccess); break; case "Mexican Spanish VOD Title": row[name] = dataAccess.GetTitleByLanguage(id, "Mexican Spanish VOD", ""); break; case "MPD Status": int passed = 0; string mpdStatus = ""; if (channel.Contains("Next Door")) { if (String.IsNullOrEmpty(row["Special Source ID"].ToString())) { int sourceId = GetSourceId(connectionString, id); if (sourceId > 0) row["Special Source ID"] = sourceId.ToString().PadLeft(8, '0'); } } else { if (useMainIdForConformingStatus) { mpdStatus = dataAccess.GetStatus(id, type, channel); passed = (mpdStatus.Equals("Air Master Passed") || mpdStatus.Equals("Delivered to MS")) ? 1 : 0; } else { for (int i = 0; i < 4; i++) { if (clipIds[i] > 0) clipStatuses[i] = dataAccess.GetStatus(clipIds[i], clipTypes[i], channel); } passed = 1; for (int i = 0; i < 4; i++) { if (clipIds[i] > 0) { if (!clipStatuses[i].Equals("Air Master Passed") && clipStatuses[i].Equals("Delivered to MS")) passed = 0; } } DoAMPassed(connectionString, id, channel, scheduleDate, dataAccess, record.History, userName, useMainIdForConformingStatus); } } mpdStatus = GetMPDStatus(connectionString, id, channel, scheduleDate); if (String.IsNullOrEmpty(mpdStatus) && passed == 1) row[name] = "Ready for Transcode"; if (mpdStatus.Equals("In Pass 2")) row[name] = "Pass"; if (mpdStatus.Equals("On FTP")) row[name] = "In Delivery"; if (passed == 0) { row[name] = ""; AddUpdateMPDRecord(connectionString, id, channel, scheduleDate, userName, record.History, dataAccess); } break; case "Notes": if (!String.IsNullOrEmpty(GetVODProduction2Notes(connectionString, id, channel, scheduleDate))) row[name] = "Has Notes"; break; case "OFRB #": row[name] = GetOFRBNumber(connectionString, id); break; case "Packaged Date": if (record != null) { if (record.PackagedDate.HasValue & record.PackagedDate.Value == 1) { if (record.PackagedDate_Date.HasValue) row[name] = record.PackagedDate_Date.Value.ToString(Constants.DateFormat); } } break; case "Portuguese VOD Title": row[name] = dataAccess.GetTitleByLanguage(id, "Portuguese VOD", ""); break; case "Product": row[name] = product; break; case "Production Title": row[name] = GetProductionTitle(connectionString, id, false); break; case "Rating": row[name] = GetRating(connectionString, id, dataAccess); break; case "ID SCC": if (IsFLDF(connectionString, id)) { if (clipIds[0] > 0) { string sccFile = clipIds[0].ToString().PadLeft(8, '0') + ".scc"; if (File.Exists(mSCCPath + sccFile)) hasCompCC1 = true; } if (clipIds[1] > 0) { string sccFile = clipIds[1].ToString().PadLeft(8, '0') + ".scc"; if (File.Exists(mSCCPath + sccFile)) hasCompCC2 = true; } if (hasCompCC1 && hasCompCC2) row[name] = "Y"; } else { string sccFile = clipCompId.ToString().PadLeft(8, '0') + ".scc"; if (File.Exists(mSCCPath + sccFile)) row[name] = "Y"; } break; case "Special Source ID": int specialSourceId = GetSourceId(connectionString, id); if (specialSourceId != 0) row[name] = specialSourceId.ToString().PadLeft(8, '0'); break; case "Studio": row[name] = GetStudioCompany(id, connectionString); break; case "Title on Asset": if (!NoTitleOnAsset(connectionString, altHDId)) row[name] = "Y"; break; case "Titles In": string title = CreateTitle(connectionString, channel, id, "Asset_Name", "XML", "Title", "All Types", scheduleDate, dataAccess); if (!String.IsNullOrEmpty(title)) row[name] = "Y"; break; case "Type": row[name] = type; break; case "VOD Title": row[name] = GetProductionTitle(connectionString, id, true); break; case "XML Passed": if (UsesXml(connectionString, channel)) { row[name] = "0"; if (record != null) { if (record.XMLPassed.HasValue && record.XMLPassed.Value == 1) { if (record.XMLPassed_Date.HasValue) row[name] = "1|" + record.XMLPassed_Date.Value.ToString(Constants.DateFormat); } } if (String.IsNullOrEmpty(conformStatus)) { if (useMainIdForConformingStatus) { conformStatus = dataAccess.GetStatus(id, type, channel); if (!conformStatus.Equals("32")) { //Remove the checkbox from the result. row[name] = "AM not passed"; DoXmlReady(row, scheduleDate, connectionString, id, channel); } } else { int statusValue = 0; GetConformStatusById(dataAccess, channel, clipIds, clipTypes, ref conformStatus, ref statusValue); if (statusValue != 32) { //Remove the checkbox from the result. row[name] = "AM not passed"; } } } else { if (!conformStatus.Equals("Air Master Passed")) { //Remove the checkbox from the result. row[name] = "AM not passed"; } } } else row[name] = "N/A"; break; case "XML Ready": DoXmlReady(row, scheduleDate, connectionString, id, channel); break; } } } catch (Exception e) { Logging.Log(e, "AsyncClasses", "Extensions.MapMPDData"); return null; } finally { dataAccess.Dispose(); dataAccess = null; } return row; } #endregion #region Private Methods private static void AddUpdateMPDRecord(string connectionString, int id, string channel, DateTime scheduleDate, string userName, string history, DataAccess da) { MSProd ms = new MSProd(); try { if (!AlreadyHasNotes(connectionString, id, scheduleDate, channel)) { string notes = "MoviesEh "; notes += DateTime.Now.ToString("T") + " " + DateTime.Now.ToString(Constants.DateFormat); notes += " MPD Status - Cleared per Conform Status "; MSProd data = ms.GetMPDRecord(connectionString, id, channel, scheduleDate); if (data == null) { data = new MSProd(); data.ID = id; data.Sched_Date = scheduleDate; data.Channel = channel; data.AM_Passed_At_Start_Of_Month = IsAMPassed(id, connectionString, channel, da); ms.AddUpdateRecord(connectionString, data, true); } data.History = history + notes; data.AM_Passed_At_Start_Of_Month = 0; data.MPDStatus = ""; data.MPDStatus_Username = userName; data.MPDStatus_Date = DateTime.Now; data.Delivered = 0; data.Delivered_Username = userName; data.Delivered_Date = DateTime.Now; data.DeliveryConfirmed = 0; data.DeliveryConfirmed_Username = userName; data.DeliveryConfirmed_Date = DateTime.Now; data.FTPVerified = 0; data.FTPVerified_Username = userName; data.FTPVerified_Date = DateTime.Now; data.PackagedDate = 0; data.PackagedDate_Username = userName; data.PackagedDate_Date = DateTime.Now; data.XMLPassed = 0; data.XMLPassed_Username = userName; data.XMLPassed_Date = DateTime.Now; ms.AddUpdateRecord(connectionString, data, false); } } finally { ms = null; } } private static bool AlreadyHasNotes(string connectionString, int id, DateTime scheduleDate, string channel) { MSProd ms = new MSProd(); try { return ms.AlreadyHasNotes(connectionString, id, channel, scheduleDate); } finally { ms = null; } } private static bool ChannelUsesImages(string channel) { string[] noUse = { "VOD CMC Barely Legal XX+", "VOD CMC Barely Legal XXX", "VOD CMC Cablevision Hustler XXX", "VOD CMC Comcast HIS XX+", "VOD CMC Comcast HIS XX+ HD", "VOD CMC Comcast HIS XXX", "VOD CMC Comcast HIS XXX HD", "VOD CMC Comcast Hustler XX+ HD", "VOD CMC Comcast Hustler XX+ SVOD", "VOD CMC Comcast Hustler XX+ SVOD HD", "VOD CMC Comcast Hustler XXX", "VOD CMC Comcast Hustler XXX HD", "VOD CMC Comcast MRG", "VOD CMC HIS XX+", "VOD CMC HIS XX+ SVOD", "VOD CMC Hustler 4 Packs XX+", "VOD CMC Hustler Free Previews XX+", "VOD CMC Hustler Free Previews XXX", "VOD CMC Hustler Last Chance XX+", "VOD CMC Hustler Shorts XX+", "VOD CMC Hustler X", "VOD CMC Hustler XX+ HD", "VOD CMC Hustler XX+ SVOD", "VOD CMC Hustler XXX HD", "VOD CMC TW Hustler XX+", "VOD HOTEL SONIFI XXX", "VOD Hustler Brazil Xplaneta XXX", "VOD Hustler South Korea Nagen X", "VOD Hustler South Korea Nagen XX+", "VOD Hustler United Kingdom Virgin X", "VOD OTHER Brazil Xplaneta XXX", "VOD OTHER Cablevision Cheap Thrills XXX", "VOD OTHER Cablevision One Off Stunts XXX", "VOD OTHER Cablevision Standard XXX", "VOD OTHER Cablevision Standard XXX HD", "VOD OTHER DISH Hustler XXX", "VOD OTHER DISH Hustler XXX HD", "VOD OTHER DISH XXX HD", "VOD TVN Cheap Thrills XX+ HD", "VOD TVN Girlfriends Films XX+ HD", "VOD TVN Last Chance XX+", "VOD TVN MRG TVMA", "VOD TVN Standard X", "VOD TVN Standard XX+ HD", "VOD TVN Ten XX+ SVOD HD", "VOD TVN TW Manhandle XX+ - SF", "VOD TVN TW Manhandle XX+ SVOD", "VOD TVN TW Penthouse XX+ SVOD", "VOD TVN TW Real XX+ SVOD", "VOD TVN TW Ten XX+ SVOD", "VOD TVN XTSY XX+", "VOD TVN XTSY XX+ HD", "VOD TVN XTSY XX+ SVOD", "VOD TW Hotel Gay XX+", "VOD TW Hotel Standard XX+" }; if (noUse.Contains(channel)) return false; return true; } private static string CheckLTOStatus(string connectionString, int id, string type, DataAccess da) { string result = "Y"; if (type.Equals("Short Clip Comp") || Is4Pack(connectionString, id) || IsDF(connectionString, id) || IsMultipleAsset(connectionString, id)) { List<int> ids = CommonMapping.GetClipIds(id, connectionString); foreach (int clipId in ids) { int altId = da.GetAltHDId(clipId); if (altId == 0) altId = clipId; if (!IsOnTape(connectionString, altId)) { result = ""; break; } } } else { if (!IsOnTape(connectionString, id)) result = ""; } return result; } private static string CreateTitle(string connectionString, string channel, int id, string titleType, string mtpXml, string xmlSection, string assetType, DateTime scheduleDate, DataAccess da) { string result = String.Empty; SystemVODTitleRules vod = new SystemVODTitleRules(); string tempTitle = ""; try { List<SystemVODTitleRules> rules = vod.GetRules(connectionString, channel, titleType, mtpXml, xmlSection, assetType); foreach (SystemVODTitleRules rule in rules) { if (!String.IsNullOrEmpty(rule.Always_Use_This_Title)) { string sql = da.CreateSql(rule.Always_Use_This_Title, id); tempTitle = GetTitle(connectionString, sql); } if (!String.IsNullOrEmpty(rule.Title_Source_1)) tempTitle = GetTempTitle(connectionString, channel, id, scheduleDate, da, tempTitle, rule.Title_Source_1); if (String.IsNullOrEmpty(tempTitle)) { if (!String.IsNullOrEmpty(rule.Title_Source_2)) tempTitle = GetTempTitle(connectionString, channel, id, scheduleDate, da, tempTitle, rule.Title_Source_2); } if (String.IsNullOrEmpty(tempTitle)) { if (!String.IsNullOrEmpty(rule.Title_Source_3)) tempTitle = GetTempTitle(connectionString, channel, id, scheduleDate, da, tempTitle, rule.Title_Source_3); } tempTitle = da.ProcessTitle(tempTitle, rule); } } finally { vod = null; } return result; } private static void DoXmlReady(DataRow row, DateTime scheduleDate, string connectionString, int id, string channel) { if (IsXmlReady(connectionString, id, channel, scheduleDate)) row["XML Ready"] = "Y"; else row["XML Ready"] = "N"; } private static string GetAssetIdFromXml(string connectionString, int id, string channel, DateTime scheduleDate) { ScheduleXml xml = new ScheduleXml(); try { return xml.GetAssetId(connectionString, id, channel, scheduleDate); } finally { xml = null; } } private static string GetCategories(string connectionString, int id, string channel, DateTime scheduleDate) { StringBuilder result = new StringBuilder(); ScheduleCategories categories = new ScheduleCategories(); try { List<Tuple<string, string>> list = categories.GetCategories(connectionString, id, channel, scheduleDate); foreach (Tuple<string, string> item in list) { if (item.Item1.Contains("(")) result.Append(item.Item1.Substring(item.Item1.IndexOf("(") - 1)); else result.Append(item.Item1); result.AppendLine(": " + item.Item2); } } finally { categories = null; } return result.ToString().Replace("\n", "").Remove(result.ToString().LastIndexOf(" ")); } private static int GetChannelId(string connectionString, string channel) { SystemStations station = new SystemStations(); try { return station.GetChannelId(connectionString, channel); } finally { station = null; } } private static string GetCompType(string connectionString, int id) { string result = "N"; Movie movie = new Movie(); try { Tuple<string, int, string, string> tuple = movie.GetCompType(connectionString, id); if (tuple == null) return result; if (tuple.Item1.Contains("Comp")) { if (tuple.Item1.Equals("Short Clip Comp")) result = "Short CC"; if (tuple.Item3.Equals("Double-Feature") || tuple.Item4.Equals("Double-Feature")) result = "DF"; if (tuple.Item2 == 1) result = "FL DF"; } if (tuple.Item3.Equals("Multiple Asset") || tuple.Item4.Equals("Multiple Asset") || tuple.Item3.Equals("4 Pack") || tuple.Item4.Equals("4 Pack")) result = "Multiple Asset"; } finally { movie = null; } return result; } private static void DoAMPassed(string connectionString, int id, string channel, DateTime scheduleDate, DataAccess da, string history, string userName, bool useMainId) { MSProd data = GetRecord(connectionString, id, scheduleDate, channel); MSProd ms = new MSProd(); try { int? amPassed = IsAMPassed(id, connectionString, channel, da); if (data == null) { data = new MSProd(); data.ID = id; data.Sched_Date = scheduleDate; data.Channel = channel; data.AM_Passed_At_Start_Of_Month = amPassed; ms.AddUpdateRecord(connectionString, data, true); } //If AM was passed at the beginning of the month, check if it was set to not passed afterward. if (!data.AM_Passed_At_Start_Of_Month.HasValue || data.AM_Passed_At_Start_Of_Month.Value == 1) { int? passed = IsAMPassed(id, connectionString, channel, da); if (passed.HasValue && passed.Value == 0) { if (!AlreadyHasNotes(connectionString, id, scheduleDate, channel)) { string notes = "MoviesEh "; notes += DateTime.Now.ToString("T") + " " + DateTime.Now.ToString(Constants.DateFormat); notes += " MPD Status - Cleared per Conform Status "; data.History = history + notes; data.AM_Passed_At_Start_Of_Month = 0; data.MPDStatus = ""; data.MPDStatus_Username = userName; data.MPDStatus_Date = DateTime.Now; data.Delivered = 0; data.Delivered_Username = userName; data.Delivered_Date = DateTime.Now; data.DeliveryConfirmed = 0; data.DeliveryConfirmed_Username = userName; data.DeliveryConfirmed_Date = DateTime.Now; data.FTPVerified = 0; data.FTPVerified_Username = userName; data.FTPVerified_Date = DateTime.Now; data.PackagedDate = 0; data.PackagedDate_Username = userName; data.PackagedDate_Date = DateTime.Now; data.XMLPassed = 0; data.XMLPassed_Username = userName; data.XMLPassed_Date = DateTime.Now; ms.AddUpdateRecord(connectionString, data, false); } } } if (!useMainId) { int? passed = IsAMPassed(id, connectionString, channel, da); if (passed.HasValue && passed.Value == 0) { if (!AlreadyHasNotes(connectionString, id, scheduleDate, channel)) { string notes = "MoviesEh "; notes += DateTime.Now.ToString("T") + " " + DateTime.Now.ToString(Constants.DateFormat); notes += " MPD Status - Cleared per Conform Status "; data.History = history + notes; data.AM_Passed_At_Start_Of_Month = 0; data.MPDStatus = ""; data.MPDStatus_Username = userName; data.MPDStatus_Date = DateTime.Now; ms.AddUpdateRecord(connectionString, data, false); } } } else { if (amPassed.HasValue && amPassed.Value == 0) { if (!AlreadyHasNotes(connectionString, id, scheduleDate, channel)) { string notes = "MoviesEh "; notes += DateTime.Now.ToString("T") + " " + DateTime.Now.ToString(Constants.DateFormat); notes += " MPD Status - Cleared per Conform Status "; data.History = history + notes; data.AM_Passed_At_Start_Of_Month = 0; data.MPDStatus = ""; data.MPDStatus_Username = userName; data.MPDStatus_Date = DateTime.Now; ms.AddUpdateRecord(connectionString, data, false); } } } } finally { ms = null; } } private static void GetConformStatusById(DataAccess dataAccess, string channel, List<int> clipIds, List<string> clipTypes, ref string conformStatus, ref int statusInt) { if (clipIds[0] > 0) { conformStatus = dataAccess.GetStatus(clipIds[0], clipTypes[0], channel); if (conformStatus.Trim() == "") conformStatus = "0"; statusInt = Convert.ToInt32(conformStatus); } if (clipIds[1] > 0) { conformStatus = dataAccess.GetStatus(clipIds[1], clipTypes[1], channel); if (conformStatus.Trim() == "") conformStatus = "0"; if (Convert.ToInt32(conformStatus) < statusInt) statusInt = Convert.ToInt32(conformStatus); } if (clipIds[2] > 0) { conformStatus = dataAccess.GetStatus(clipIds[2], clipTypes[2], channel); if (conformStatus.Trim() == "") conformStatus = "0"; if (Convert.ToInt32(conformStatus) < statusInt) statusInt = Convert.ToInt32(conformStatus); } if (clipIds[3] > 0) { conformStatus = dataAccess.GetStatus(clipIds[3], clipTypes[3], channel); if (conformStatus.Trim() == "") conformStatus = "0"; if (Convert.ToInt32(conformStatus) < statusInt) statusInt = Convert.ToInt32(conformStatus); } } private static string GetCountryCode(string connectionString, string channel) { SystemStations station = new SystemStations(); try { return station.GetCountryCodeByChannel(connectionString, channel); } finally { station = null; } } /// <summary> /// Gets the header IDs for the requested asset, channel, and schedule date. /// </summary> /// <param name="id">The asset ID.</param> /// <param name="channel">The channel.</param> /// <param name="scheduleDate">The schedule date.</param> /// <returns>The header IDs, as a comma-delimited string.</returns> private static string GetHeaderIds(string connectionString, int id, string channel, DateTime scheduleDate) { ScheduleHeaderIDs headers = new ScheduleHeaderIDs(); try { return headers.GetHeaderIds(connectionString, id, channel, scheduleDate); } finally { headers = null; } } private static string GetMPDStatus(string connectionString, int id, string channel, DateTime scheduleDate) { MSProd ms = new MSProd(); try { return ms.GetMPDStatus(connectionString, id, channel, scheduleDate); } finally { ms = null; } } private static string GetOFRBNumber(string connectionString, int id) { Movie movie = new Movie(); try { return movie.GetOFRBNumber(connectionString, id); } finally { movie = null; } } private static string GetProduct(string channel, string product) { //Use either these hard-coded headers or the product in the history table (product). switch (channel) { case "VOD OTHER TW Oceanic Mo Bettah XX+": case "VOD TVN See My Sex Tapes XX+": case "VOD TVN See My Sex Tapes XX": case "VOD TVN See My Sex Tapes XX H264": product = "SMST HDR"; break; case "VOD TVN XTSY XX": case "VOD TVN XTSY XX+": case "VOD TVN XTSY XX+ CCDN": product = "XTSY HDR"; break; case "VOD CMC Comcast MRG": case "VOD CMC Insight MRG": case "VOD GDMX Time Warner - Movies MRG": case "VOD GDMX Time Warner - Events MRG": case "VOD iNDEMAND Charter MRG": product = ""; break; case "VOD OTHER Cablevision": case "VOD OTHER Cablevision Cheap Thrills XXX": case "VOD OTHER TW Oceanic Cheap Thrills XX": case "VOD TVN Cheap Thrills Adult Stunt XX+": case "VOD TVN Cheap Thrills XX+": case "VOD TVN TW Adult XX - SF": case "VOD TVN TW Cheap Thrills XX+": product = "Cheap Thrills HDR"; break; case "VOD TVN Juicy XX": case "VOD TVN Juicy XX+": case "VOD TVN Juicy XX+ HD": case "VOD TVN Juicy XX+ CCDN": case "VOD TVN Juicy XXX": case "VOD TVN Comcast Juicy XX+": case "VOD TVN Comcast Juicy XXX": product = "Juicy HDR"; break; case "VOD TVN Standard X": case "VOD TVN TEN XX HD": case "VOD TVN Standard XX+ CCDN": case "VOD TVN TW Ten XX+ SVOD": product = "Standard HDR"; break; case "VOD TVN Gay XX": case "VOD TVN Gay XXX": case "VOD TW Hotel Gay X": case "VOD TVN TW Manhandle XX SVOD": case "VOD TVN TW Manhandle XX - SF": case "VOD TVN TW Manhandle XX+ SVOD": case "VOD TVN TW Manhandle XX+ - SF": case "VOD TVN Manhandle XXX": product = "Gay HDR"; break; case "VOD TVN TW Penthouse XX+ SVOD": product = "Penthouse HDR"; break; case "VOD TVN Comcast Penthouse XX+": case "VOD TVN Comcast Penthouse XXX": case "VOD TVN Penthouse XX": case "VOD TVN Penthouse XX HD": case "VOD TVN Penthouse XX+": case "VOD TVN Penthouse XX+ CCDN": case "VOD TVN Penthouse XX+ HD": case "VOD TVN Penthouse XXX": product = "Penthouse HDR"; break; case "VOD TVN Kinky XX+": product = "Kinky HDR"; break; case "VOD TVN TW Real XX+ SVOD": product = "Real HDR"; break; case "VOD TVN Comcast Standard XX+": case "VOD TVN Comcast Standard XXX": case "VOD TVN Standard XX": case "VOD TVN Standard XX H264": case "VOD TVN Standard XX+": case "VOD TVN Standard XXX": case "VOD TW Hotel Standard XX": case "VOD TW Hotel Standard XX+": case "VOD OTHER Cablevision Standard XXX": case "VOD OTHER Cablevision Standard XXX HD": case "VOD TVN TW Adult XX": case "VOD TVN TW Adult XX+": default: break; } return product; } private static string GetProductionTitle(string connectionString, int id, bool vod) { string result = String.Empty; Movie movie = new Movie(); try { using (DataTable dt = movie.GetProductionTitlesStructures(connectionString, id)) { if (dt.HasRows()) { result = dt.Rows[0]["title_production"].ToString(); if (vod) result = dt.Rows[0]["title_vod"].ToString(); } } } finally { movie = null; } return result; } private static string GetRating(string connectionString, int id, DataAccess da) { string result = String.Empty; Movie movie = new Movie(); try { int xxx = movie.GetRating(connectionString, id); result = da.GetXXX(xxx); } finally { movie = null; } return result; } private static MSProd GetRecord(string connectionString, int id, DateTime scheduleDate, string channel) { MSProd ms = new MSProd(); try { return ms.GetMPDRecord(connectionString, id, channel, scheduleDate); } finally { ms = null; } } private static int GetSourceId(string connectionString, int id) { Movie movie = new Movie(); try { return movie.GetSourceId(connectionString, id); } finally { movie = null; } } private static Tuple<string, string> GetStructures(int id, string connectionString) { Movie movie = new Movie(); try { return movie.GetStructure(connectionString, id); } finally { movie = null; } } private static string GetStudioCompany(int id, string connectionString) { Studio studio = new Studio(); try { return studio.GetCompanyByMovie(connectionString, id); } finally { studio = null; } } private static string GetStuntName(string connectionString, int id, string channel, DateTime scheduleDate) { Schedule schedule = new Schedule(); try { return schedule.GetStuntName(connectionString, id, channel, scheduleDate); } finally { schedule = null; } } private static string GetTempTitle(string connectionString, string channel, int id, DateTime scheduleDate, DataAccess da, string tempTitle, string type) { switch (type) { case "Broadcast": tempTitle = da.GetProperTitleBroadcast(id, channel); break; case "Broadcast 2 (if selected)": tempTitle = da.GetSpecificTitleIfSelected(id, "Broadcast Title 2", channel); break; case "Broadcast 3 (if selected)": tempTitle = da.GetSpecificTitleIfSelected(id, "Broadcast Title 3", channel); break; case "VOD": tempTitle = da.GetProperVODTitle(id, channel); break; case "VOD 2 (if selected)": tempTitle = da.GetSpecificTitleIfSelected(id, "VOD Title 2", channel); break; case "VOD 3 (if selected)": tempTitle = da.GetSpecificTitleIfSelected(id, "VOD Title 3", channel); break; case "HD": tempTitle = da.GetProperHDTitle(id, channel); break; case "HD 3 (if selected)": tempTitle = da.GetSpecificTitleIfSelected(id, "HD Title 3", channel); break; case "StuntName": tempTitle = GetStuntName(connectionString, id, channel, scheduleDate); break; case "INT VOD English 1": tempTitle = GetTitleByType(connectionString, "Title_INT_VOD", id); break; case "Series": tempTitle = GetTitleByType(connectionString, "Title_Series", id); break; case "Internet": tempTitle = GetTitleByType(connectionString, "Title_Internet", id); break; default: tempTitle = type; if (!String.IsNullOrEmpty(tempTitle)) { string sql = da.CreateSql(type, id, true); tempTitle = GetTitle(connectionString, sql); } break; } return tempTitle; } private static string GetTitle(string connectionString, string sql) { Movie movie = new Movie(); try { return movie.GetTitle(connectionString, sql); } finally { movie = null; } } private static string GetTitleByType(string connectionString, string type, int id) { Movie movie = new Movie(); try { return movie.GetTitleByType(connectionString, type, id); } finally { movie = null; } } private static List<ScheduleVODHistory> GetVODHistory(string connectionString, int id, string channel, DateTime scheduleDate) { ScheduleVODHistory history = new ScheduleVODHistory(); try { return history.GetHistory(connectionString, id, channel, scheduleDate); } finally { history = null; } } private static string GetVODProduction2Notes(string connectionString, int id, string channel, DateTime scheduleDate) { VODProduction2Notes notes = new VODProduction2Notes(); try { return notes.GetNotes(connectionString, id, channel, scheduleDate); } finally { notes = null; } } private static bool HasLanguageQC(string connectionString, int id) { MovieConform conform = new MovieConform(); try { return conform.HasLanguageQC(connectionString, id); } finally { conform = null; } } private static bool ImageQCComplete(string connectionString, int id, DateTime date) { ImageDashboardStatus image = new ImageDashboardStatus(); try { return image.IsQCComplete(connectionString, id, date); } finally { image = null; } } private static bool Is4Pack(string connectionString, int id) { Movie movie = new Movie(); try { return movie.GetCountByStructure(connectionString, id, "4 Pack") > 0; } finally { movie = null; } } private static int? IsAMPassed(int id, string connectionString, string channel, DataAccess da) { int? result = null; if (channel.Equals("VOD OTHER OTT The Mens Room Unedited HD") || channel.Equals("VOD OTHER OTT Barely Legal Unedited HD")) return 1; int altId = da.GetAltHDId(id); if (altId == 0) altId = id; string status = CommonMapping.GetAMQCStatus(altId, da); if (status.Equals("Passed")) result = 1; return result; } private static bool IsDF(string connectionString, int id) { Movie movie = new Movie(); try { return movie.GetCountByStructure(connectionString, id, "Double-Feature") > 0; } finally { movie = null; } } private static bool IsFLDF(string connectionString, int id) { Movie movie = new Movie(); try { return movie.IsFLDF(connectionString, id); } finally { movie = null; } } private static bool IsMultipleAsset(string connectionString, int id) { Movie movie = new Movie(); try { return movie.GetCountByStructure(connectionString, id, "Multiple Asset") > 0; } finally { movie = null; } } private static bool IsOnTape(string connectionString, int id) { LTO lto = new LTO(); try { string fileName = id.ToString().PadLeft(8, '0') + ".mov"; return lto.IsOnTape(connectionString, fileName); } finally { lto = null; } } private static bool IsXmlReady(string connectionString, int id, string channel, DateTime scheduleDate) { XmlReady xml = new XmlReady(); try { return xml.IsXmlReady(connectionString, id, channel, scheduleDate); } finally { xml = null; } } private static bool NoTitleOnAsset(string connectionString, int id) { TrackS s = new TrackS(); try { return s.HasNoTitleOnAsset(connectionString, id); } finally { s = null; } } private static bool UsesXml(string connectionString, string channel) { SystemStations stations = new SystemStations(); try { return stations.VodProd2UsesXml(connectionString, channel); } finally { stations = null; } } #endregion } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class Admin_Users : System.Web.UI.Page { private DataClassesDataContext db = new DataClassesDataContext(); protected void Page_Load(object sender, EventArgs e) { // man skal have administrations rettigheder for at være på denne side if (Session["role_access"] == null || Convert.ToInt32(Session["role_access"]) < 100) { Response.Redirect("../Login.aspx"); } // præsenter den ønskede del af bruger administrationen, baseret på action i URL switch (Request.QueryString["action"]) { case "add": Panel_Form.Visible = true; GetRoles(); break; case "edit": if (Request.QueryString["user_id"] != null) { Panel_Form.Visible = true; GetItem(Request.QueryString["user_id"]); } break; case "delete": if (Request.QueryString["user_id"] != null) { DeleteItem(Request.QueryString["user_id"]); } break; default: GetItems(); break; } } private void GetItems() { Panel_List.Visible = true; Repeater_List.DataSource = db.dbUsers.OrderByDescending(u => u.dbRole.Access).ToList(); Repeater_List.DataBind(); } private void DeleteItem(string user_id) { dbUser user = db.dbUsers.First(u => u.Id.Equals(user_id)); if (user != null) { db.dbUsers.DeleteOnSubmit(user); db.SubmitChanges(); } Response.Redirect("Users.aspx"); } private void GetItem(string user_id) { if (!IsPostBack) { dbUser user = db.dbUsers.First(u => u.Id.Equals(user_id)); if (user != null) { TextBox_Name.Text = user.Name; TextBox_Email.Text = user.Email; GetRoles(); DropDownList_Role.SelectedValue = user.RoleId.ToString(); } } } private void GetRoles() { if (!IsPostBack) { DropDownList_Role.DataTextField = "Title"; DropDownList_Role.DataValueField = "Id"; DropDownList_Role.DataSource = db.dbRoles.ToList(); DropDownList_Role.DataBind(); DropDownList_Role.Items.Insert(0, new ListItem("Vælg Rolle", "0")); } } protected void Button_Save_Click(object sender, EventArgs e) { switch (Request.QueryString["action"]) { case "add": if (TextBox_Password.Text == "" || TextBox_Password_Repeat.Text == "") { Panel_Error.Visible = true; Label_Error.Text = "Udfyld kodeord"; } else { dbUser newUser = new dbUser(); newUser.Name = TextBox_Name.Text; newUser.Email = TextBox_Email.Text; newUser.Password = Helpers.getHashSha256(TextBox_Password.Text, TextBox_Email.Text); db.dbUsers.InsertOnSubmit(newUser); db.SubmitChanges(); Response.Redirect("Users.aspx"); } break; case "edit": dbUser editUser = db.dbUsers.First(u => u.Id.Equals(Request.QueryString["user_id"])); editUser.Name = TextBox_Name.Text; editUser.Email = TextBox_Email.Text; editUser.RoleId = Convert.ToInt32(DropDownList_Role.SelectedValue); if (TextBox_Password.Text != "" || TextBox_Password_Repeat.Text != "") { editUser.Password = Helpers.getHashSha256(TextBox_Password.Text, TextBox_Email.Text); } db.SubmitChanges(); Response.Redirect("Users.aspx"); break; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /* Write methods to calculate minimum, * maximum, average, sum and product of * given set of integer numbers. Use variable number of arguments. */ class ParamTask { static void TasksWithParam(params int[] array) { int min = 0; int max = 0; long sum = 0; long average = 0; long product = 1; if (array.Length < 1) product = 0; for (int i = 0; i < array.Length; i++) { if (array[i] > max) { max = array[i]; } if (array[i] < min) { min = array[i]; } sum += (long)array[i]; product *= (long)array[i]; } average = (sum / array.Length); Console.WriteLine("Min element: " + min); Console.WriteLine("Max element: " + max); Console.WriteLine("Sum : " + sum); Console.WriteLine("Product: " + product); Console.WriteLine("Average: " + average); } static void Main(string[] args) { TasksWithParam(1, -215, 352, 7, -1124, 16, -3, 12, 42); } }
namespace HeBoGuoShi.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddBuyer : DbMigration { public override void Up() { CreateTable( "dbo.BuyerProducts", c => new { Id = c.Guid(nullable: false, identity: true), UserId = c.String(maxLength: 128), SellerId = c.String(maxLength: 128), OwnerProductId = c.Guid(nullable: false), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.OwnerProducts", t => t.OwnerProductId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.SellerId) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .Index(t => t.UserId) .Index(t => t.SellerId) .Index(t => t.OwnerProductId); } public override void Down() { DropForeignKey("dbo.BuyerProducts", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.BuyerProducts", "SellerId", "dbo.AspNetUsers"); DropForeignKey("dbo.BuyerProducts", "OwnerProductId", "dbo.OwnerProducts"); DropIndex("dbo.BuyerProducts", new[] { "OwnerProductId" }); DropIndex("dbo.BuyerProducts", new[] { "SellerId" }); DropIndex("dbo.BuyerProducts", new[] { "UserId" }); DropTable("dbo.BuyerProducts"); } } }
public class Solution { public string Multiply(string num1, string num2) { if (num1 == "0" || num2 == "0") return "0"; int len = num1.Length + num2.Length; int[] helper = new int[len]; for (int j = num2.Length - 1; j >= 0 ; j --) { for (int i = num1.Length - 1; i >= 0; i --) { int curr = (num2[j] - '0') * (num1[i] - '0'); int prev = helper[len - i - j - 2]; helper[len - i - j - 2] = (curr + prev) % 10; helper[len - i - j - 1] += (curr + prev) / 10; } } StringBuilder sb = new StringBuilder(); if (helper[len - 1] != 0) sb.Append(helper[len - 1].ToString()); for (int i = len - 2; i >= 0; i --) { sb.Append(helper[i].ToString()); } return sb.ToString(); } }
using SciVacancies.Domain.Enums; using SciVacancies.ReadModel.Core; using System; using System.Collections.Generic; using System.Linq; using NPoco; using MediatR; namespace SciVacancies.WebApp.Queries { public class OrganizationQueriesHandler : IRequestHandler<SingleOrganizationQuery, Organization>, IRequestHandler<CountOrganizationsQuery, int>, IRequestHandler<SelectOrganizationsForAutocompleteQuery, IEnumerable<Organization>>, IRequestHandler<SelectPagedOrganizationsQuery, Page<Organization>>, IRequestHandler<SelectOrganizationsByGuidsQuery, IEnumerable<Organization>>, IRequestHandler<SelectOrganizationResearchDirectionsQuery, IEnumerable<ResearchDirection>> { private readonly IDatabase _db; public OrganizationQueriesHandler(IDatabase db) { _db = db; } public Organization Handle(SingleOrganizationQuery msg) { if (msg.OrganizationGuid == Guid.Empty) throw new ArgumentNullException($"OrganizationGuid is empty: {msg.OrganizationGuid}"); Organization organization = _db.SingleOrDefaultById<Organization>(msg.OrganizationGuid); return organization; } public IEnumerable<Organization> Handle(SelectOrganizationsForAutocompleteQuery msg) { if (String.IsNullOrEmpty(msg.Query)) throw new ArgumentNullException($"Query is empty: {msg.Query}"); IEnumerable<Organization> organizations; if (msg.Take != 0) { organizations = _db.FetchBy<Organization>(f => f.Where(w => w.name.Contains(msg.Query) && w.status != OrganizationStatus.Removed)).Take(msg.Take); } else { organizations = _db.FetchBy<Organization>(f => f.Where(w => w.name.Contains(msg.Query) && w.status != OrganizationStatus.Removed)); } return organizations; } public Page<Organization> Handle(SelectPagedOrganizationsQuery msg) { Page<Organization> organizations = _db.Page<Organization>(msg.PageIndex, msg.PageSize, new Sql("SELECT o.* FROM org_organizations o WHERE o.status != @0 ORDER BY o.guid DESC", OrganizationStatus.Removed)); return organizations; } public IEnumerable<Organization> Handle(SelectOrganizationsByGuidsQuery msg) { IEnumerable<Organization> organizations = _db.Fetch<Organization>(new Sql($"SELECT o.* FROM org_organizations o WHERE o.guid IN (@0) AND o.status != @1 ORDER BY o.guid DESC", msg.OrganizationGuids, OrganizationStatus.Removed)); return organizations; } public IEnumerable<ResearchDirection> Handle(SelectOrganizationResearchDirectionsQuery msg) { IEnumerable<ResearchDirection> orgResearchDirections = _db.Fetch<ResearchDirection>(new Sql($"SELECT * FROM org_researchdirections ors, d_researchdirections drs WHERE ors.organization_guid = @0 AND ors.researchdirection_id = drs.id", msg.OrganizationGuid)); return orgResearchDirections; } public int Handle(CountOrganizationsQuery msg) { var organizations = _db.Fetch<Organization>(new Sql($"SELECT * FROM org_organizations")); if (organizations != null && organizations.Count > 0) { return organizations.Count(); } else { return 0; } } } }
using System.Linq; using FluentAssertions; using Nono.Engine.Logging; using Xunit; namespace Nono.Engine.Tests { public class BasicTest { [Theory] [InlineData(1, 1)] [InlineData(1, 100)] [InlineData(100, 1)] [InlineData(3, 3)] [InlineData(3, 2)] [InlineData(2, 3)] public void BulkFill_Rectangle(int rowPower, int columnPower) { // Arrange var rowHint = new [] { columnPower }; var columnHint = new [] { rowPower }; var solve = new Solver(new NullLog()); var nonogram = new Nonogram(Enumerable.Repeat(rowHint, rowPower), Enumerable.Repeat(columnHint, columnPower)); var result = solve.Solve(nonogram); result.Field.RowCount.Should().Be(rowPower); result.Field.ColumnCount.Should().Be(columnPower); result.Field.All(x => x == Box.Filled).Should().BeTrue(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SoundEffect : MonoBehaviour { public AudioSource touch; void Start() { } void OnMouseDown() { touch.Play(); } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace StoreFront.Data { public class SFDataContext { public static string connection = "data source=3JNRXW1\\SQLEXPRESS; initial catalog=StoreFront; integrated security=True"; } }
using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Windows.Automation; using UIAFramework.Base; namespace UIAFramework { public class UIList : ControlBase { AutomationElement _UIList; public UIList() { } public UIList(string condition, string treescope, UIAEnums.ConditionType? type = null, [CallerMemberName] string memberName = "") : base(condition, treescope, type, memberName) { ParentBase.controlType = Common.GetControlType("list"); } public UIList(string condition, string treescope, AutomationElement ae, UIAEnums.ConditionType? type = null, [CallerMemberName] string memberName = "") : base(condition, treescope, ae, type, memberName) { ParentBase.controlType = Common.GetControlType("list"); } public UIList(string treePath, bool isPath, [CallerMemberName] string memberName = "") : base(treePath, isPath, memberName) { ParentBase.controlType = Common.GetControlType("list"); } public UIList(string treePath, bool isPath, AutomationElement ae, [CallerMemberName] string memberName = "") : base(treePath, isPath, ae, memberName) { ParentBase.controlType = Common.GetControlType("list"); } public UIList(AutomationElement ae, [CallerMemberName] string memberName = "") : base(ae,memberName) { ParentBase.controlType = Common.GetControlType("list"); } public UIList (string condition, string treescope, bool isMultipleControl, UIAEnums.ConditionType? type = null, [CallerMemberName] string memberName = "") :base(condition,treescope,isMultipleControl,type,memberName) { ParentBase.controlType = Common.GetControlType("list"); } public UIList(string condition, string treescope, AutomationElement ae, bool isMultipleControl, UIAEnums.ConditionType? type = null, [CallerMemberName] string memberName = "") : base(condition, treescope,ae, isMultipleControl, type, memberName) { ParentBase.controlType = Common.GetControlType("list"); } public UIList(AutomationElement ae) : base(ae) { } #region Actions /// <summary> /// Selects a comboBox Item based on its name /// </summary> /// <param name="name"></param> public void SelectListItem(string name) { _UIList = UnWrap(); ScrollPattern SIP = _UIList.GetScrollPattern(); if (SIP.Current.VerticallyScrollable) SIP.SetScrollPercent(SIP.Current.HorizontalScrollPercent, 0); AutomationElement ListItem = _UIList.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem)); while (ListItem != null) { ScrollItemPattern SP = ListItem.GetScrollItemPattern(); SP.ScrollIntoView(); AutomationElement textBlock = ListItem.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text)); if (textBlock.Current.Name.Contains(name)) { ListItem.GetSelectionItemPattern().Select(); return; } ListItem = ControlFactory.GetNextSibling<UIListItem>(ListItem).NativeElement; System.Threading.Thread.Sleep(500); } } /// <summary> /// Selects a Perticular ListItem based on its rowNumber /// </summary> /// <param name="rowNumber"></param> public void SelectListItem(int rowNumber) { UIListItem listItem = ControlFactory.Create<UIListItem>("listitem[" + rowNumber + "]", true, UnWrap()); listItem.Select(); } /// <summary> /// Gets all ListItems of ListView /// </summary> /// <param name="rowNumber"></param> public List<UIListItem> GetAllUIListItems() { _UIList = UnWrap(); List<UIListItem> ListItems = new List<UIListItem>(); ScrollPattern SIP = _UIList.GetScrollPattern(); if (SIP.Current.VerticallyScrollable) SIP.SetScrollPercent(SIP.Current.HorizontalScrollPercent, 0); AutomationElement ListItem = _UIList.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem)); while (ListItem != null) { ScrollItemPattern SP = ListItem.GetScrollItemPattern(); SP.ScrollIntoView(); ListItems.Add(new UIListItem(ListItem)); ListItem = ControlFactory.GetNextSibling<UIListItem>(ListItem).NativeElement; System.Threading.Thread.Sleep(500); } return ListItems; } /// <summary> /// Gets all ListItems Names of ListView /// </summary> /// <param name="rowNumber"></param> public List<string> GetAllUIListItemsName() { _UIList = UnWrap(); List<string> ListItemNames = new List<string>(); ScrollPattern SIP = _UIList.GetScrollPattern(); if (SIP.Current.VerticallyScrollable) SIP.SetScrollPercent(SIP.Current.HorizontalScrollPercent, 0); AutomationElement ListItem = _UIList.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem)); while (ListItem != null) { ScrollItemPattern SP = ListItem.GetScrollItemPattern(); SP.ScrollIntoView(); ListItemNames.Add(ListItem.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text)).Current.Name); ListItem = ControlFactory.GetNextSibling<UIListItem>(ListItem).NativeElement; System.Threading.Thread.Sleep(500); } return ListItemNames; } /// <summary> /// Gets all ListItems Check Boxes of ListView /// </summary> /// <param name="rowNumber"></param> public List<UICheckBox> GetAllUIListItemCheckBoxes() { _UIList = UnWrap(); List<UICheckBox> CheckBoxes = new List<UICheckBox>(); ScrollPattern SIP = _UIList.GetScrollPattern(); if (SIP.Current.VerticallyScrollable) SIP.SetScrollPercent(SIP.Current.HorizontalScrollPercent, 0); AutomationElement ListItem = _UIList.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem)); while (ListItem != null) { ScrollItemPattern SP = ListItem.GetScrollItemPattern(); SP.ScrollIntoView(); CheckBoxes.Add(new UICheckBox(ListItem.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.CheckBox)))); ListItem = ControlFactory.GetNextSibling<UIListItem>(ListItem).NativeElement; System.Threading.Thread.Sleep(500); } return CheckBoxes; } /// <summary> /// Gets a Perticular Check Box of ListItem Check Box of ListView /// </summary> /// <param name="rowNumber"></param> public UICheckBox GetCheckBoxOfUIListItem(string name) { _UIList = UnWrap(); ScrollPattern SIP = _UIList.GetScrollPattern(); if (SIP.Current.VerticallyScrollable) SIP.SetScrollPercent(SIP.Current.HorizontalScrollPercent, 0); AutomationElement ListItem = _UIList.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem)); while (ListItem != null) { ScrollItemPattern SP = ListItem.GetScrollItemPattern(); SP.ScrollIntoView(); AutomationElement textBlock = ListItem.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text)); if (textBlock.Current.Name == name) { return new UICheckBox(ListItem.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.CheckBox))); } ListItem = ControlFactory.GetNextSibling<UIListItem>(ListItem).NativeElement; System.Threading.Thread.Sleep(500); } throw new Exception("The name of list item you have entered i.e., " + name + "does not exists in the context"); } } #endregion }
using System; using System.Collections.Generic; using System.Linq; using NHibernate.Envers.Configuration.Attributes; using Profiling2.Domain.DTO; using Profiling2.Domain.Extensions; using Profiling2.Domain.Prf.Actions; using Profiling2.Domain.Prf.Organizations; using Profiling2.Domain.Prf.Persons; using Profiling2.Domain.Prf.Responsibility; using Profiling2.Domain.Prf.Sources; using Profiling2.Domain.Prf.Suggestions; using SharpArch.Domain.DomainModel; namespace Profiling2.Domain.Prf.Events { public class Event : Entity, IIncompleteDate { [Audited] public virtual string EventName { get; set; } [Audited] public virtual string NarrativeEn { get; set; } [Audited] public virtual string NarrativeFr { get; set; } [Audited] public virtual Location Location { get; set; } [Audited] public virtual int DayOfStart { get; set; } [Audited] public virtual int MonthOfStart { get; set; } [Audited] public virtual int YearOfStart { get; set; } [Audited] public virtual int DayOfEnd { get; set; } [Audited] public virtual int MonthOfEnd { get; set; } [Audited] public virtual int YearOfEnd { get; set; } [Audited] public virtual bool Archive { get; set; } [Audited] public virtual string Notes { get; set; } public virtual DateTime? Created { get; set; } [Audited(TargetAuditMode = RelationTargetAuditMode.NotAudited)] public virtual EventVerifiedStatus EventVerifiedStatus { get; set; } [Audited] public virtual IList<PersonResponsibility> PersonResponsibilities { get; set; } [Audited] public virtual IList<EventRelationship> EventRelationshipsAsSubject { get; set; } [Audited] public virtual IList<EventRelationship> EventRelationshipsAsObject { get; set; } public virtual IList<Tag> Tags { get; set; } [Audited] public virtual IList<OrganizationResponsibility> OrganizationResponsibilities { get; set; } [Audited] public virtual IList<EventSource> EventSources { get; set; } public virtual IList<AdminExportedEventProfile> AdminExportedEventProfiles { get; set; } public virtual IList<AdminReviewedSource> AdminReviewedSources { get; set; } public virtual IList<AdminSuggestionPersonResponsibility> AdminSuggestionPersonResponsibilities { get; set; } [Audited] public virtual IList<ActionTaken> ActionTakens { get; set; } [Audited] public virtual IList<Violation> Violations { get; set; } public virtual IList<EventApproval> EventApprovals { get; set; } [Audited] public virtual IList<JhroCase> JhroCases { get; set; } public Event() { this.PersonResponsibilities = new List<PersonResponsibility>(); this.EventRelationshipsAsSubject = new List<EventRelationship>(); this.EventRelationshipsAsObject = new List<EventRelationship>(); this.Tags = new List<Tag>(); this.OrganizationResponsibilities = new List<OrganizationResponsibility>(); this.EventSources = new List<EventSource>(); this.AdminExportedEventProfiles = new List<AdminExportedEventProfile>(); this.AdminReviewedSources = new List<AdminReviewedSource>(); this.AdminSuggestionPersonResponsibilities = new List<AdminSuggestionPersonResponsibility>(); this.ActionTakens = new List<ActionTaken>(); this.Violations = new List<Violation>(); this.EventApprovals = new List<EventApproval>(); this.JhroCases = new List<JhroCase>(); } public virtual string Headline { get { try { string cats = string.Join(", ", this.Violations.Select(x => x.Name)); // deprecated field, but some Events may still not have their categories populated - so we fall back on this if (string.IsNullOrEmpty(cats)) cats = this.EventName; return cats + " - " + this.Location.LocationName + " (" + this.GetStartDateString() + (this.HasEndDate() ? " to " + this.GetEndDateString() : string.Empty) + ")"; } catch (Exception) { return "(couldn't find audit trail object)"; } } } /// <summary> /// For audit purposes. /// </summary> public virtual string JhroCaseNumbers { get { return string.Join(", ", this.JhroCases.Select(x => x.CaseNumber)); } } /// <summary> /// For audit purposes. /// </summary> public virtual string ViolationNames { get { return string.Join(", ", this.Violations.Select(x => x.Name)); } } /// <summary> /// For audit purposes. /// </summary> public virtual string LocationNameSummary { get { try { return this.Location != null ? this.Location.ToString() : string.Empty; } catch (Exception e) { return e.Message; } } } public virtual string GetJhroCaseNumber() { if (this.JhroCases != null && this.JhroCases.Any()) { return this.JhroCases[0].CaseNumber; } return null; } /// <summary> /// Scours attached entities for the text "TBC". /// </summary> /// <returns></returns> public virtual IList<ToBeConfirmedDTO> GetToBeConfirmedDTOs() { IList<ToBeConfirmedDTO> dtos = new List<ToBeConfirmedDTO>(); foreach (PersonResponsibility pr in this.PersonResponsibilities.Where(x => !x.Archive && x.Person != null && (x.Commentary.IContains("TBC") || x.Notes.IContains("TBC")))) dtos.Add(new ToBeConfirmedDTO() { Type = typeof(PersonResponsibility).Name, Priority = "High", Summary = pr.Person.Name + " (" + pr.PersonResponsibilityType.ToString() + ")", Text = string.Join("\n<hr />", new string[] { pr.Commentary, pr.Notes }.Where(x => !string.IsNullOrEmpty(x) && x.IContains("TBC"))) }); foreach (OrganizationResponsibility or in this.OrganizationResponsibilities.Where(x => !x.Archive && x.Organization != null && (x.Commentary.IContains("TBC") || x.Notes.IContains("TBC")))) dtos.Add(new ToBeConfirmedDTO() { Type = typeof(OrganizationResponsibility).Name, Priority = "High", Summary = or.Organization.OrgLongName + " (" + or.OrganizationResponsibilityType.ToString() + ") " + (or.Unit != null ? or.Unit.UnitName : string.Empty), Text = string.Join("\n<hr />", new string[] { or.Commentary, or.Notes }.Where(x => !string.IsNullOrEmpty(x) && x.IContains("TBC"))) }); if (this.Notes.IContains("TBC")) dtos.Add(new ToBeConfirmedDTO() { Type = typeof(Event).Name, Priority = "Medium", Summary = this.Headline + " Notes", Text = this.Notes }); foreach (ActionTaken at in this.ActionTakens .Where(x => !x.Archive && (x.Commentary.IContains("TBC") || x.Notes.IContains("TBC")))) dtos.Add(new ToBeConfirmedDTO() { Type = typeof(ActionTaken).Name, Priority = "Medium", Summary = at.GetCompleteSummary(), Text = string.Join("\n<hr />", new string[] { at.Commentary, at.Notes }.Where(x => !string.IsNullOrEmpty(x) && x.IContains("TBC"))) }); foreach (PersonResponsibility pr in this.PersonResponsibilities.Where(x => !x.Archive && x.Person != null && (x.Person.BackgroundInformation.IContains("TBC") || x.Person.Notes.IContains("TBC")))) dtos.Add(new ToBeConfirmedDTO() { Type = typeof(Person).Name, Priority = "Medium", Summary = pr.Person.Name, Text = string.Join("\n<hr />", new string[] { pr.Person.BackgroundInformation, pr.Person.Notes }.Where(x => !string.IsNullOrEmpty(x) && x.IContains("TBC"))) }); foreach (PersonAlias pa in this.PersonResponsibilities.Select(x => x.Person.PersonAliases) .Aggregate(new List<PersonAlias>(), (output, z) => output.Concat(z).ToList()) .Where(x => !x.Archive && x.Notes.IContains("TBC"))) dtos.Add(new ToBeConfirmedDTO() { Type = typeof(PersonAlias).Name, Priority = "Medium", Summary = "Alias: " + pa.Name + " for person: " + pa.Person.Name, Text = pa.Notes }); foreach (OrganizationAlias oa in this.OrganizationResponsibilities.Select(x => x.Organization.OrganizationAliases) .Aggregate(new List<OrganizationAlias>(), (output, z) => output.Concat(z).ToList()) .Where(x => !x.Archive && x.Notes.IContains("TBC"))) dtos.Add(new ToBeConfirmedDTO() { Type = typeof(OrganizationAlias).Name, Priority = "Low", Summary = "Alias: " + oa.OrgLongName + " for organization: " + oa.Organization.OrgLongName, Text = oa.Notes }); return dtos; } public virtual bool IsApproved() { return this.EventApprovals != null && this.EventApprovals.Any(); } /// <summary> /// Useful for audit page. /// </summary> public virtual string EventVerifiedStatusName { get { return this.EventVerifiedStatus != null ? this.EventVerifiedStatus.EventVerifiedStatusName : string.Empty; } } public virtual bool IsPersonResponsible(Person p) { return this.PersonResponsibilities.Select(x => x.Person).Contains(p); } /// <summary> /// Return EventSources which haven't been archived. /// </summary> /// <returns></returns> public virtual IList<EventSource> GetUsableEventSources() { if (this.EventSources != null) { return this.EventSources.Where(x => !x.Archive && x.Source != null && !x.Source.Archive).ToList(); } return null; } /// <summary> /// Logic copied from Profiling1 'save as word'. /// </summary> /// <returns></returns> public virtual bool HasAtLeastOneReliableSource() { IList<EventSource> list = this.GetUsableEventSources().Where(x => x.Reliability != null).ToList(); if (list != null && list.Any()) { if (list.Count == 1) { return new string[] { Reliability.NAME_HIGH, Reliability.NAME_MODERATE }.Contains(list.First().Reliability.ReliabilityName); } return true; } return false; } public virtual IList<EventRelationship> GetEventRelationships() { return this.EventRelationshipsAsSubject.Concat(this.EventRelationshipsAsObject).ToList<EventRelationship>(); } public virtual IList<string> GetCaseCodesInEventSources() { return this.EventSources.Where(x => x.HasCaseCode()) .Select(x => x.GetCaseCodes()) .Aggregate(new List<string>(), (x, y) => x.Concat(y).ToList()) .Distinct() .ToList(); } /// <summary> /// Return a float between 0 and 1 where 1 is identical and 0 is not. Used as a filter in finding similar events. /// </summary> /// <param name="e"></param> /// <returns></returns> public virtual float GetViolationSimilarity(Event e) { if (e != null) { float f = 0; float part = 1 / (float)this.Violations.Count; foreach (Violation v in this.Violations) { if (e.Violations.Contains(v)) f += part; } return f; } return 0; } /// <summary> /// Return a float between 0 and 1 where 1 is identical and 0 is not. Used as a filter in finding similar events. /// </summary> /// <param name="e"></param> /// <returns></returns> public virtual float GetLocationSimilarity(Event e) { if (e != null) { if (e.Location == null && this.Location == null) return 1; else if (e.Location != null && this.Location != null) return e.Location.GetSimilarity(this.Location); } return 0; } public override string ToString() { return "Event(ID=" + this.Id + ")"; } public virtual object ToShortHeadlineJSON() { return new { Id = this.Id, CaseCode = string.Join("; ", this.JhroCases.Select(x => x.CaseNumber)), Headline = this.Headline, VerifiedStatus = this.EventVerifiedStatus != null ? this.EventVerifiedStatus.EventVerifiedStatusName : null }; } public virtual object ToShortJSON() { return new { Id = this.Id, CaseCode = string.Join("; ", this.JhroCases.Select(x => x.CaseNumber)), StartDate = this.HasStartDate() ? this.GetStartDateString() : null, EndDate = this.HasEndDate() ? this.GetEndDateString() : null, Location = this.Location.ToShortJSON(), Violations = this.Violations.Select(x => x.ToJSON()), VerifiedStatus = this.EventVerifiedStatus != null ? this.EventVerifiedStatus.EventVerifiedStatusName : null }; } public virtual object ToJSON(IList<SourceDTO> sources, int personId) { return new { Id = this.Id, CaseCode = string.Join("; ", this.JhroCases.Select(x => x.CaseNumber)), StartDate = this.HasStartDate() ? this.GetStartDateString() : null, EndDate = this.HasEndDate() ? this.GetEndDateString() : null, Location = this.Location.ToShortJSON(), Violations = this.Violations.Select(x => x.ToJSON()), Narrative = !string.IsNullOrEmpty(this.NarrativeEn) ? this.NarrativeEn : this.NarrativeFr, Notes = this.Notes, VerifiedStatus = this.EventVerifiedStatus != null ? this.EventVerifiedStatus.EventVerifiedStatusName : null, ActionsTaken = this.ActionTakens.Select(x => x.ToJSON()), OthersResponsible = this.PersonResponsibilities.Where(x => !x.Archive && x.Person.Id != personId).Select(x => x.ToJSON()), EventSources = this.EventSources.Select(x => x.ToJSON(sources.Where(y => y.SourceID == x.Source.Id).First())), RelatedEvents = this.EventRelationshipsAsSubject.Where(x => !x.Archive).Select(x => x.ToJSON()) .Concat(this.EventRelationshipsAsObject.Where(x => !x.Archive).Select(x => x.ToJSON())), Tags = this.Tags.Select(x => x.ToJSON()) }; } // data modification methods public virtual void AddJhroCase(JhroCase jc) { if (this.JhroCases.Contains(jc)) return; this.JhroCases.Add(jc); } public virtual void AddEventSource(EventSource es) { if (this.EventSources.Contains(es)) return; this.EventSources.Add(es); } public virtual void RemoveEventSource(EventSource es) { this.EventSources.Remove(es); } public virtual bool AddPersonResponsibility(PersonResponsibility pr) { if (this.PersonResponsibilities.Contains(pr)) return false; this.PersonResponsibilities.Add(pr); pr.Person.AddPersonResponsibility(pr); return true; } public virtual void RemovePersonResponsibility(PersonResponsibility pr) { this.PersonResponsibilities.Remove(pr); } public virtual bool AddOrganizationResponsibility(OrganizationResponsibility or) { foreach (OrganizationResponsibility o in this.OrganizationResponsibilities) { if (o.Organization.Id == or.Organization.Id) { if (o.Unit == null && or.Unit == null) return false; else if (o.Unit != null && or.Unit != null && o.Unit.Id == or.Unit.Id) return false; } } this.OrganizationResponsibilities.Add(or); or.Organization.AddOrganizationResponsibility(or); return true; } public virtual void RemoveOrganizationResponsibility(OrganizationResponsibility or) { this.OrganizationResponsibilities.Remove(or); } public virtual void AddActionTaken(ActionTaken at) { this.ActionTakens.Add(at); } public virtual void RemoveActionTaken(ActionTaken at) { this.ActionTakens.Remove(at); } public virtual void AddEventRelationshipAsSubject(EventRelationship er) { if (this.EventRelationshipsAsSubject != null && this.EventRelationshipsAsSubject.Contains(er)) return; this.EventRelationshipsAsSubject.Add(er); } public virtual void AddEventRelationshipAsObject(EventRelationship er) { if (this.EventRelationshipsAsObject != null && this.EventRelationshipsAsObject.Contains(er)) return; this.EventRelationshipsAsObject.Add(er); } public virtual void RemoveEventRelationshipAsSubject(EventRelationship er) { this.EventRelationshipsAsSubject.Remove(er); } public virtual void RemoveEventRelationshipAsObject(EventRelationship er) { this.EventRelationshipsAsObject.Remove(er); } } }
using System; using System.Collections.Generic; using System.Text; namespace MinesweeperLibrary.FillInBoard { public class FillInBoardWith0 : IFillInBoardWith0 { //Print Board with 0 only public void FillInBoardWith0Only(int grid, char[,] board) { for (int i = 0; i < grid; i++) { for (int j = 0; j < grid; j++) { board[i, j] = '0'; } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace LoginFrame { public partial class Frm关于 : Form { public Frm关于() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { this.Close(); } private void Frm关于_Load(object sender, EventArgs e) { string version = System.Configuration.ConfigurationManager.AppSettings["version"].ToString();//窗口标题 this.label1.Text = version; //string AboutImage = "../../pic/" + System.Configuration.ConfigurationManager.AppSettings["AboutImage"].ToString();//关于图片 //AboutImage += Application.StartupPath + AboutImage; //this.pictureBox1.BackgroundImage = Image.FromFile(AboutImage); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Anywhere2Go.DataAccess.AccountObject { class Reports { } public class AccountingKPIModel { public string DepId { get; set; } public string StartDate { get; set; } public string EndDate { get; set; } public AccountingKPIReport AccountingKPIReport { get; set; } } public class AccountingKPIReport { public AccountingKPIReport() { AccountingKPIItems = new List<AccountingKPIItemReport>(); } public List<AccountingKPIItemReport> AccountingKPIItems { get; set; } } public class AccountingKPIItemReport { public string CreateBy { get; set; } public int SumStatusWaitApprove { get; set; } public int SumStatusApprove { get; set; } public int SumStatusOpenBilling { get; set; } public int SumStatusCloseBilling { get; set; } } }
// ----------------------------------------------------------------------- // <copyright file="TaskExtensions.cs" company="AnoriSoft"> // Copyright (c) AnoriSoft. All rights reserved. // </copyright> // ----------------------------------------------------------------------- namespace Anori.Extensions { using System; using System.Threading.Tasks; using JetBrains.Annotations; /// <summary> /// Task Extensions. /// </summary> public static class TaskExtensions { #pragma warning disable S3168 // "async" methods should not return "void" /// <summary> /// Fires the and forget safe asynchronous. /// </summary> /// <param name="task">The task.</param> /// <param name="error">The error.</param> public static async void FireAndForgetSafeAsync(this Task task, Action<Exception>? error = null) #pragma warning restore S3168 // "async" methods should not return "void" { try { await task; } catch (Exception ex) { error.Raise(ex); } } #pragma warning disable S3168 // "async" methods should not return "void" /// <summary> /// Fires the and forget safe asynchronous. /// </summary> /// <param name="task">The task.</param> /// <param name="completed">The completed.</param> /// <param name="error">The error.</param> /// <param name="final">The final.</param> /// <param name="cancel">The cancel.</param> /// <param name="configureAwait">if set to <c>true</c> [configure await].</param> /// <exception cref="System.ArgumentNullException">task is null.</exception> public static async void FireAndForgetSafeAsync( [NotNull] this Task task, Action? completed = null, Action<Exception>? error = null, Action? final = null, Action? cancel = null, bool configureAwait = false) #pragma warning restore S3168 // "async" methods should not return "void" { if (task == null) { throw new ArgumentNullException(nameof(task)); } try { await task.ConfigureAwait(configureAwait); completed?.Invoke(); } catch (TaskCanceledException) { cancel.Raise(); } catch (Exception ex) { error.Raise(ex); } finally { final.Raise(); } } #pragma warning disable RECS0165 // Asynchronous methods should return a Task instead of void #pragma warning disable S3168 // "async" methods should not return "void" /// <summary> /// Fires the and forget safe asynchronous. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <param name="task">The task.</param> /// <param name="completed">The completed.</param> /// <param name="error">The error.</param> /// <param name="final">The final.</param> /// <param name="cancel">The cancel.</param> /// <param name="configureAwait">if set to <c>true</c> [configure await].</param> /// <exception cref="ArgumentNullException">task is null.</exception> public static async void FireAndForgetSafeAsync<T>( [NotNull] this Task<T> task, Action<T>? completed = null, Action<Exception>? error = null, Action? final = null, Action? cancel = null, bool configureAwait = false) #pragma warning restore S3168 // "async" methods should not return "void" #pragma warning restore RECS0165 // Asynchronous methods should return a Task instead of void { if (task == null) { throw new ArgumentNullException(nameof(task)); } try { var result = await task.ConfigureAwait(configureAwait); completed.Raise(result); } catch (TaskCanceledException) { cancel.Raise(); } catch (Exception ex) { error.Raise(ex); } finally { final.Raise(); } } #pragma warning disable RECS0165 // Asynchronous methods should return a Task instead of void #pragma warning disable S3168 // "async" methods should not return "void" /// <summary> /// Fires the and forget safe asynchronous. /// </summary> /// <typeparam name="T">The type.</typeparam> /// <param name="task">The task.</param> /// <param name="completed">The completed.</param> /// <param name="error">The error.</param> /// <param name="final">The final.</param> /// <param name="cancel">The cancel.</param> /// <param name="configureAwait">if set to <c>true</c> [configure await].</param> /// <exception cref="System.ArgumentNullException">task is null.</exception> public static async void FireAndForgetSafeAsync<T>( [NotNull] this Task<T> task, Func<T, Task>? completed = null, Func<Exception, Task>? error = null, Func<Task>? final = null, Func<Task>? cancel = null, bool configureAwait = false) #pragma warning restore S3168 // "async" methods should not return "void" #pragma warning restore RECS0165 // Asynchronous methods should return a Task instead of void { if (task == null) { throw new ArgumentNullException(nameof(task)); } try { var result = await task.ConfigureAwait(configureAwait); await completed.RaiseAsync(result); } catch (TaskCanceledException) { await cancel.RaiseAsync(); } catch (Exception ex) { await error.RaiseAsync(ex); } finally { await final.RaiseAsync(); } } /// <summary> /// Determines whether this instance is finished. /// </summary> /// <param name="task">The task.</param> /// <returns> /// <c>true</c> if the specified task is finished; otherwise, <c>false</c>. /// </returns> /// <exception cref="ArgumentNullException">task is null.</exception> public static bool IsFinished([NotNull] this Task task) { if (task == null) { throw new ArgumentNullException(nameof(task)); } if (task.IsCompleted) { return true; } if (task.IsCanceled) { return true; } // ReSharper disable once ConvertIfStatementToReturnStatement if (task.IsFaulted) { return true; } return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel.DataAnnotations; namespace Xlns.BusBook.Core.Model { public class Flyer : ModelEntity { [Required(ErrorMessage="Il titolo è obbligatorio!")] [Display(Name="Titolo")] [StringLength(50, ErrorMessage = "Il titolo dev'essere al massimo 50 caratteri")] public virtual String Titolo { get; set; } [Display(Name = "Descrizione")] [StringLength(500, ErrorMessage="La descrizione dev'essere al massimo 500 caratteri")] public virtual String Descrizione { get; set; } public virtual IList<Viaggio> Viaggi { get; set; } public virtual Agenzia Agenzia { get; set; } } }
using System; using System.Globalization; namespace Task_06 { class Program { static CultureInfo ci = new CultureInfo("ru-us"); static void Percent(double budget, byte part) { Console.WriteLine("Доля, выделенная пользователем на компьютерные игры: {0}", (budget * part / 100).ToString("C", ci)); } static void Main(string[] args) { Console.WriteLine("Введите бюджет пользователя в долларах"); if (!double.TryParse(Console.ReadLine(), out double budget) || budget < 0) { Console.WriteLine("Ошибка!"); return; } Console.WriteLine("Введите процент бюджета, выделенного на компьютерные игры"); if (!byte.TryParse(Console.ReadLine(), out byte part) || part > 100) { Console.WriteLine("Ошибка!"); return; } Percent(budget, part); Console.ReadLine(); } } }
using Cottle.Functions; using Cottle.Values; using EddiCore; using EddiDataDefinitions; using EddiDataProviderService; using EddiSpeechResponder.Service; using JetBrains.Annotations; using System; using Utilities; namespace EddiSpeechResponder.CustomFunctions { [UsedImplicitly] public class Distance : ICustomFunction { public string name => "Distance"; public FunctionCategory Category => FunctionCategory.Utility; public string description => Properties.CustomFunctions_Untranslated.Distance; public Type ReturnType => typeof( decimal? ); public NativeFunction function => new NativeFunction((values) => { bool numVal = values[0].Type == Cottle.ValueContent.Number; bool stringVal = values[0].Type == Cottle.ValueContent.String; StarSystem curr = null; StarSystem dest = null; if (values.Count == 1 && stringVal) { curr = EDDI.Instance?.CurrentStarSystem; dest = StarSystemSqLiteRepository.Instance.GetOrFetchStarSystem(values[0].AsString, true); } else if (values.Count == 2 && stringVal) { curr = StarSystemSqLiteRepository.Instance.GetOrFetchStarSystem(values[0].AsString, true); dest = StarSystemSqLiteRepository.Instance.GetOrFetchStarSystem(values[1].AsString, true); } if (curr != null && dest != null) { var result = curr.DistanceFromStarSystem(dest); if (result is null) { return $"Unable to calculate distance between {curr.systemname} and {dest.systemname}. Could not obtain system coordinates."; } return new ReflectionValue(result); } else if (values.Count == 6 && numVal) { var x1 = values[0].AsNumber; var y1 = values[1].AsNumber; var z1 = values[2].AsNumber; var x2 = values[3].AsNumber; var y2 = values[4].AsNumber; var z2 = values[5].AsNumber; var result = Functions.StellarDistanceLy(x1, y1, z1, x2, y2, z2); return new ReflectionValue(result); } else { return "The Distance function is used improperly. Please review the documentation for correct usage."; } }, 1, 6); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NfePlusAlpha.Domain.Entities { public class tbNotaFiscalEletronicaTransportador { public tbNotaFiscalEletronicaTransportador() { this.tbNotaFiscalEletronica = new tbNotaFiscalEletronica(); } public int nft_codigo { get; set; } public int nft_modFrete { get; set; } //Transporta public string nft_cpfcnpj { get; set; } public string nft_xNome { get; set; } public string nft_IE { get; set; } public string nft_xEnder { get; set; } public string nft_xMun { get; set; } public string nft_UF { get; set; } //veicTransp public string nft_veicTranspPlaca { get; set; } public string nft_veicTranspUF { get; set; } public string nft_veicTranspRNTC { get; set; } //Volumes public int nft_qVol { get; set; } public string nft_esp { get; set; } public string nft_marca { get; set; } public string nft_nVol { get; set; } public decimal nft_pesoL { get; set; } public decimal nft_pesoB { get; set; } //Lacres public string nft_nLacres { get; set; } public int nfe_codigo { get; set; } public virtual tbNotaFiscalEletronica tbNotaFiscalEletronica { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace CG.MovieApp.UI.Models { public class DirectorModel { [Required(ErrorMessage ="Bu alan boş geçilemez.")] [StringLength(35,ErrorMessage ="Bu alan 35 max 35 karakter.",MinimumLength =3)] public string Name { get; set; } [Required(ErrorMessage = "Bu alan boş geçilemez.")] [StringLength(35, ErrorMessage = "Bu alan 35 max 35 karakter.", MinimumLength = 3)] public string LastName { get; set; } [Required(ErrorMessage ="Bu alan boş geçilemez.")] public string Country { get; set; } public DateTime BirthDate { get; set; } public List<FilmModel> Films { get; set; } } }
using System; using System.Collections.Generic; using Microsoft.UnifiedRedisPlatform.Core.Extensions; using Microsoft.UnifiedRedisPlatform.Core.Services.Models; namespace Microsoft.UnifiedRedisPlatform.Core.Logging { internal static class GenericLogProvider { internal static GenericLog CreateFromEvent(string eventName, double timeTaken = 0.0, IDictionary<string, string> properties = null, IDictionary<string, string> metrics = null) { var genericLog = new GenericLog() { LogType = LogTypes.Event, Message = eventName, Duration = timeTaken, Time = DateTimeOffset.UtcNow }; if (properties != null) genericLog.Properties.AddRange(properties); if (metrics != null) genericLog.Properties.AddRange(metrics); return genericLog; } internal static GenericLog CreateFromException(Exception exception, IDictionary<string, string> properties = null) { var genericLog = new GenericLog() { LogType = LogTypes.Exception, Message = exception.ToString(), Time = DateTimeOffset.UtcNow }; if (properties != null) genericLog.Properties.AddRange(properties); return genericLog; } internal static GenericLog CreateFromMetric(string metricName, double duration, IDictionary<string, string> properties = null, IDictionary<string, string> metrics = null) { var genericLog = new GenericLog() { LogType = LogTypes.Event, Message = metricName, Duration = duration, Time = DateTimeOffset.UtcNow }; if (properties != null) genericLog.Properties.AddRange(properties); if (metrics != null) genericLog.Properties.AddRange(metrics); return genericLog; } } }
using ApartmentApps.Api; using ApartmentApps.Api.Modules; using ApartmentApps.Api.Services; using ApartmentApps.Api.ViewModels; using ApartmentApps.Data; namespace ApartmentApps.Portal.Controllers { public class UnitMapper : BaseMapper<Unit, UnitViewModel> { public UnitMapper(IUserContext userContext, IModuleHelper moduleHelper) : base(userContext, moduleHelper) { } public override void ToModel(UnitViewModel viewModel, Unit model) { model.Name = viewModel.Name; model.Latitude = viewModel.Latitude; model.Longitude = viewModel.Longitude; model.BuildingId = viewModel.BuildingId; } public override void ToViewModel(Unit model, UnitViewModel viewModel) { viewModel.Id = model.Id.ToString(); viewModel.Name = model.Name; viewModel.Title = $"{model.Building.Name} - {model.Name}"; viewModel.Latitude = model.Latitude; viewModel.Longitude = model.Longitude; viewModel.BuildingId = model.BuildingId; viewModel.BuildingName = model.Building.Name; viewModel.SearchAlias = $"{model.Building.Name}-{model.Name}"; } } }
using UnityEngine; using System.Collections; /** * @author Chris Foulston */ namespace Malee.Hive.Events { public class PhysicsEventsProxy : MonoBehaviour { public delegate void TriggerEnter(Collider collider); public delegate void TriggerStay(Collider collider); public delegate void TriggerExit(Collider collider); public delegate void CollisionEnter(Collision collision); public delegate void CollisionStay(Collision collision); public delegate void CollisionExit(Collision collision); public TriggerEnter triggerEnterDelegate; public TriggerStay triggerStayDelegate; public TriggerExit triggerExitDelegate; public CollisionEnter collisionEnterDelegate; public CollisionStay collisionStayDelegate; public CollisionExit collisionExitDelegate; // // -- UNITY -- // void OnTriggerEnter(Collider collider) { if (triggerEnterDelegate != null) { triggerEnterDelegate(collider); } } void OnTriggerStay(Collider collider) { if (triggerStayDelegate != null) { triggerStayDelegate(collider); } } void OnTriggerExit(Collider collider) { if (triggerExitDelegate != null) { triggerExitDelegate(collider); } } void OnCollisionEnter(Collision collision) { if (collisionEnterDelegate != null) { collisionEnterDelegate(collision); } } void OnCollisionStay(Collision collision) { if (collisionStayDelegate != null) { collisionStayDelegate(collision); } } void OnCollisionExit(Collision collision) { if (collisionExitDelegate != null) { collisionExitDelegate(collision); } } } }
using System; using System.Web.Mvc; namespace Allyn.MvcApp.Areas.Shop { public class ShopAreaRegistration : AreaRegistration { public override string AreaName { get { return "Shop"; } } public override void RegisterArea(AreaRegistrationContext context) { //微信服务配置 context.MapRoute( "WeChatService", "Shop/{controller}/{action}/{signature}/{timestamp}/{nonce}/{echoStr}", new { ontroller = "home", action = "Index", signature = UrlParameter.Optional, timestamp = UrlParameter.Optional, echoStr = UrlParameter.Optional }, new { controller = @"^[\w]+$", action = @"^[\w]+$", signature = @"^[\w]+$", nonce = @"^[\w]+$", timestamp = @"^[\w]+$", echoStr = @"^[\w]+$" }, new string[] { "Allyn.MvcApp.Areas.Shop.Controllers" } ); // context.MapRoute( // "ShopKeyAndQty", // "Shop/{controller}/{action}/{productKey}/{qty}", // new { controller = "shop", action = "shopping" }, // new { controller = @"^[\w]+$", action = @"^[\w]+$", productKey = @"^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$", qty = "^[0-9]+$" }, // new string[] { "Allyn.MvcApp.Areas.Shop.Controllers" } //); //商城带标识参数配置. context.MapRoute( "ShopKey", "Shop/{controller}/{action}/{id}", new { controller = "home", action = "index", id = UrlParameter.Optional }, new { controller = @"^[\w]+$", action = @"^[\w]+$", id = @"^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$" }, new string[] { "Allyn.MvcApp.Areas.Shop.Controllers" } ); ///微信授权配置 context.MapRoute( "WxAuthCode", "Shop/{controller}/{action}/{code}", new { controller = "home", action = "Index", code = UrlParameter.Optional }, new { controller = @"^[\w]+$", action = @"^[\w]+$", code = @"^[\w]+$" }, new string[] { "Allyn.MvcApp.Areas.Shop.Controllers" } ); //商城主页 context.MapRoute( "ShopDefault", "Shop/{controller}/{action}", new { controller = "home", action = "index" }, new { controller = @"^[\w]+$", action = @"^[\w]+$" }, new string[] { "Allyn.MvcApp.Areas.Shop.Controllers" } ); // //商城主页 // context.MapRoute( // "AreasDefault", // "{controller}/{action}", // new { areas="Shop",controller = "home", action = "index" }, // new { controller = @"^[\w]+$", action = @"^[\w]+$" }, // new string[] { "Allyn.MvcApp.Areas.Shop.Controllers" } //); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class moveStars : MonoBehaviour { private Vector3 leftBottomCameraBorder; private Vector3 siz; // Start is called before the first frame update void Start() { leftBottomCameraBorder = Camera.main.ViewportToWorldPoint(new Vector3(0,0,0)); } // Update is called once per frame void Update() { gameObject.GetComponent<Rigidbody2D>().velocity=new Vector2(-1,0); siz.x=gameObject.GetComponent<SpriteRenderer>().bounds.size.x; siz.y=gameObject.GetComponent<SpriteRenderer>().bounds.size.y; //float random= Random.Range(leftBottomCameraBorder.y,leftTopCameraBorder.y); if (transform.position.x < leftBottomCameraBorder.x + (siz.x / 2)) Destroy(gameObject); } }
using System; using System.Threading.Tasks; using System.Text; using System.CodeDom.Compiler; using System.Reflection; using System.Linq; using System.Collections.Generic; using System.IO; namespace Theresa { public class TemplateCompilerBase { } public interface ITemplateRunner { Task<string> GetString(object[] values); } public class Template { static Dictionary<string, Template> Compilers = new Dictionary<string, Template>(); ITemplateRunner RunnerInstance; private Template() { } public static async Task<Template> FromFile(string fileName) { if (!Compilers.ContainsKey(fileName)) { using (var stream = new System.IO.FileStream(fileName, FileMode.Open)) { Compilers[fileName] = await Template.FromStream(stream); } } return Compilers[fileName]; } public static async Task<Template> FromStream(Stream stream) { Type type = await Parser.ParseStream(stream); return new Template { RunnerInstance = Activator.CreateInstance(type) as ITemplateRunner }; } public async Task<string> Execute(params object[] values) { return await this.RunnerInstance.GetString(values); } } public class TheresaException : Exception { public TheresaException(string message) : base(message) { } } /// <summary> /// A Parser instance is responsible for parsing a stream of template data, and dynamically generating and returning /// a type that implements ITemplateRunner. /// </summary> internal static class Parser { const string BaseCode = @" using System; using System.Text; using System.Threading.Tasks; {0} namespace Theresa {{ public class TemplateRunner : {1}, ITemplateRunner {{ StringBuilder StringBuilder = new StringBuilder(); {2} public async Task<string> GetString(object[] values) {{ {3} {4} //#line 2 ""/Users/Alex/GoogleDrive/Projects/code/Template/Theresa.Test/Templates/basic.thtml"" //throw new TheresaException(""asdf""); //#line default return this.StringBuilder.ToString(); }} }} }} "; enum ReadState { Literal, Code, UnescapedExpression, Expression, Directives } public static async Task<Type> ParseStream(Stream stream) { StringBuilder outputCode = new StringBuilder(); StringBuilder classCode = new StringBuilder(); StringBuilder currentOutput = outputCode; ReadState currentState = ReadState.Literal; string CodeParams = ""; try { /*using(var reader = new StreamReader(stream)) { while(!reader.EndOfStream) { string line = await reader.ReadLineAsync(); if(currentState == ReadState.Literal && String.IsNullOrWhiteSpace(line)) { currentOutput.Append("this.StringBuilder.Append(\"" + line + "\\n\");\n"); continue; } bool onlyCode = true; bool lineHasCode = false; string[] segments = System.Text.RegularExpressions.Regex.Split(line, @"(<%==|<%=|<%@|<%\+|<%|%>)"); for(int i = 0, segmentsLength = segments.Length; i < segmentsLength; i++) { var segment = segments[i]; if(segment == "<%") { currentOutput = outputCode; currentState = ReadState.Code; continue; } else if(segment == "<%@") { currentState = ReadState.Directives; continue; } else if(segment == "<%+") { currentOutput = classCode; currentState = ReadState.Code; continue; } else if(segment == "<%=") { currentState = ReadState.Expression; continue; } else if(segment == "<%==") { currentState = ReadState.UnescapedExpression; continue; } else if(segment == "%>") { currentState = ReadState.Literal; continue; } switch(currentState) { case ReadState.Code: currentOutput.Append(segment + "\n"); lineHasCode = true; break; case ReadState.Literal: if(segment == "") break; // Only output whitespace if the line already has code. if(!String.IsNullOrWhiteSpace(segment) || (lineHasCode && String.IsNullOrWhiteSpace(segment))) { onlyCode = false; currentOutput.Append("this.StringBuilder.Append(\"" + segment + "\");\n"); } break; case ReadState.Expression: currentOutput.Append("this.StringBuilder.Append( global::Theresa.Util.EscapeHtml((" + segment + ").ToString()) );\n"); lineHasCode = true; break; case ReadState.UnescapedExpression: currentOutput.Append("this.StringBuilder.Append((" + segment + ").ToString());\n"); lineHasCode = true; break; case ReadState.Directives: this.HandleDirective(segment); break; } } if(!onlyCode) currentOutput.Append(@"this.StringBuilder.Append(""\n"");" + "\n"); } }*/ string output = String.Format( BaseCode, "", "Object", "",//classCode.ToString(), "",//CodeParams, ""//outputCode.ToString() ); //CSharpCodeProvider provider = new CSharpCodeProvider(); //CompilerParameters parameters = new CompilerParameters(); var c = new CSharpParser(); c.ParseExpression("var x = "); var assemblies = AppDomain.CurrentDomain .GetAssemblies() .Where(a => !a.IsDynamic) .GroupBy(a => a.GetName().Name) .Select(g => g.OrderBy(a => a.GetName().Version ).Last()) .Select(a => a.Location) .ToArray(); /* parameters.ReferencedAssemblies.AddRange(assemblies); parameters.IncludeDebugInformation = true; parameters.GenerateInMemory = false; // false when debugging parameters.GenerateExecutable = false; CompilerResults results = provider.CompileAssemblyFromSource(parameters, output); if (results.Errors.HasErrors) { var errors = new List<TheresaException>(); foreach (CompilerError error in results.Errors) errors.Add(new TheresaException(error.ToString())); throw new AggregateException(errors); } return results.CompiledAssembly.GetType("Theresa.TemplateRunner"); */ return null; } catch(Exception e) { throw e; } } static void HandleDirective(string directive) { string[] parts = directive.Split(':').Select(s => s.Trim()).ToArray(); if (parts[0] == "params") { //this.CodeParams = parts[1]; } } } }
using System; using System.Collections.Generic; using Admin.Extentions; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Musical_WebStore_BlazorApp.Shared; using Musical_WebStore_BlazorApp.Client; using Musical_WebStore_BlazorApp.Server.Data; using Microsoft.EntityFrameworkCore; using Musical_WebStore_BlazorApp.Server.Data.Models; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Components.Authorization; using Admin.Models; using AutoMapper; using Admin.ViewModels; using Admin.ResultModels; namespace Musical_WebStore_BlazorApp.Server.Controllers { [ApiController] [Route("api/[controller]")] public class ChatsController : Controller { private readonly MusicalShopIdentityDbContext ctx; private readonly UserManager<User> _userManager; private readonly IMapper _mapper; public ChatsController(MusicalShopIdentityDbContext ctx, UserManager<User> userManager, IMapper mapper) { this.ctx = ctx; _userManager = userManager; _mapper = mapper; } private Task<Chat[]> GetChatsAsync() => ctx.Chats.ToArrayAsync(); [Route("getchats/{email}")] public async Task<ChatModel[]> GetChats(string email) { var user = await _userManager.FindByEmailAsync(email); var chats = await GetChatsAsync(); var chatsmodels = chats.Where(c => c.ChatUsers.Select(cu => cu.UserId).Contains(user.Id)).Select(c => _mapper.Map<ChatModel>(c)).ToArray(); return chatsmodels; } [Route("getchatsforservice")] public async Task<ChatModel[]> GetChatsForService() { var user = await _userManager.FindByEmailAsync(User.Identity.Name); var serviceid = ctx.ServiceUsers.Single(us => us.UserId == user.Id).ServiceId; var chats = await GetChatsAsync(); var chatsmodels = chats.Where(c => c.ServiceId == serviceid) .Where(cm => ctx.ChatUsers.Where(cu => cu.ChatId == cm.Id).Count() == 1) .Select(c => _mapper.Map<ChatModel>(c)) .ToArray(); return chatsmodels; } public Task<Message[]> GetMessagesAsync() => ctx.Messages.ToArrayAsync(); [Route("getmessages")] public async Task<MessageModel[]> GetMessages() { var messages = await GetMessagesAsync(); var messagesmodels = messages.Select(m => _mapper.Map<MessageModel>(m)).ToArray(); return messagesmodels; } [HttpPost] [Route("addmessage")] public async Task<AddMessageResult> AddMessage(AddMessageModel model) { var mes = _mapper.Map<Message>(model); mes.Date = DateTime.Now; var email = User.Identity.Name; var user = await _userManager.FindByEmailAsync(email); mes.UserId = user.Id; ctx.Messages.Add(mes); await ctx.SaveChangesAsync(); return new AddMessageResult() {Success = true}; } [Route("addchat")] public async Task<Result> AddChat(AddChatModel model) { var user = await _userManager.FindByEmailAsync(User.Identity.Name); var chat = new Chat() { Name = user.GetCompany(ctx).Name + " - " + ctx.Services.Single(s => s.Id == model.ServiceId).Name, Description = "—", ServiceId = model.ServiceId, CompanyId = user.GetCompany(ctx).Id }; ctx.Chats.Add(chat); ctx.SaveChanges(); ctx.ChatUsers.Add( new ChatUser() { UserId = user.Id, ChatId = chat.Id } ); ctx.SaveChanges(); ctx.Messages.Add( new Message() { Date = DateTime.Now, ChatId = chat.Id, Text = "Conversation was started", } ); ctx.SaveChanges(); return new Result() { Successful = true}; } [Route("joinchat")] public async Task<Result> JoinChat(JoinChatModel model) { var user = await _userManager.FindByEmailAsync(User.Identity.Name); ctx.ChatUsers.Add ( new ChatUser() { ChatId = model.ChatId, UserId = user.Id } ); ctx.Messages.Add( new Message() { ChatId = model.ChatId, Text = $"{user.UserName} joined chat." } ); await ctx.SaveChangesAsync(); return new Result() {Successful = true}; } [Route("getchatusers/{chatId}")] public async Task<ChatUserModel[]> GetChatUsers(int chatId) { var cuModels = ctx.ChatUsers.Where(cu => cu.ChatId == chatId).Select(cu => _mapper.Map<ChatUserModel>(cu)).ToArray(); return cuModels; } [Route("getusers")] public async Task<UserLimited[]> GetUsers() { var users = await _userManager.Users.ToArrayAsync(); var res = users.Select(u => _mapper.Map<UserLimited>(u)).ToArray(); return res; } } }
using Andreys.App.Models; using Andreys.App.Services; using Andreys.App.ViewModels.Products; using SIS.HTTP; using SIS.MvcFramework; namespace Andreys.App.Controllers { public class ProductsController : Controller { private readonly IProductsService _productsService; public ProductsController(IProductsService productsService) { _productsService = productsService; } [HttpGet("/Products/Add")] public HttpResponse Add() { if (!this.IsUserLoggedIn()) { return this.Redirect("/Users/Login"); } return this.View(); } [HttpPost("/Products/Add")] public HttpResponse Add(ProductInputModel input) { if (!this.IsUserLoggedIn()) { return this.Redirect("/Users/Login"); } if (input.Name.Length < 4 || input.Name.Length > 20) { return this.Error("Name must be contain at least 4 or must have 20 characters"); } if (input.Description.Length > 10) { return this.Error("Description must have only 10 characters"); } if (input.Price < 0) { return this.Error("Price must be > 0"); } this._productsService.AddProduct(input.Name, input.ImageUrl, input.Description, input.Price, input.Category, input.Gender); return this.Redirect("/"); } public HttpResponse Details(int id) { if (!this.IsUserLoggedIn()) { return this.Redirect("/Users/Login"); } ProductDetailsModel viewModel = this._productsService.GetDetails(id); return this.View(viewModel); } public HttpResponse Delete(int id) { if (!this.IsUserLoggedIn()) { return this.Redirect("/Users/Login"); } this._productsService.Delete(id); return this.Redirect("/"); } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. namespace FiiiCoin.Models { public class TransactionFeeSetting :BaseModel { private long confirmations; public long Confirmations { get { return confirmations; } set { confirmations = value; OnChanged("Confirmations"); } } private long feePerKB; public long FeePerKB { get { return feePerKB; } set { feePerKB = value; OnChanged("FeePerKB"); } } private bool encrypt; public bool Encrypt { get { return encrypt; } set { encrypt = value; OnChanged("Encrypt"); } } } }
using System.Threading.Tasks; using System.Web.Http; using Appmon.Dashboard.Models; using Newtonsoft.Json; namespace Appmon.Dashboard.Controllers { public class BuildController : ApiController { // GET api/builds public BuildResult Get() { return (BuildResult)JsonConvert.DeserializeObject(DocumentService.GetResult("ErmsBuildsCollection"), typeof(BuildResult)); } // GET api/builds/5 public string Get(int id) { return "value"; } // POST api/builds public void Post() { Task pushBuilds = DocumentService.PushBuilds(); } // PUT api/builds/5 public void Put(int id, [FromBody]string value) { } // DELETE api/builds/5 public void Delete(int id) { // No implemented. } } }
using NUnit.Framework; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Remote; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using OpenQA.Selenium; using OpenQA.Selenium.Interactions; namespace UniteTestProject { [TestFixture] public class TestClass { private RemoteWebDriver driver; [OneTimeSetUp] public void Init() { driver = new ChromeDriver(); driver.Manage().Window.Maximize(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);//new change string url = "https://seoul.universe.local:3344/webappbuilder/apps/2/"; url = "http://dev104.interpret.co.nz/FH-integrated-spatial-planner/"; driver.Navigate().GoToUrl(url); } [Test] public void TestMethod() { var username = HelperUtil.GetVisibilityElement(driver, By.Id("dijit_form_ValidationTextBox_0")); username.SendKeys("godfrey.huang"); var password = HelperUtil.GetVisibilityElement(driver, By.Id("dijit_form_ValidationTextBox_1")); password.SendKeys("gaoxin112233"); var okBtn = HelperUtil.GetVisibilityElement(driver, By.XPath("//span[@widgetid='dijit_form_Button_0']")); okBtn.Click(); var x = HelperUtil.GetVisibilityElement(driver, By.CssSelector("#graphics-conflict_layer circle")); Actions actions = new Actions(driver); // actions.MoveToElement(x, 200, 50).Click().KeyDown(Keys.Shift).ClickAndHold(). // MoveToElement(x, 300, 150).Click().Release().KeyUp(Keys.Shift).Build().Perform(); actions.MoveToElement(x).Click().Perform(); // driver.ExecuteScript("document.querySelector('#graphics-conflict_layer circle').onclick"); // driver.ExecuteScript("document.querySelector('#graphics-conflict_layer circle').onclick()"); // driver.ExecuteScript("document.querySelector('#graphics-conflict_layer circle').click()"); } [OneTimeTearDown] public void Cleanup() { driver.Quit(); } } }
using System; namespace FancyScrollView { public interface IFancyScrollRectContext { Func<(float ScrollSize, float ReuseMargin)> CalculateScrollSize { get; set; } } }
using ND.FluentTaskScheduling.Domain.interfacelayer; using ND.FluentTaskScheduling.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //********************************************************************** // // 文件名称(File Name):RefreshCommandQueueLogRepository.CS // 功能描述(Description): // 作者(Author):Aministrator // 日期(Create Date): 2017-04-11 15:23:40 // // 修改记录(Revision History): // R1: // 修改作者: // 修改日期:2017-04-11 15:23:40 // 修改理由: //********************************************************************** namespace ND.FluentTaskScheduling.Repository { public class RefreshCommandQueueLogRepository : BaseRepository<tb_refreshcommadqueuelog>, IRefreshCommandQueueLogRepository { } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace DrasCommon.HtmlHelpers { public class MethodArgs : Dictionary<string, string> { } public static class DialogHelpers { //private static TagBuilder _builder = new TagBuilder("a"); private static TagBuilder _builder; /// <summary> /// Creates a link that will open a jQuery UI dialog form. /// </summary> /// <param name="htmlHelper"></param> /// <param name="linkText">The inner text of the anchor element</param> /// <param name="title">The title to be displayed in the dialog window</param> /// <param name="contentUrl">The url that will return the content to be loaded into the dialog window</param> /// <param name="cssClass">The CSS class to be applied to the dialog</param> /// <param name="height">Dialog box height</param> /// <param name="width">Dialog box width</param> /// <param name="dialogTitle">Params to be passed to contentUrl</param> /// <returns></returns> public static MvcHtmlString DialogFormLink(this HtmlHelper htmlHelper, string linkText, string title, string contentUrl, string cssClass, MethodArgs args, string height, string width) { BuildFormLink(linkText, title, contentUrl, args); _builder.Attributes.Remove("data-dialog-height"); _builder.Attributes.Remove("data-dialog-width"); _builder.Attributes.Add("data-dialog-height", height); _builder.Attributes.Add("data-dialog-width", width); _builder.AddCssClass(cssClass); return new MvcHtmlString(_builder.ToString()); } public static MvcHtmlString DialogFormLink(this HtmlHelper htmlHelper, string linkText, string title, string contentUrl, string cssClass, MethodArgs args) { BuildFormLink(linkText, title, contentUrl, args); _builder.AddCssClass(cssClass); return new MvcHtmlString(_builder.ToString()); } public static MvcHtmlString DialogFormLink(this HtmlHelper htmlHelper, string linkText, string title, string contentUrl, string cssClass) { BuildFormLink(linkText, title, contentUrl); _builder.AddCssClass(cssClass); return new MvcHtmlString(_builder.ToString()); } public static MvcHtmlString DialogFormLink(this HtmlHelper htmlHelper, string linkText, string title, string contentUrl) { BuildFormLink(linkText, title, contentUrl); return new MvcHtmlString(_builder.ToString()); } private static void BuildFormLink(string linkText, string title, string contentUrl, MethodArgs args = null) { string parmString = string.Empty; int i = 0; //if (!(args == null)) //{ // foreach (var item in args) // { // if (i > 0) // { // parmString += "?"; // parmString += item.Key; // parmString += "="; // } // parmString += item.Value; // i++; // } //} if (!(args == null)) { foreach (var item in args) { if (i > 0) { // 1st argument if(i==1) { parmString += "?"; } // 2nd, 3rd, ..., nth arguments if(i>1) { parmString += "&"; } parmString += item.Key; parmString += "="; } parmString += item.Value; i++; } } if (!string.IsNullOrEmpty(parmString)) contentUrl = contentUrl + "/" + parmString; _builder = new TagBuilder("a"); _builder.SetInnerText(linkText); _builder.Attributes.Add("href", contentUrl); _builder.Attributes.Add("title", title); _builder.Attributes.Add("data-dialog-title", title); // set height and width default values _builder.Attributes.Add("data-dialog-height", "400"); _builder.Attributes.Add("data-dialog-width", "750"); // css class to identify link and to wire up jQuery functions _builder.AddCssClass("dialogLink"); } public static MvcHtmlString DialogOKLink(this HtmlHelper htmlHelper, string linkText, string title, string contentUrl, MethodArgs args) { BuildOKLink(linkText, title, contentUrl, args); return new MvcHtmlString(_builder.ToString()); } private static void BuildOKLink(string linkText, string title, string contentUrl, MethodArgs args = null) { string parmString = string.Empty; int i = 0; if (!(args == null)) { foreach (var item in args) { if (i > 0) { // 1st argument if (i == 1) { parmString += "?"; } // 2nd, 3rd, ..., nth arguments if (i > 1) { parmString += "&"; } parmString += item.Key; parmString += "="; } parmString += item.Value; i++; } } if (!string.IsNullOrEmpty(parmString)) contentUrl = contentUrl + "/" + parmString; _builder = new TagBuilder("a"); _builder.SetInnerText(linkText); _builder.Attributes.Add("href", contentUrl); _builder.Attributes.Add("title", title); _builder.Attributes.Add("data-dialog-title", title); // set height and width default values _builder.Attributes.Add("data-dialog-height", "600"); _builder.Attributes.Add("data-dialog-width", "600"); // css class to identify link and to wire up jQuery functions _builder.AddCssClass("dialogOKLink"); } } }
using System; using System.Collections.Generic; using System.IO; using FubuMVC.Core.Runtime.Files; using NUnit.Framework; using FubuCore; using System.Linq; using FubuTestingSupport; namespace FubuMVC.CodeSnippets.Testing { [TestFixture] public class CLanguageSnippetFinderTester { private List<Snippet> theSnippets; [SetUp] public void SetUp() { theSnippets = new List<Snippet>(); } private void scan(string text) { var file = new FakeFubuFile(text); var reader = new SnippetReader(file, new CLangSnippetScanner("cs"), theSnippets.Add); reader.Start(); } [Test] public void determine_name() { var scanner = new CLangSnippetScanner("cs"); scanner.DetermineName("// SAMPLE: States").ShouldEqual("States"); scanner.DetermineName(" // SAMPLE: States").ShouldEqual("States"); scanner.DetermineName(" // SAMPLE: States").ShouldEqual("States"); scanner.DetermineName("Texas").ShouldBeNull(); scanner.DetermineName("SAMPLE:").ShouldBeNull(); } [Test] public void is_at_end() { var scanner = new CLangSnippetScanner("cs"); scanner.IsAtEnd("// ENDSAMPLE").ShouldBeTrue(); scanner.IsAtEnd("// SAMPLE: States").ShouldBeFalse(); scanner.IsAtEnd("Texas").ShouldBeFalse(); scanner.IsAtEnd("ENDSAMPLE").ShouldBeFalse(); scanner.IsAtEnd("// Something else").ShouldBeFalse(); } [Test] public void find_easy() { scan(@" foo bar Missouri Kansas // SAMPLE: States Texas Arkansas Oklahoma Wisconsin // ENDSAMPLE Connecticut New York "); var snippet = theSnippets.Single(); snippet.Name.ShouldEqual("States"); snippet.Text.TrimEnd().ShouldEqual(@"Texas{0}Arkansas{0}Oklahoma{0}Wisconsin".ToFormat(Environment.NewLine)); snippet.Start.ShouldEqual(7); snippet.End.ShouldEqual(10); snippet.Class.ShouldEqual("lang-cs"); } [Test] public void find_multiples() { scan(@" foo bar Missouri Kansas // SAMPLE: States Texas Arkansas Oklahoma Wisconsin // ENDSAMPLE Connecticut New York // SAMPLE: Names Jeremy Jessica Natalie Max Lindsey // ENDSAMPLE "); var snippet1 = theSnippets.First(); snippet1.Name.ShouldEqual("States"); snippet1.Text.TrimEnd().ShouldEqual(@"Texas{0}Arkansas{0}Oklahoma{0}Wisconsin".ToFormat(Environment.NewLine)); snippet1.Start.ShouldEqual(7); snippet1.End.ShouldEqual(10); var snippet2 = theSnippets.Last(); snippet2.Name.ShouldEqual("Names"); snippet2.Start.ShouldEqual(16); snippet2.End.ShouldEqual(20); snippet2.Text.ShouldEqual(@"Jeremy{0}Jessica{0}Natalie{0}Max{0}Lindsey{0}".ToFormat(Environment.NewLine).TrimStart()); } } public class FakeFubuFile : IFubuFile { private readonly StringWriter _writer = new StringWriter(); public FakeFubuFile() { } public FakeFubuFile(string text) { _writer.WriteLine(text.Trim()); } public void Append(string text) { _writer.WriteLine(text); } public string ReadContents() { return _writer.ToString(); } public void ReadContents(Action<Stream> action) { throw new NotImplementedException(); } public void ReadLines(Action<string> read) { _writer.ToString().ReadLines(read); } public long Length() { throw new NotImplementedException(); } public string Etag() { throw new NotImplementedException(); } public DateTime LastModified() { throw new NotImplementedException(); } public string Path { get; set; } public string Provenance { get { return "TheApp"; } } public string ProvenancePath { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public string RelativePath { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms; namespace ParPorApp.Helpers { public class FontAwesomeLabel : Label { public FontAwesomeLabel() { FontFamily = Device.OnPlatform(null, "FontAwesome", "/Assets/Fonts/fontawesome-webfont.ttf#FontAwesome"); } } }
using HCBot.Runner.Menu; using HCBot.Runner.States; using System; using System.Collections.Generic; using System.Text; using Telegram.Bot; using Telegram.Bot.Types; namespace HCBot.Runner.Commands { public interface ICommand { BotMenuItem Position { get; set; } IServiceProvider ServiceProvider { get; set; } void ExecuteCommand(ITelegramBotClient bot, Chat chat, UserStateBag user); } }
namespace ServiceDesk.Ticketing.Domain.CategoryAggregate { public interface ICategoryRepository: IRepository<Category> { Category GetByName(string name); } }
#region License //*****************************************************************************/ // Copyright (c) 2012 Luigi Grilli // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. //*****************************************************************************/ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using ByteArray = Grillisoft.ImmutableArray.ImmutableArray<byte>; namespace Grillisoft.FastCgi.Protocol { public struct MessageHeader { /// <summary> /// Record header size in bytes /// </summary> public const ushort HeaderSize = Consts.ChunkSize; /// <summary> /// FastCGI version number /// </summary> public byte Version; /// <summary> /// Record type /// </summary> public MessageType MessageType; /// <summary> /// Request ID /// </summary> public ushort RequestId; /// <summary> /// Content length /// </summary> public ushort ContentLength; /// <summary> /// Length of record padding /// </summary> public byte PaddingLength; /// <summary> /// Reseved for future use and header padding /// </summary> public byte Reserved; public MessageHeader(MessageType messageType, ushort requestId, ushort contentLength) { Version = Consts.Version; MessageType = messageType; RequestId = requestId; ContentLength = contentLength; PaddingLength = CalculatePadding(contentLength); Reserved = 0x00; } public MessageHeader(ByteArray array) : this(array.ToArray(0, HeaderSize)) { } public MessageHeader(byte[] header) : this(header, 0) { } public MessageHeader(byte[] header, int startIndex) { Version = header[startIndex + 0]; MessageType = (MessageType)header[startIndex + 1]; RequestId = Utils.ReadUint16(header, startIndex + 2); ContentLength = Utils.ReadUint16(header, startIndex + 4); PaddingLength = header[startIndex + 6]; Reserved = header[startIndex + 7]; } public RecordType RecordType { get { return (this.RequestId == 0) ? RecordType.Management : RecordType.Application; } } /// <summary> /// Size of the entire message complete with header, content and padding /// </summary> public int MessageSize { get { return HeaderSize + this.ContentLength + this.PaddingLength; } } public void CopyTo(byte[] dest) { this.CopyTo(dest, 0); } public void CopyTo(byte[] header, int startIndex) { header[startIndex + 0] = Version; header[startIndex + 1] = (byte) MessageType; header[startIndex + 2] = (byte) ((RequestId >> 8) & 0xFF); header[startIndex + 3] = (byte) (RequestId & 0xFF); header[startIndex + 4] = (byte) ((ContentLength >> 8) & 0xFF); header[startIndex + 5] = (byte) (ContentLength & 0xFF); header[startIndex + 6] = PaddingLength; header[startIndex + 7] = Reserved; } public byte[] ToArray() { var ret = new byte[HeaderSize]; this.CopyTo(ret); return ret; } private static byte CalculatePadding(ushort contentLength) { if (contentLength % Consts.ChunkSize == 0) return 0; return (byte)(Consts.ChunkSize - (contentLength % Consts.ChunkSize)); } } }
/*************************************** * * Body for Objects that uses Spine Animation * ***************************************/ using Spine.Unity; using UnityEngine; namespace DChild.Gameplay.Objects { [System.Serializable] public struct SpineTimeHandler { [SerializeField][HideInInspector] private SkeletonAnimation m_spineAnimation; public SpineTimeHandler(SkeletonAnimation m_spineAnimation) { this.m_spineAnimation = m_spineAnimation; } public void ChangeTimeScale(float timeScale) => m_spineAnimation.timeScale = timeScale; } }
namespace Krafteq.ElsterModel { using System; using LanguageExt; using static LanguageExt.Prelude; public class KzFieldValidationRule { bool required; int? lessThan; Func<KzFieldSet, int, Lst<KzFieldError>> custom; KzFieldValidationRule(){} public static KzFieldValidationRule Required() => new KzFieldValidationRule { required = true }; public static KzFieldValidationRule LessThan(int fieldNumber) => new KzFieldValidationRule {lessThan = fieldNumber}; public static KzFieldValidationRule Custom(Func<KzFieldSet, int, Lst<KzFieldError>> validateFunc) => new KzFieldValidationRule {custom = validateFunc}; public Lst<KzFieldError> Validate(KzFieldSet fieldSet, int fieldNumber) { if (this.required) { return fieldSet.GetValue(fieldNumber) .Match(some => Lst<KzFieldError>.Empty, () => Prelude.List(KzFieldError.Required)); } if (this.lessThan != null) { var comparedField = fieldSet.GetValue(this.lessThan.Value); var currentField = fieldSet.GetValue(fieldNumber); var comparedValue = comparedField .Map(x => x.GetDecimalValue()) .IfNone(0); return toList(currentField .Map(value => value.GetDecimalValue()) .Match( value => Math.Abs(value) >= Math.Abs(comparedValue) && value != 0m ? Some(KzFieldError.MustBeLessThanAnotherField(this.lessThan.Value)) : None, () => comparedField.Match( Some: _ => Some(KzFieldError.Required), None: () => None ))); } if (this.custom != null) { return this.custom(fieldSet, fieldNumber); } throw new InvalidOperationException(); } } }
using System; namespace AutoTests.Framework.Core.Exceptions { public class ConstraintException : Exception { public ConstraintException(string message) : base(message) { } } }
using System; using System.Threading; using Autofac; using Tests.Pages.Van.LogIn; using Tests.Pages.Van.Main; using Tests.Pages.Van.Main.CommitteePages; using NUnit.Framework; using Tests.Data.Van; namespace Tests.Projects.Van.CatalistDataSync { public class SyncResponsesForNewOrNewlySharedActivistCodesByDefault : BaseTest { /// <summary> /// Logs in as a user and go to its committeeDetails page, verifies the Catalist Data Sync check boxes are checked /// Goes to ActivistCodeDetails page and share an AC to CatalistTestCommittee3, verifies the AC also shows up on Synced with Catalist terry box along with Committee access terry box /// Goes back to CommiteeDetails page, removes the AC and verifies the removed AC shows up on the Catalist Data Sync -AC, not synced with catalist terry box /// </summary> [Test] [Category("van"), Category("van_CatalistDataSync"), Category("van_smoketest")] public void SyncResponsesForNewOrNewlySharedActivistCodesByDefaultTest() { const string clientId = "afl"; const string committeeID = "EIDD3CBL"; const string activistCodeID = "EID3D1414B"; var user = new VanTestUser { UserName = "SajAutotestAfl2", Password = "numero2dos", CommitteeId = "Catalist Testing Committee3", PinCode = "1212" }; //Login as user SajAutotestAfl and go to Committee Details Page by using the committeeID var login = Scope.Resolve<Func<string, LoginPage>>()(clientId); login.Login(user); var committeeDetails = Scope.Resolve<CommitteeDetailsPage>(); committeeDetails.GoToThisPage(committeeID); committeeDetails.VerifyCatalistDataSyncCheckBoxesAreChecked(); //go to ActivistCodeDetails page and move the Catalist Testing Committee3 to Committees With Access terry box and verifies Catalist Testing Committee3 also shows up on //Committees synced with Catalist terry box var activistCodeDetails = Scope.Resolve<ActivistCodeDetailsPage>(); activistCodeDetails.GoToThisPage(activistCodeID); activistCodeDetails.GiveAccessToCommittee("Catalist Testing Committee3"); activistCodeDetails.VerifyCommSyncedWithCatalistTerryBoxDisplaysCorrectCommittees(); //Go to committeeDetails Page to verify the Activist Code we just gave access to Committees shows up on Activist Codes with Access and Catalist Data Sync // -Activist Codes - synced with Catalist terry box, Removes the Catalist Testing Committee3 from the Activist Code with access terry box and verifies the //committee got removed from Catalist Data Sync - Synced with Catalist terry box activistCodeDetails.GoToCommitteeDetailsPage(committeeID); committeeDetails.RemoveActivistCodeAccess("Registration: AC303 (Public)"); committeeDetails.VerifyCommWithoutAccessDisplaysOnNotSyncedWithCatalistAcTerryBox(); } } }
using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.Data.People.Cities.Domain.Enums { /// <summary> /// 城市线分类 /// </summary> public enum CityLineType { /// <summary> /// 一线城市 /// </summary> [LabelCssClass(BadgeColorCalss.Metal)] [Display(Name = "一线城市")] One = 1, /// <summary> /// 一线城市 /// </summary> [LabelCssClass(BadgeColorCalss.Metal)] [Display(Name = "二线城市")] Two = 2, /// <summary> /// 一线城市 /// </summary> [LabelCssClass(BadgeColorCalss.Metal)] [Display(Name = "三线城市")] Three = 3, /// <summary> /// 一线城市 /// </summary> [LabelCssClass(BadgeColorCalss.Metal)] [Display(Name = "四线城市")] Four = 4, } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Navigation; namespace Restaurant.View { public partial class CheckView : Page { List<String> orders = new List<String>(); List<String> products = new List<String>(); bool zmianaStolika = false; public CheckView() { InitializeComponent(); orders.Add("Ilosc Nazwa Wartosc"); orders.Add("12 Mewy 12$"); products.Add("1\tabb"); products.Add("12\tCljaaaa"); this.listBox1.ItemsSource = orders; this.listBox2.ItemsSource = products; } private void zmien_Click(Object sender, System.Windows.RoutedEventArgs e) { if (!zmianaStolika) { ((TextBox)(((Button)sender).FindName("textBoxZmienStolik"))).Text = (String)((Label)(((Button)sender).FindName("labelStol"))).Content; ((TextBox)(((Button)sender).FindName("textBoxZmienStolik"))).Visibility = Visibility.Visible; } else { ((TextBox)(((Button)sender).FindName("textBoxZmienStolik"))).Visibility = Visibility.Collapsed; int a = Convert.ToInt32(((TextBox)(((Button)sender).FindName("textBoxZmienStolik"))).Text); ((Label)(((Button)sender).FindName("labelStol"))).Content = Convert.ToString(a); } zmianaStolika = !zmianaStolika; } private void dodaj_Click(Object sender, System.Windows.RoutedEventArgs e) { } // Executes when the user navigates to this page. protected override void OnNavigatedTo(NavigationEventArgs e) { } } }
using System; using SQLite; using SQLitePCL; namespace ICT13580010A2.Models { public class Product { [PrimaryKey, AutoIncrement] public int Id{get;set;} [NotNull] [MaxLength(200)] public String Name{get;set;} public string Description{get;set;} [NotNull] [MaxLength(100)] public string Category{get;set;} public decimal ProductPrice { get; set; } public decimal SellPrize { get; set; } public int Stock { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using CEMAPI.Models; using Newtonsoft.Json.Linq; using System.Net.Http; namespace CEMAPI.DAL { public class GeneralNotesDAL { TETechuvaDBContext context = new TETechuvaDBContext(); RecordExceptions exception = new RecordExceptions(); FailInfo finfo = new FailInfo(); SuccessInfo sinfo = new SuccessInfo(); HttpResponseMessage hrm = new HttpResponseMessage(); public GeneralNotesDAL() { context.Configuration.ProxyCreationEnabled = false; } public bool SaveGeneralNotes(TEGenaralNote teGeneralNote, int? authUser) { FailInfo finfo = new FailInfo(); SuccessInfo sinfo = new SuccessInfo(); HttpResponseMessage hrm = new HttpResponseMessage(); bool result = true; TEGenaralNote teGeneral = new TEGenaralNote(); try { teGeneral.ReferenceID = teGeneralNote.ReferenceID; teGeneral.ModuleName = teGeneralNote.ModuleName; teGeneral.Notes = teGeneralNote.Notes; teGeneral.IsDeleted = false; teGeneral.LastModifiedByID = authUser; teGeneral.LastModifiedDate = DateTime.Now; context.TEGenaralNotes.Add(teGeneral); context.SaveChanges(); } catch (Exception ex) { exception.RecordUnHandledException(ex); result = false; } return result; } public bool UpdateGeneralNotes(TEGenaralNote teGeneralNote, int? authUser) { bool result = false; try { TEGenaralNote genNote = new TEGenaralNote(); genNote = context.TEGenaralNotes.Where(a => a.NotesID == teGeneralNote.NotesID && a.ReferenceID == teGeneralNote.ReferenceID && a.ModuleName == teGeneralNote.ModuleName).FirstOrDefault(); genNote.Notes = teGeneralNote.Notes; genNote.LastModifiedByID = authUser; genNote.LastModifiedDate = DateTime.Now; context.Entry(genNote).CurrentValues.SetValues(genNote); context.SaveChanges(); result = true; } catch (Exception ex) { result = false; exception.RecordUnHandledException(ex); } return result; } public bool DeleteGeneralNotes(int? notesID, int? authUser) { bool result = true; try { TEGenaralNote teGeneralNote = new TEGenaralNote(); teGeneralNote = context.TEGenaralNotes.Where(a => a.NotesID == notesID).FirstOrDefault(); teGeneralNote.IsDeleted = true; teGeneralNote.LastModifiedByID = authUser; teGeneralNote.LastModifiedDate = DateTime.Now; context.Entry(teGeneralNote).CurrentValues.SetValues(teGeneralNote); context.SaveChanges(); int? noteID = 0; noteID = teGeneralNote.NotesID; result = noteID > 0 ? true : false; } catch (Exception ex) { result = false; exception.RecordUnHandledException(ex); } return result; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PointController : MonoBehaviour { public GameObject player; float minX = -5f; float maxX = 5f; float minY = -3.7f; float maxY = 3.7f; // Use this for initialization void Start () { Reposition(); } public void Reposition() { //Debug.Log(gameObject.tag); if (player == null) { player = GameObject.FindGameObjectWithTag("Player"); } Vector2 newPosition = player.transform.position; while (Mathf.Sqrt(Mathf.Pow(newPosition.x - player.transform.position.x, 2) + Mathf.Pow(newPosition.y - player.transform.position.y, 2)) < 4.5f) { newPosition = new Vector2(Random.Range(minX, maxX), Random.Range(minY, maxY)); } transform.position = newPosition; } public void SetIsWorthPoint(bool worth) { if (worth) { gameObject.tag = "Point"; } else { gameObject.tag = "ShieldPoint"; } } public bool GetIsWorthPoint() { return gameObject.tag.Equals("Point"); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class paddlehit : MonoBehaviour { private AudioSource paddleSound; // Use this for initialization void Start () { paddleSound = this.GetComponent<AudioSource>(); } // Update is called once per frame void Update () { } private void OnCollisionEnter(Collision collision) { if (collision.collider.name == "Ball") { // play the sound paddleSound.Play(); } } }
using BankAppCore.Data.EFContext; using Microsoft.AspNet.Identity; using System; using static BankAppCore.Data.EFContext.EFContext; /* namespace BankAppCore.Data.Repositories { public class UnitOfWork : IDisposable { private ShopContext context; private UserManager<ApplicationUser> userManager; private AccountRepository accountRepository; private BillRepository billRepository; private ClientRepository clientRepository; private UserActionLogRepository userActionLogRepository; private ApplicationUserRepository applicationUserRepository; public UnitOfWork(ShopContext context, UserManager<ApplicationUser> userManager) { this.context = context; this.userManager = userManager; } public AccountRepository AccountRepository { get { if (this.accountRepository == null) { this.accountRepository = new AccountRepository(context); } return accountRepository; } } public BillRepository BillRepository { get { if (this.billRepository == null) { this.billRepository = new BillRepository(context); } return billRepository; } } public ClientRepository ClientRepository { get { if (this.clientRepository == null) { this.clientRepository = new ClientRepository(context); } return clientRepository; } } public UserActionLogRepository UserActionLogRepository { get { if (this.userActionLogRepository == null) { this.userActionLogRepository = new UserActionLogRepository(context); } return userActionLogRepository; } } public ApplicationUserRepository ApplicationUserRepository { get { if (this.applicationUserRepository == null) { this.applicationUserRepository = new ApplicationUserRepository(context); } return applicationUserRepository; } } private bool disposed = false; protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { context.Dispose(); } } this.disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } } }*/