text
stringlengths
13
6.01M
using System; using System.Web.Mvc; using IBLLService; using ShengUI.Helper; using Common; using System.Text; using MODEL; using MODEL.ViewModel; using Senparc.Weixin.MP.TenPayLib; using System.Xml; using ShengUI.Helper.payCls; using System.Collections.Generic; namespace ShengUI.Logic { [HandleError] public class AoShaCarController : BaseController { ITokenConfig_MANAGER token = OperateContext.Current.BLLSession.ITokenConfig_MANAGER; IYX_sysConfigs_MANAGER sysConfigs = OperateContext.Current.BLLSession.IYX_sysConfigs_MANAGER; ITG_review_MANAGER proreviewManager = OperateContext.Current.BLLSession.ITG_review_MANAGER; IYX_weiUser_MANAGER weiUserM = OperateContext.Current.BLLSession.IYX_weiUser_MANAGER; IMST_SUPPLIER_MANAGER supplierB = OperateContext.Current.BLLSession.IMST_SUPPLIER_MANAGER; IMST_CATEGORY_MANAGER categoryB = OperateContext.Current.BLLSession.IMST_CATEGORY_MANAGER; IMST_PRD_MANAGER prdB = OperateContext.Current.BLLSession.IMST_PRD_MANAGER; IMST_PRD_IMG_MANAGER prdimgB = OperateContext.Current.BLLSession.IMST_PRD_IMG_MANAGER; ISYS_REF_MANAGER sysrefB = OperateContext.Current.BLLSession.ISYS_REF_MANAGER; ITG_order_MANAGER orderB = OperateContext.Current.BLLSession.ITG_order_MANAGER; ITG_transactionLog_MANAGER transactionlogB = OperateContext.Current.BLLSession.ITG_transactionLog_MANAGER; public string JssdkSignature = ""; public string noncestr = ""; public string shareInfo = ""; public string timestamp = ""; public string openid = ""; public string userid = ""; //支付参数 public string sj = "";//随机串 public string PaySign = "";//签名 public string Package = ""; public string payTimeSamp = "";//生成签名的时间戳 public string isok = "NO"; public ActionResult UserMain() { ViewBag.PageFlag = "UserMain"; ViewBag.isok = "OK"; ViewBag.Appid = WeChatConfig.GetKeyValue("appid"); ViewBag.Uri = WeChatConfig.GetKeyValue("shareurl"); noncestr = CommonMethod.GetCode(16); string jsapi_ticket = Js_sdk_Signature.IsExistjsapi_ticket(token.IsExistAccess_Token()); timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10); ; string url = Request.Url.ToString().Replace("#", ""); JssdkSignature = Js_sdk_Signature.GetjsSDK_Signature(noncestr, jsapi_ticket, timestamp, url); ViewBag.noncestr = noncestr; ViewBag.jsapi_ticket = jsapi_ticket; ViewBag.timestamp = timestamp; openid = CommonMethod.getCookie("openid"); userid = CommonMethod.getCookie("userid"); if (string.IsNullOrEmpty(openid)) { //根据授权 获取openid //根据授权 获取用户的openid string code = Request.QueryString["code"];//获取授权code LogHelper.WriteLog("//////////////////////////////////////////////////////////////////////////////////"); LogHelper.WriteLog("code:" + code); if (string.IsNullOrEmpty(code)) { string codeurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx242aa47391c159f6&redirect_uri=http://www.aoshacar.com/AoShaCar/userMain&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"; Response.Redirect(codeurl); } else { string openIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WeChatConfig.GetKeyValue("appid") + "&secret=" + WeChatConfig.GetKeyValue("appsecret") + "&code=" + code + "&grant_type=authorization_code"; string content = Tools.GetPage(openIdUrl, ""); openid = Tools.GetJsonValue(content, "openid");//根据授权 获取当前人的openid } } var model = VIEW_YX_weiUser.ToViewModel(weiUserM.GetModelWithOutTrace(u => u.openid == openid)); if (model != null) { CommonMethod.delCookie("openid"); CommonMethod.delCookie("userid"); CommonMethod.setCookie("openid", openid, 1); CommonMethod.setCookie("userid", model.userNum, 1); ViewBag.nickname = model.nickname; ViewBag.headimgurl = model.headimgurl; } else { Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson dic = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(token.IsExistAccess_Token(), openid); //LogHelper.WriteLog("XXXXXXXXXXX:" + openid); if (dic != null) { ViewBag.nickname = dic.nickname; ViewBag.headimgurl = dic.headimgurl; } model = new MODEL.ViewModel.VIEW_YX_weiUser(); model.subscribe = dic.subscribe; model.openid = dic.openid; model.nickname = dic.nickname; model.sex = dic.sex; model.U_language = dic.language; model.city = dic.city; model.province = dic.province; model.country = dic.country; model.headimgurl = dic.headimgurl; model.subscribe_time = DateTime.Now; model.userSex = dic.sex == 2 ? "女" : "男"; model.userNum = Common.Tools.Get8Digits(); model.F_id = 0; model.isfenxiao = 0; model.userMoney = 0; model.userYongJin = 0; weiUserM.Add(VIEW_YX_weiUser.ToEntity(model)); } ViewBag.UserType= ConfigSettings.GetSysConfigValue("USERTYPE", model.isfenxiao.ToString()); return View(model); } public ActionResult Index() { ViewBag.PageFlag = "Index"; if (string.IsNullOrEmpty(CommonMethod.getCookie("userid")) || string.IsNullOrEmpty(CommonMethod.getCookie("openid"))) { //CommonMethod.delCookie("userid"); //登陆 string code = Request.QueryString["code"];//获取授权code if (!string.IsNullOrEmpty(code)) { string openIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WeChatConfig.GetKeyValue("appid") + "&secret=" + WeChatConfig.GetKeyValue("appsecret") + "&code=" + code + "&grant_type=authorization_code"; string content = Tools.GetPage(openIdUrl, ""); openid = Tools.GetJsonValue(content, "openid");//根据授权 获取当前人的openid var model = weiUserM.GetModelWithOutTrace(u => u.openid == openid); if (model != null) { CommonMethod.delCookie("openid"); CommonMethod.delCookie("userid"); CommonMethod.setCookie("openid", openid, 1); CommonMethod.setCookie("userid", model.userNum, 1); } } else { string codeurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx242aa47391c159f6&redirect_uri=http://www.aoshacar.com/AoShaCar/Index&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"; Response.Redirect(codeurl); } //end } ViewBag.PageFlag = "Index"; var sid = TypeParser.ToInt32(Request["sid"]); if (sid <= 0) sid = 2; ViewBag.SupplierID = sid; ViewBag.SupplierName = supplierB.Get(s => s.SUPPLIER_ID == sid).SUPPLIER_NAME; ViewBag.CategoryList = VIEW_MST_CATEGORY.ToListViewModel(categoryB.GetListBy(c => c.ACTIVE == true)); ViewBag.ProductList = VIEW_MST_PRD.ToListViewModel(prdB.GetListBy(p => p.ISCHECK == true && p.STATUS == true && p.ISHOT == true, p => p.SEQ_NO)); return View(); } public ActionResult CompanyList() { ViewBag.PageFlag = "CompanyList"; ViewBag.SupplierList = VIEW_MST_SUPPLIER.ToListViewModel(supplierB.GetListBy(s => s.SYNCOPERATION!="D")); return View(); } public ActionResult OrderList() { ViewBag.PageFlag = "OrderList"; var status = false; var userid = CommonMethod.getCookie("userid"); var openid = CommonMethod.getCookie("openid"); if (string.IsNullOrEmpty(userid) || string.IsNullOrEmpty(openid)) { return Content("对不起,请登陆系统!"); } ViewBag.OrderList = VIEW_TG_order.ToListViewModel(orderB.GetListBy(s => s.UserId == userid && s.userOpenId == openid && s.trade_type == "ONLINE"&&s.SYNCOPERATION!="D", o => o.orderTime, false)); return View(); } public ActionResult ReservationList() { ViewBag.PageFlag = "ReservationList"; var status = false; var userid = CommonMethod.getCookie("userid"); var openid = CommonMethod.getCookie("openid"); if (string.IsNullOrEmpty(userid) || string.IsNullOrEmpty(openid)) { return Content("对不起,请登陆系统!"); } ViewBag.OrderList = VIEW_TG_order.ToListViewModel(orderB.GetListBy(s => s.UserId == userid && s.userOpenId == openid && s.trade_type == "JSAPI" && s.SYNCOPERATION != "D", o => o.orderTime, false)); return View(); } public ActionResult Category(string id) { ViewBag.isok = "OK"; ViewBag.Appid = WeChatConfig.GetKeyValue("appid"); ViewBag.Uri = WeChatConfig.GetKeyValue("shareurl"); noncestr = CommonMethod.GetCode(16); string jsapi_ticket = Js_sdk_Signature.IsExistjsapi_ticket(token.IsExistAccess_Token()); timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10); ; string url = Request.Url.ToString().Replace("#", ""); JssdkSignature = Js_sdk_Signature.GetjsSDK_Signature(noncestr, jsapi_ticket, timestamp, url); ViewBag.noncestr = noncestr; ViewBag.jsapi_ticket = jsapi_ticket; ViewBag.timestamp = timestamp; ViewBag.JssdkSignature = JssdkSignature; ViewBag.PageFlag = id; var sid = TypeParser.ToInt32(Request["sid"]); if (sid <= 0) sid = 2; ViewBag.SupplierID = sid; ViewBag.SupplierName = supplierB.Get(s => s.SUPPLIER_ID == sid).SUPPLIER_NAME; ViewBag.ProductList = VIEW_MST_PRD.ToListViewModel(prdB.GetListBy(p => p.CATE_ID == id && p.STATUS == true && p.ISCHECK == true, p => p.SEQ_NO)); var model = VIEW_MST_CATEGORY.ToViewModel(categoryB.Get(c => c.CATE_CD == id)); return View(model); } public ActionResult CheckTime() { var pid = Request["pid"]; var model = VIEW_MST_PRD.ToViewModel(prdB.Get(p => p.PRD_CD == pid)); var sid = Request["pid"]; var Time = sysrefB.GetListBy(s => s.REF_TYPE == model.CATE_ID, s => s.REF_SEQ); return this.JsonFormat(Time, true, SysOperate.Load); } public ActionResult ProductDetail(string id) { ViewBag.Appid = WeChatConfig.GetKeyValue("appid"); ViewBag.Uri = WeChatConfig.GetKeyValue("shareurl"); noncestr = CommonMethod.GetCode(16); string jsapi_ticket = Js_sdk_Signature.IsExistjsapi_ticket(token.IsExistAccess_Token()); timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10); ; string url = Request.Url.ToString().Replace("#", ""); JssdkSignature = Js_sdk_Signature.GetjsSDK_Signature(noncestr, jsapi_ticket, timestamp, url); ViewBag.noncestr = noncestr; ViewBag.jsapi_ticket = jsapi_ticket; ViewBag.timestamp = timestamp; ViewBag.JssdkSignature = JssdkSignature; var userid = CommonMethod.getCookie("userid"); var openid = CommonMethod.getCookie("openid"); ViewBag.userName = ""; ViewBag.userTel = ""; if (!string.IsNullOrEmpty(userid) && !string.IsNullOrEmpty(openid)) { var user = VIEW_YX_weiUser.ToViewModel(weiUserM.GetModelWithOutTrace(u => u.openid == openid)); if (user != null) { ViewBag.userName = user.userRelname; ViewBag.userTel = user.userTel; } } var sid = TypeParser.ToInt32(Request["sid"]); if (sid <= 0) sid = 2; ViewBag.SupplierID = sid; var supplier = supplierB.Get(s => s.SUPPLIER_ID == sid); ViewBag.SupplierName = supplier.SUPPLIER_NAME; ViewBag.Address = supplier.ADDRESS; ViewBag.Tel = supplier.TEL; var model = VIEW_MST_PRD.ToViewModel(prdB.Get(p => p.PRD_CD == id)); ViewBag.ImgList = VIEW_MST_PRD_IMG.ToListViewModel(prdimgB.GetListBy(pm => pm.PRD_CD == id)); ViewBag.AM = sysrefB.GetListBy(s => s.REF_TYPE == model.CATE_ID && s.REF_PARAM.Contains("AM_"), s => s.REF_SEQ); ViewBag.PM = sysrefB.GetListBy(s => s.REF_TYPE == model.CATE_ID && s.REF_PARAM.Contains("PM_"), s => s.REF_SEQ); ViewBag.PageFlag = model.CATE_ID; return View(model); } public ActionResult SubmitOrder() { var status = false; var openid = CommonMethod.getCookie("openid"); var userid = CommonMethod.getCookie("userid"); if (string.IsNullOrEmpty(userid) || string.IsNullOrEmpty(openid)) { return this.JsonFormat(status, status, "对不起,请登陆系统!"); } string orderNum = CommonMethod.GetOrderNum();//订单号 string ThingNum = Request.Form["thingNum"];//CommonMethod.GetCode(18);//流水号; string thingName = Request.Form["thingName"]; string sid = Request.Form["sid"]; string suppliername = Request.Form["suppliername"]; string uname = Request.Form["uname"]; string mobile = Request.Form["mobile"]; string currentselectdate = Request.Form["selectdate"]; string currentselecttime = Request.Form["selecttime"]; string thingPrice = Request.Form["thingPrice"];//总金额 string thingFrontPrice = Request.Form["thingFrontPrice"];//预付 string supplieraddress = Request.Form["supplieraddress"];//地址Id string trade_type = "JSAPI"; var order = new VIEW_TG_order(); order.orderNum = orderNum; order.ThingNum = ThingNum; order.remark1 = thingName; order.userOpenId = openid; order.UserId = userid; order.userName = uname; order.UserTel = mobile; order.UserAddress = supplieraddress; order.remark2 = suppliername; order.remark3 = sid; order.total_fee = TypeParser.ToDecimal(thingPrice); order.yunPrice = TypeParser.ToDecimal(thingFrontPrice); order.remark4 = currentselectdate; order.remark5 = currentselecttime; order.trade_type = trade_type; order.years = DateTime.Now.Year; order.months = DateTime.Now.Month; order.ispay = 0; order.ssh_status = 0; order.orderTime = DateTime.Now; order.SYNCFLAG = "N"; order.SYNCOPERATION = "A"; order.SYNCVERSION = DateTime.Now; order.VERSION = 1; orderB.Add(VIEW_TG_order.ToEntity(order)); status = true; var user = weiUserM.GetModelWithOutTrace(u => u.openid == openid); if (user != null) { user.RelName = uname; user.userTel = mobile; weiUserM.Modify(user, "RelName", "userTel"); } // string order_sql = "insert into TG_order(flat2,trade_type,orderNum,ThingNum,total_fee,yunPrice,fenxiaoId,UserId,userOpenId,userName,UserTel,UserAddress,UserPostNum,orderTime,remark4,ispay,years,months) values(" + zengsongJifen + ",'" + trade_type + "','" + orderNum + "','" + ThingNum + "'," + total_fee + "," + YunFei + "," + fenxiaoId + "," + userid + ",'" + openid + "','" + userName + "','" + UserTel + "','" + UserAddress + "','" + UserPostNum + "','" + DateTime.Now + "','" + remark4 + "',0," + DateTime.Now.Year + "," + DateTime.Now.Month + ")"; //string thing_sql = "insert into TG_Thing(UserId,openId,ThingNum,orderNum,productId,productCount,productPrice,productMoney,createTim,ispay,remark4) values(" + userid + ",'" + openid + "','" + ThingNum + "','" + orderNum + "'," + pid + "," + productCount + "," + proprice + "," + (productCount * proprice) + ",'" + DateTime.Now + "',0,'" + proColor + "')"; //string car_sql = "delete from TG_car where Pid=" + pid + " and (UserOpenId='" + openid + "' or UserId=" + userid + ")"; return this.JsonFormat(status, status, "/aoshacar/payorder.aspx?orderid=" + orderNum); } public ActionResult OrderDetail(string orderid) { //----- noncestr = CommonMethod.GetCode(16); string jsapi_ticket = Js_sdk_Signature.IsExistjsapi_ticket(WeChatConfig.IsExistAccess_Token2()); timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10); ; string url = Request.Url.ToString().Replace("#", ""); JssdkSignature = Js_sdk_Signature.GetjsSDK_Signature(noncestr, jsapi_ticket, timestamp, url); ViewBag.Appid = WeChatConfig.GetKeyValue("appid"); ViewBag.Uri = WeChatConfig.GetKeyValue("shareurl"); ViewBag.noncestr = noncestr; ViewBag.jsapi_ticket = jsapi_ticket; ViewBag.timestamp = timestamp; ViewBag.PageFlag = "PayOrder"; if (string.IsNullOrEmpty(CommonMethod.getCookie("userid")) || string.IsNullOrEmpty(CommonMethod.getCookie("openid"))) { return Content("对不起,请登陆系统!"); } var order = orderB.Get(o => o.orderNum == orderid); if (order == null) return Content("对不起,这个订单是错误的!"); return View(VIEW_TG_order.ToViewModel(order)); } public ActionResult ROrderDetail(string orderid) { //----- noncestr = CommonMethod.GetCode(16); string jsapi_ticket = Js_sdk_Signature.IsExistjsapi_ticket(WeChatConfig.IsExistAccess_Token2()); timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10); ; string url = Request.Url.ToString().Replace("#", ""); JssdkSignature = Js_sdk_Signature.GetjsSDK_Signature(noncestr, jsapi_ticket, timestamp, url); ViewBag.Appid = WeChatConfig.GetKeyValue("appid"); ViewBag.Uri = WeChatConfig.GetKeyValue("shareurl"); ViewBag.noncestr = noncestr; ViewBag.jsapi_ticket = jsapi_ticket; ViewBag.timestamp = timestamp; ViewBag.PageFlag = "PayOrder"; if (string.IsNullOrEmpty(CommonMethod.getCookie("userid")) || string.IsNullOrEmpty(CommonMethod.getCookie("openid"))) { return Content("对不起,请登陆系统!"); } var order = orderB.Get(o => o.orderNum == orderid); if (order == null) return Content("对不起,这个订单是错误的!"); return View(VIEW_TG_order.ToViewModel(order)); } public ActionResult PayOrder(string orderid) { ViewBag.PageFlag = "PayOrder"; var openid = CommonMethod.getCookie("openid"); var userid = CommonMethod.getCookie("userid"); var user = weiUserM.GetModelWithOutTrace(u => u.userNum == userid && u.openid == openid); if (user==null) { return Content("对不起,请登陆系统!"); } ViewBag.UserType = user.isfenxiao; ViewBag.userYongJin = user.userYongJin; ViewBag.Userid = userid; ViewBag.Openid = openid; var order = orderB.Get(o => o.orderNum == orderid); if (order == null) return Content("对不起,这个订单是错误的!"); //----- noncestr = CommonMethod.GetCode(16); string jsapi_ticket = Js_sdk_Signature.IsExistjsapi_ticket(WeChatConfig.IsExistAccess_Token2()); timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10); ; string url = Request.Url.ToString().Replace("#", ""); JssdkSignature = Js_sdk_Signature.GetjsSDK_Signature(noncestr, jsapi_ticket, timestamp, url); ViewBag.Appid = WeChatConfig.GetKeyValue("appid"); ViewBag.Uri = WeChatConfig.GetKeyValue("shareurl"); ViewBag.noncestr = noncestr; ViewBag.jsapi_ticket = jsapi_ticket; ViewBag.timestamp = timestamp; //微信支付代码 // //httpContext var packageReqHandler = new RequestHandler(HttpContext); packageReqHandler.Init(); //时间戳 payTimeSamp = Senparc.Weixin.MP.TenPayLibV3.TenPayV3Util.GetTimestamp(); //随机字符串 sj = CommonMethod.GetCode(16) + "_" + userid; //设置参数 packageReqHandler.SetParameter("body", "商城-购买支付"); //商品信息 127字符 packageReqHandler.SetParameter("appid", PayConfig.AppId); packageReqHandler.SetParameter("mch_id", PayConfig.MchId); packageReqHandler.SetParameter("nonce_str", sj); packageReqHandler.SetParameter("notify_url", PayConfig.NotifyUrl); packageReqHandler.SetParameter("openid", openid); packageReqHandler.SetParameter("out_trade_no", orderid + "_" + CommonMethod.GetCode(4)); //商家订单号 packageReqHandler.SetParameter("spbill_create_ip", Request.UserHostAddress); //用户的公网ip,不是商户服务器IP packageReqHandler.SetParameter("total_fee", (Convert.ToDouble(order.yunPrice) * 100).ToString()); //商品金额,以分为单位(money * 100).ToString() packageReqHandler.SetParameter("trade_type", "JSAPI"); packageReqHandler.SetParameter("attach", CommonMethod.GetCode(28));//自定义参数 127字符 string sign = packageReqHandler.CreateMd5Sign("key", PayConfig.AppKey);//第一次签名结果 #region 获取package包====================== packageReqHandler.SetParameter("sign", sign); string data = packageReqHandler.ParseXML();//支付发送的数据 XML格式 string prepayXml = Senparc.Weixin.MP.AdvancedAPIs.TenPayV3.Unifiedorder(data); //string prepayXml = WeiXin.GetPage("https://api.mch.weixin.qq.com/pay/unifiedorder", data); var xdoc = new XmlDocument(); xdoc.LoadXml(prepayXml); XmlNode xn = xdoc.SelectSingleNode("xml"); LogHelper.WriteLog(prepayXml); try { string PrepayId = WeChatConfig.GetXMLstrByKey("prepay_id", xdoc); Package = string.Format("prepay_id={0}", PrepayId); LogHelper.WriteLog(Package); } catch (Exception ex) { LogHelper.WriteLog(ex.ToString()); Package = string.Format("prepay_id={0}", ""); } #endregion #region 设置支付参数 输出页面 该部分参数请勿随意修改 ============== var paySignReqHandler = new RequestHandler(HttpContext); paySignReqHandler.SetParameter("appId", PayConfig.AppId); paySignReqHandler.SetParameter("timeStamp", payTimeSamp); paySignReqHandler.SetParameter("nonceStr", sj); paySignReqHandler.SetParameter("package", Package); paySignReqHandler.SetParameter("signType", "MD5"); PaySign = paySignReqHandler.CreateMd5Sign("key", PayConfig.AppKey); #endregion //--------END ViewBag.payTimeSamp = payTimeSamp; ViewBag.sj = sj; ViewBag.Package = Package; ViewBag.PaySign = PaySign; return View(VIEW_TG_order.ToViewModel(order)); } public ActionResult successPay(string ordernum) { var status = false; var openid = CommonMethod.getCookie("openid"); var userid = CommonMethod.getCookie("userid"); var type = Request["paytype"]; var user = weiUserM.GetModelWithOutTrace(u => u.userNum == userid && u.openid == openid); if (user == null) { return Content("对不起,请登陆系统!"); } var order = orderB.GetModelWithOutTrace(o => o.orderNum == ordernum); if (order == null) return Content("对不起,这个订单是错误的!"); if (string.IsNullOrEmpty(type)) { //添加交易记录 TG_transactionLog transactionlog = new TG_transactionLog(); transactionlog.userId = userid; transactionlog.openid = openid; transactionlog.tranCate = 0; transactionlog.CateName = "微信消费"; transactionlog.tranMoney = order.yunPrice; transactionlog.tranContent = "微信消费(订单号:" + ordernum + ")消费:" + order.total_fee + " 元,预付:" + order.yunPrice + " 元"; transactionlog.orderNum = ordernum; transactionlog.remark4 = "1001"; transactionlog.AddTime = DateTime.Now; transactionlogB.Add(transactionlog); YX_sysNews sysnew = new YX_sysNews(); sysnew.userid = userid; sysnew.orderId = ordernum; sysnew.newsCate = "订单提醒"; sysnew.newsContent = "用户微信支付成功"; sysnew.newsState = 0; sysnew.Addtime = DateTime.Now; OperateContext.Current.BLLSession.IYX_sysNews_MANAGER.Add(sysnew); Common.Tools.GetPage("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + WeChatConfig.IsExistAccess_Token2(), WeChatConfig.GetSubcribePostData(openid, transactionlog.tranContent)); } else if (user.isfenxiao >= 1 && user.userYongJin > order.total_fee) { order.ssh_status = 3; order.ispay = 3; order.yunPrice = order.total_fee; order.payTime = DateTime.Now; orderB.Modify(order, "yunPrice", "payTime", "ispay", "ssh_status"); //添加交易记录 TG_transactionLog transactionlog = new TG_transactionLog(); transactionlog.userId = userid; transactionlog.openid = openid; transactionlog.tranCate = 0; transactionlog.CateName = "微信消费"; transactionlog.tranMoney = order.total_fee; transactionlog.tranContent = "会员微信消费(订单号:" + ordernum + ")消费:" + order.total_fee + " 元"; transactionlog.orderNum = ordernum; transactionlog.remark4 = "1002"; transactionlog.AddTime = DateTime.Now; transactionlogB.Add(transactionlog); user.userYongJin = user.userYongJin - order.total_fee; weiUserM.Modify(user, "userYongJin"); YX_sysNews sysnew = new YX_sysNews(); sysnew.userid = userid; sysnew.orderId = ordernum; sysnew.newsCate = "订单提醒"; sysnew.newsContent = "用户微信支付成功"; sysnew.newsState = 0; sysnew.Addtime = DateTime.Now; OperateContext.Current.BLLSession.IYX_sysNews_MANAGER.Add(sysnew); Common.Tools.GetPage("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + WeChatConfig.IsExistAccess_Token2(), WeChatConfig.GetSubcribePostData(openid, transactionlog.tranContent)); } else { } List<string> openids = new List<string>() { "oJUBAv7TVJBowlpJs58qBvCNCrAc", "oJUBAv1jDW_8IQyyvYyTjW2Q6o3w", "oJUBAv9bmEB2mFMSZyLkZBaTK540", "oJUBAv3rjppIvGenkn3h1MIo4wts", "oJUBAv7XiorX2muQXNft5ChU1OCk", "oJUBAv2Omhudt9cyqG_f2A1xMhUA" }; foreach (var item in openids) { Common.Tools.GetPage("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + WeChatConfig.IsExistAccess_Token2(), WeChatConfig.GetSubcribePostData(item, "用户: " + user.userRelname + " 已成功预约。\n预约订单号:" + order.orderNum + "\n预约时间:"+order.remark4+" "+order.remark5+"\n 联系电话:" + user.userTel)); } return Redirect("/aoshacar/OrderDetail?orderid=" + ordernum); } public ActionResult Notify() { MODEL.TG_order order = new TG_order(); LogHelper.WriteLog("XXXXXXXXXXXXXXXX"); //创建ResponseHandler实例 ShengUI.Helper.payCls.ResponseHandler resHandler = new ShengUI.Helper.payCls.ResponseHandler(HttpContext); resHandler.setKey(PayConfig.AppKey); //判断签名 try { string error = ""; if (resHandler.isWXsign(out error)) { #region 协议参数===================================== //--------------协议参数-------------------------------------------------------- //SUCCESS/FAIL此字段是通信标识,非交易标识,交易是否成功需要查 string return_code = resHandler.getParameter("return_code"); //返回信息,如非空,为错误原因签名失败参数格式校验错误 string return_msg = resHandler.getParameter("return_msg"); //微信分配的公众账号 ID string appid = resHandler.getParameter("appid"); //以下字段在 return_code 为 SUCCESS 的时候有返回-------------------------------- //微信支付分配的商户号 string mch_id = resHandler.getParameter("mch_id"); //微信支付分配的终端设备号 string device_info = resHandler.getParameter("device_info"); //微信分配的公众账号 ID string nonce_str = resHandler.getParameter("nonce_str"); //业务结果 SUCCESS/FAIL string result_code = resHandler.getParameter("result_code"); //错误代码 string err_code = resHandler.getParameter("err_code"); //结果信息描述 string err_code_des = resHandler.getParameter("err_code_des"); //以下字段在 return_code 和 result_code 都为 SUCCESS 的时候有返回--------------- //-------------业务参数--------------------------------------------------------- //用户在商户 appid 下的唯一标识 string openid = resHandler.getParameter("openid"); //用户是否关注公众账号,Y-关注,N-未关注,仅在公众账号类型支付有效 string is_subscribe = resHandler.getParameter("is_subscribe"); //JSAPI、NATIVE、MICROPAY、APP string trade_type = resHandler.getParameter("trade_type"); //银行类型,采用字符串类型的银行标识 string bank_type = resHandler.getParameter("bank_type"); //订单总金额,单位为分 string total_fee = resHandler.getParameter("total_fee"); //货币类型,符合 ISO 4217 标准的三位字母代码,默认人民币:CNY string fee_type = resHandler.getParameter("fee_type"); //微信支付订单号 string transaction_id = resHandler.getParameter("transaction_id"); //商户系统的订单号,与请求一致。 string out_trade_no = resHandler.getParameter("out_trade_no"); //商家数据包,原样返回 string attach = resHandler.getParameter("attach"); //支 付 完 成 时 间 , 格 式 为yyyyMMddhhmmss,如 2009 年12 月27日 9点 10分 10 秒表示为 20091227091010。时区为 GMT+8 beijing。该时间取自微信支付服务器 string time_end = resHandler.getParameter("time_end"); #endregion //支付成功 if (!out_trade_no.Equals("") && return_code.Equals("SUCCESS") && result_code.Equals("SUCCESS")) { LogHelper.WriteLog("Notify 页面 支付成功,支付信息:商家订单号:" + out_trade_no + "、支付金额(分):" + total_fee + "、自定义参数:" + attach); /** * 这里输入用户逻辑操作,比如更新订单的支付状态 * * **/ LogHelper.WriteLog("============ 单次支付结束 ==============="); var orderid = ""; if (out_trade_no.Contains("_")) { orderid = out_trade_no.Substring(0, out_trade_no.Length - 5); } else { orderid = out_trade_no; } LogHelper.WriteLog("============ 获取订单:" + orderid + "==============="); order = orderB.GetModelWithOutTrace(o => o.orderNum == orderid); if (order!=null)//代表 { // string sql = "update TG_order set ispay=1,transaction_id='" + transaction_id + "',payTime='" + DateTime.Now + "' where orderNum='" + out_trade_no + "'";//支付成功,更新订单状态 LogHelper.WriteLog(out_trade_no.Substring(0, out_trade_no.Length - 5)); order.payTime = DateTime.Now; order.transaction_id = transaction_id; order.ispay = 3; order.ssh_status = 3; orderB.Modify(order, "ispay", "transaction_id", "payTime", "ssh_status"); LogHelper.WriteLog("============ 修改订单:" + orderid + "==============="); } total_fee = (Convert.ToInt32(total_fee) / 100).ToString(); } else { LogHelper.WriteLog("Notify 页面 支付失败,支付信息 total_fee= " + total_fee + "、err_code_des=" + err_code_des + "、result_code=" + result_code); } } else { LogHelper.WriteLog("Notify 页面 isWXsign= false ,错误信息:" + error); } } catch (Exception ee) { LogHelper.WriteLog("Notify 页面 发送异常错误:" + ee.Message); } return Content("Notify 页面 "); } public ActionResult Consumption() { ViewBag.PageFlag = "Consumption"; var status = false; var userid = "36798177";// CommonMethod.getCookie("userid"); var openid = "oJUBAv2Omhudt9cyqG_f2A1xMhUA";// CommonMethod.getCookie("openid"); if (string.IsNullOrEmpty(userid) || string.IsNullOrEmpty(openid)) { return Content("对不起,请登陆系统!"); } ViewBag.TransactionLogList = VIEW_TG_transactionLog.ToListViewModel(transactionlogB.GetListBy(s => s.userId == userid && s.openid == openid && s.tranCate == 0, o => o.AddTime, false)); return View(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace CapCSharpEFLibrary.Models { public class Customer //has to be made public { [Key] public int Id { get; set; } [StringLength(30)] // defining string length as 30 for Name [Required] // only makes sense where an entity is allowed to be nullable we do not want name to be nullable public string Name { get; set; } public double Sales { get; set; } // doubles are not allowed to be nullable, numeric data generally does not need additional attributes public bool Active { get; set; } public override string ToString() => $"{Id}/{Name}/{Sales}/{Active}"; //overrides public Customer() {} // need a default contstuctor } }
 using System.Collections.Generic; using System.Linq; namespace NBatch.Main.Common { public static class Extensions { public static IList<T> EmptyList<T>() { return Enumerable.Empty<T>().ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using Android.Widget; using Cashflow9000.Adapters; using Cashflow9000.Models; using Java.Sql; using DatePicker = Cashflow9000.Views.DatePicker; namespace Cashflow9000.Fragments { public class BudgetHeaderFragment : Fragment { public interface IBudgetHeaderFragmentListener { void OnDateChanged(); void OnRecurrenceChanged(); } private DatePicker DatePicker; private Spinner SpinRecurrence; public DateTime Date => DatePicker?.Date ?? DateTime.Today; public RecurrenceType Type { get; private set; } public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.Inflate(Resource.Layout.BudgetHeader, container, false); // Find UI views DatePicker = view.FindViewById<DatePicker>(Resource.Id.datePicker); SpinRecurrence = view.FindViewById<Spinner>(Resource.Id.spinRecurrence); // View logic DatePicker.ShowTime = false; DatePicker.DateChanged += DatePickerOnDateChanged; RecurrenceAdapter recurrenceAdapter = new RecurrenceAdapter(Activity, false); SpinRecurrence.Adapter = recurrenceAdapter; SpinRecurrence.SetSelection(recurrenceAdapter.Recurrences.FindIndex(c => c.Type == RecurrenceType.Monthly)); SpinRecurrence.ItemSelected += SpinRecurrenceOnItemSelected; return view; } private void SpinRecurrenceOnItemSelected(object sender, AdapterView.ItemSelectedEventArgs e) { Type = CashflowData.Recurrence((int)e.Id).Type; (Activity as IBudgetHeaderFragmentListener)?.OnDateChanged(); } private void DatePickerOnDateChanged(object sender, EventArgs eventArgs) { (Activity as IBudgetHeaderFragmentListener)?.OnRecurrenceChanged(); } } }
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using MyProject.Models; namespace MyProject.Data { public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } // This allows the Games, Reviews and ApplicationUsers to link correctly. protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.Entity<Game>() .HasMany<Review>() .WithOne(x => x.Game) .OnDelete(DeleteBehavior.Cascade); builder.Entity<ApplicationUser>() .HasMany<Game>() .WithOne(x => x.Developer) .OnDelete(DeleteBehavior.Cascade); builder.Entity<ApplicationUser>() .HasMany<Review>() .WithOne(x => x.User) .OnDelete(DeleteBehavior.Cascade); } public DbSet<Game> Games { get; set; } public DbSet<Review> Reviews { get; set; } public DbSet<ApplicationRole> ApplicationRole { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GenerateText : MonoBehaviour { public Transform self; public GameObject[] textGO; float currentPosX; public float enlargement = 0.5f; // Use this for initialization void Start () { for (int i = 0; i < textGO.Length; i++){ Vector3 positionLetter = new Vector3( transform.position.x - currentPosX, transform.position.y , transform.position.z); Instantiate(textGO[i], positionLetter, Quaternion.identity, self); currentPosX = currentPosX + enlargement; } } // Update is called once per frame void Update () { currentPosX = currentPosX + enlargement; } }
using Entities.RaceModels; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace DAL.DataManager { public class RaceManager : MainContext { public List<RaceModel> GetUserRaces(int userId) { List<RaceModel> result = RaceDataContext.Races.Where(r => RaceDataContext.RaceUsers.Where(ru => ru.UserId == userId).Select(ru => ru.RaceId).Contains(r.Id)) .Select(r => new RaceModel() { RaceId = r.Id, FinishTime = r.FinishTime.Value, Places = getPlaces(r) }).ToList(); return result; } public Guid CreateRace(RaceModel race, Guid categoryId) { DAL.Race raceToStore = new DAL.Race() { Id = race.RaceId, CategoryId = categoryId }; RaceDataContext.Races.InsertOnSubmit(raceToStore); RaceDataContext.SubmitChanges(); return raceToStore.Id; } public void AddUserToRace(int userId, Guid raceId) { DAL.RaceUser userRace = new DAL.RaceUser() { RaceId = raceId, UserId = userId }; RaceDataContext.RaceUsers.InsertOnSubmit(userRace); RaceDataContext.SubmitChanges(); } public void UpdateUserInRace(int userId, byte? place, Guid raceId) { DAL.RaceUser userRace = RaceDataContext.RaceUsers.FirstOrDefault(ur => ur.RaceId == raceId && ur.UserId == userId); userRace.Place = place; DAL.Race race = RaceDataContext.Races.FirstOrDefault(r => r.Id == raceId); if (place == race.RaceUsers.Count) { race.FinishTime = DateTime.Now; } RaceDataContext.SubmitChanges(); } #region Private_methods private List<RacerModel> getPlaces(DAL.Race race) { List<RacerModel> result = new List<RacerModel>(); result.AddRange(RaceDataContext.UserProfiles .Where(u => RaceDataContext.RaceUsers.Where(ru => ru.RaceId == race.Id).Select(ur => ur.UserId).Contains(u.UserId)) .Select(u => new RacerModel() { RacerId = u.UserId, RacerName = u.UserName })); return result; } #endregion } }
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using QuotingDojo.Models; namespace QuotingDojo.Controllers { public class QuotesController : Controller { [HttpGet("")] public IActionResult Index() { return View(); } [HttpGet("quotes")] public IActionResult Quotes() { List<Dictionary<string, object>> AllQuotes = DbConnector.Query($"SELECT * FROM quotes ORDER BY Created_At DESC"); ViewBag.Quotes = AllQuotes; return View(); } [HttpPost("create")] public IActionResult Create(Quote quote) { if (ModelState.IsValid) { string sql = $@"INSERT INTO quotes (User, Content, Created_at) VALUES ('{quote.User}', '{quote.Content}', NOW())"; DbConnector.Execute(sql); return RedirectToAction("Quotes"); } return View("Index"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PlaygroundFunc; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace PlaygroundFuncTestes { [TestClass] public class CalculadoraTestes { [TestMethod] public void Somar_Dois_Numeros_RetornaTotal() { var total = new Calculadora().Calcular(20, 30, (a, b) => a + b); Assert.AreEqual(50,total); } [TestMethod] [ExpectedException(typeof(DivideByZeroException), "Tentativa de divisão por zero.")] public void Dividir_Dois_Numeros_Passar_E_Falhar_Divisao_Por_Zero() { var total = new Calculadora().Calcular(100, 0, (a, b) => a/b); Assert.AreEqual(10, total); } [TestMethod] public void Dividir_Dois_Numeros_Retornal_Total() { var total = new Calculadora().Calcular(400, 40, (a, b) => a/b, (x) => x > 0); Assert.AreEqual(10, total); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using JDWinService.Dal; using JDWinService.Model; using JDWinService.Utils; using System.Data; namespace JDWinService.Services { public class JD_CuPriceDetailService { JD_CuPriceDetailDal dal = new JD_CuPriceDetailDal(); public void UpdateCuPrice(int ItemID, string FileName,int TaskID) { dal.HandleCuPrice(ItemID, FileName,TaskID); } /// <summary> /// 获取待更新的数据 /// </summary> /// <returns></returns> public DataView GetDistinctList() { return new JD_LimitPriceApply_LogDal().GetDistinctList(); } public void UpdateStatusInNew() { new JD_LimitPriceApply_LogDal().UpdateStatusInNew(); } public void UpdateItemInfo(string MOQ, string PPQ, string PackageInfo, string FNumber,string ItemID) { dal.UpdateItemInfo(MOQ, PPQ, PackageInfo, FNumber, ItemID); } } }
using System; using System.Xml.Serialization; using Lib.Implementations.Results; namespace Lib.Interfaces { [Serializable] [XmlInclude(typeof(TracerResult))] [XmlInclude(typeof(MethodResult))] [XmlInclude(typeof(ThreadResult))] public abstract class AbstractResult { } }
 using System.Collections.Generic; using UnityEngine; namespace PhotonInMaze.Common.Model { public interface IMazeCell { HashSet<Direction> Walls { get; } float X { get; } float Y { get; } int Row { get; } int Column { get; } bool IsGoal { get; } bool IsProperPathToGoal { get; } bool IsTrap { get; } Direction GetDirectionTo(IMazeCell next); HashSet<Direction> GetPossibleMovesDirection(); HashSet<Vector2Int> GetPossibleMovesCoords(); bool IsStartCell(); string ToStringAsName(); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace ProductLookUP { public partial class frmHeadersName : Form { public frmHeadersName() { InitializeComponent(); } private void button3_Click(object sender, EventArgs e) { DirectoryInfo f = new DirectoryInfo(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "//SIO//"); if (!f.Exists) { f.Create(); } f = null; StreamWriter sw = new StreamWriter(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "//SIO//HNLU.txt", false); sw.WriteLine(textlocalSKU.Text); sw.WriteLine(txtItemName.Text); sw.WriteLine(txtPrice.Text); sw.WriteLine(txtPrice2.Text); sw.WriteLine(txtPrice3.Text); sw.WriteLine(txtQOH.Text); sw.WriteLine(txtInteger1.Text); sw.WriteLine(txtInteger2.Text); sw.WriteLine(txtInteger3.Text); sw.WriteLine(txtInteger4.Text); sw.WriteLine(txtInteger5.Text); sw.WriteLine(txtBarcode.Text); sw.WriteLine(txtReorderPoint.Text); sw.WriteLine(txtRecordQuantity.Text); sw.Close(); sw.Dispose(); sw = null; this.Close(); } private void label49_Click(object sender, EventArgs e) { } private void label50_Click(object sender, EventArgs e) { } private void label51_Click(object sender, EventArgs e) { } private void frmHeadersName_Load(object sender, EventArgs e) { FileInfo fhnin = new FileInfo(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "//SIO//HNLU.txt"); if (fhnin.Exists) { StreamReader sr = new StreamReader(fhnin.FullName); textlocalSKU.Text = sr.ReadLine(); txtItemName.Text = sr.ReadLine(); txtPrice.Text = sr.ReadLine(); txtPrice2.Text = sr.ReadLine(); txtPrice3.Text = sr.ReadLine(); txtQOH.Text = sr.ReadLine(); txtInteger1.Text = sr.ReadLine(); txtInteger2.Text = sr.ReadLine(); txtInteger3.Text = sr.ReadLine(); txtInteger4.Text = sr.ReadLine(); txtInteger5.Text = sr.ReadLine(); txtBarcode.Text = sr.ReadLine(); txtReorderPoint.Text = sr.ReadLine(); txtRecordQuantity.Text = sr.ReadLine(); sr.Close(); } } private void txtPrice2_TextChanged(object sender, EventArgs e) { } } }
using ClassLibraryAandelen.basis; using System; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; namespace ClassLibraryAandelen.classes { /** * Klasse dat de portefeuille van een eigenaar voorstelt. Elke portefeuille heeft een lijst van aandelen * die hierna beheert kunnen worden. * **/ public class Portefeuille : Notifyable, IMarkdownable { #region fields [Key] public int ID { get; set; } [Required] private String _naam; [Required] public ObservableCollection<Aandeel> Aandelen { get; set; } #endregion #region constructor /// <summary> /// instantieert een Portefeuille met zijn eigen id en naam /// </summary> /// <param name="ID">Unieke id nummer</param> /// <param name="Naam">Naam portefeuille</param> internal Portefeuille(int ID, String Naam) { this.ID = ID; this.Naam = Naam; Aandelen = new ObservableCollection<Aandeel>(); } public Portefeuille(String Naam) : this(0, Naam) { } public Portefeuille() : this(0, "") { } #endregion #region properties /** * Wanneer de property verandert worden dan wordt de onpropertychanged gecalled op de Naam Property en op de Identity. * Het wordt ook op de Identity property getriggert omdat deze altijd up to date. * **/ public String Naam { get { return _naam; } set { if (_naam != value) _naam = value; OnPropertyChanged(); OnPropertyChanged("Identity"); } } public Double TotaleWaarde { get { Double TotaleWaarde = 0; if (Aandelen.Count != 0) Aandelen.ToList().ForEach(a => TotaleWaarde += a.ActueleWaarde); return TotaleWaarde; } } public String Identity => $"Portefeuille {Naam} - Waarde: {TotaleWaarde}"; #endregion #region methods /// <summary> /// Notifieert dat de totale waarde en Identity properties is verandert, in methode gestoke om buiten de classe /// uitgevoert te worden. /// </summary> public void updatePortefeuille() { NotifyProperties("TotaleWaarde", "Identity"); } /// <summary> /// Retourneert een beschrijving in Markdown formaat over deze portefeuille met de optie om markdown bescrijvingen van /// de aandelen in Markdown beschrijving of niet. /// </summary> /// <param name="IncludeAandelen">boolean om te zeggen of je de aandelen erbij wilt in Markdown</param> /// <returns>Beschrijving van de portefeuilles inhoud</returns> public string GetReturnMarkdownDescription(Boolean IncludeAandelen = true) { StringBuilder builderString = new StringBuilder(); builderString.AppendLine($"Portefeuille {Naam}".MdTitel(3)); builderString.AppendLine($"Totaal aandelen: {Aandelen.Count}".UnOrdered()); builderString.AppendLine($"Totaal waarde: {TotaleWaarde.EuroSum()}".UnOrdered()); if (Aandelen.Count != 0 && IncludeAandelen) { builderString.AppendLine(); builderString.AppendLine("Aandeel | Begin waarde | Actuele waarde | %-verschil actuele & begin waarde"); builderString.AppendLine("--- |---|---|---"); foreach (Aandeel aandeel in Aandelen) { builderString.AppendLine(aandeel.GetReturnMarkdownDescription()); } } builderString.AppendLine(Markdown.HR); return builderString.ToString(); } #endregion } }
namespace ExcelToJsonExtractor { public class TradeInformation { public TradeInformation(string recordNumber, string typeOfAction, string name, string isinCode, string tradeIdentifier, string stockExchange, string dateOfAction, string paymentDate, object quantity, double rate, string currency, double exchangeCurrency, object marketValue, object commision, object totalTransactionCost) { RecordNumber = recordNumber.Trim(); TypeOfAction = typeOfAction.Trim(); Name = name.Trim() ?? "NULL"; IsinCode = isinCode; TradeIdentifier = tradeIdentifier.Trim() ?? "NULL"; StockExchange = stockExchange; DateOfAction = dateOfAction.Trim(); PaymentDate = paymentDate.Trim(); Quantity = (double)(quantity ?? 0.0); Rate = rate; ExchangeCurrency = exchangeCurrency; Currency = currency.Trim(); MarketValue = marketValue; TotalTransactionCost = totalTransactionCost ?? 0; } public string RecordNumber { get; } public string TypeOfAction { get; } public string Name { get; } public string IsinCode { get; } public string TradeIdentifier { get; } public string StockExchange { get; } public string DateOfAction { get; } public string PaymentDate { get; } public double Quantity { get; } public double Rate { get; } public double ExchangeCurrency { get; } public string Currency { get; } public object MarketValue { get; } public object Commision { get; } public object TotalTransactionCost { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using NLog; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.IE; using OpenQA.Selenium.Safari; namespace SeleniumHarness { public static class Harness { private static List<Type> tests { get; set; } private static string logFile = Globals.Instance.fileName; private static Logger log = Globals.Instance.log; private static string email = Globals.Instance.email; private static List<Type> getTests() { tests = (from t in Assembly.GetEntryAssembly().GetTypes() where t.IsClass && t.Namespace == "SeleniumTests" select t).ToList(); log.Info(String.Format("{0} tests found", tests.Count())); return tests; } public static void run() { var tests = getTests(); if (tests == null) return; var browsers = new[] {"Chrome", "Safari", "IE", "Firefox"}; foreach (var t in tests) new TestRunner(t, browsers).runtTest(); if (email != null) EmailLog.send(); } public static void run(string[] browsers) { var tests = getTests(); if (tests == null) return; foreach (var t in tests) new TestRunner(t, browsers).runtTest(); if (email != null) EmailLog.send(); } public static void run(string test) { var tests = getTests(); if (tests == null) return; var browsers = new[] {"Chrome", "Safari", "IE", "Firefox"}; foreach (var t in tests) if (t.Name == test) new TestRunner(t, browsers).runtTest(); if (email != null) EmailLog.send(); } public static void run(string[] browsers, string test) { var tests = getTests(); if (tests == null) return; foreach (var t in tests) if (t.Name == test) new TestRunner(t, browsers).runtTest(); if (email != null) EmailLog.send(); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using EBS.Domain.Service; using EBS.Infrastructure; using Dapper.DBContext; using System.Reflection; using Autofac; namespace EBS.Test.Domain { [TestClass] public class PurchaseSaleInventoryTaskTest { [TestMethod] public void Test_PurchaseSaleInventory() { AppContext.Init(); var builder = new ContainerBuilder(); //// ASP.NET MVC Autofac RegisterDependency //Assembly webAssembly = Assembly.GetExecutingAssembly(); //builder.RegisterControllers(webAssembly); builder.RegisterType<DapperDBContext>().As<IDBContext>().WithParameter("connectionStringName", "masterDB"); builder.RegisterType<QueryService>().As<IQuery>().WithParameter("connectionStringName", "masterDB"); builder.Update(AppContext.Container); PurchaseSaleInventoryTask task = new PurchaseSaleInventoryTask(); task.Execute(); Assert.AreEqual(1, 1); } } }
// Programming Using C# @MAH // Assignment 5 // Author: Per Jonsson // Version 1 // Created: 2013-07-11 // Project: CustomerRegistry // Class: Address.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ContactRegistry { /// <summary> /// A class for handling addresses. /// </summary> public class Address { #region Fields private string street; private string zip; private string city; private Countries country; #endregion #region Constructors /// <summary> /// Default constructor, using chain callin /// </summary> public Address() : this(string.Empty, string.Empty, "Norrköping") {} /// <summary> /// 2nd constructor, calls the overloaded constructor /// </summary> /// <param name="street"></param> /// <param name="zip"></param> /// <param name="city"></param> public Address(string street, string city, string zip) : this(street, city, zip, Countries.Sverige) {} /// <summary> /// Code only at one place /// </summary> /// <param name="street"></param> /// <param name="zip"></param> /// <param name="city"></param> /// <param name="country"></param> public Address(string street, string city, string zip, Countries country) { this.street = street; this.zip = zip; this.city = city; this.country = country; } /// <summary> /// Copy constructor /// </summary> /// <param name="theOther"></param> public Address(Address origAddress) { this.street = origAddress.street; this.zip = origAddress.zip; this.city = origAddress.city; this.country = origAddress.country; } #endregion #region Properties public string Street { get { return street; } } public string City { get { return city; } } public string Zip { get { return zip; } } public Countries Country { get { return country; } } #endregion #region Methods /// <summary> /// Deletes the '_' from country names saved in the enum /// </summary> /// <returns>The country name without the '_'</returns> public string GetCountryString() { string strCountry = Country.ToString(); strCountry = strCountry.Replace("_", " "); return strCountry; } /// <summary> /// overrides the ToString method /// </summary> /// <returns>A string with the address formatted in one line</returns> public override string ToString() { string strOut = string.Format("{0,-25} {1,-8} {2,-10} {3}", Street, City, Zip, GetCountryString()); return strOut; } #endregion } }
using Alabo.App.Asset.Recharges.Domain.Entities; using Alabo.Domains.Repositories; namespace Alabo.App.Asset.Recharges.Domain.Repositories { public interface IRechargeRepository : IRepository<Recharge, long> { } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace lab_044 { public partial class Form1 : Form { public Form1() { InitializeComponent(); textBox1.Multiline = true; textBox1.Size = new Size(320, 216); this.Text = "Формирование таблицы"; string[] names = { "Андрей - раб", "Света-Х", "ЖЭК", "Справка по тел", "Александр Степанович", "Мама - дом", "Карапузова Таня", "Погода сегодня", "Театр Браво" }; string[] phones = { "274-88-14", "+38(067)7030356", "22-345-72", "009", "223-67-67 доп 32-67", "570-38-76", "201-72-23-прямой моб", "001", "216-40-22" }; textBox1.ScrollBars = ScrollBars.Vertical; textBox1.Font = new Font("Courier New", 9.0F); textBox1.Text = "ТАБЛИЦА ТЕЛЕФОНОВ\r\n\r\n"; for (int i = 0; i <= 8; i++) { textBox1.Text += String.Format("{0, -21} {1, -21}", names[i], phones[i]) + "\r\n"; } textBox1.Text += "\r\nПРИМЕЧАНИЕ:" + "\r\nдля корректного отображения таблицы" + "\r\nв Блокноте укажите шрифт Courier New"; var writer = new System.IO.StreamWriter(@"e:\Table_CS.txt", false, System.Text.Encoding.GetEncoding(1251)); writer.Write(textBox1.Text); writer.Close(); } private void показатьТаблицуВБлокнотеToolStripMenuItem_Click(object sender, EventArgs e) { try { System.Diagnostics.Process.Start("Notepad", @"e:\Table_CS.txt"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void выходToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } } }
//Triangles public void Triangles(List<string> passInList) { const int NUMBER_OF_POINTS = 3; //always 3 points for triangle foreach (string s in passInList) { string[] array = s.Split(' '); if (array.Length == NUMBER_OF_POINTS) { int firstSegment = Convert.ToInt32(array[0]); int secondSegment = Convert.ToInt32(array[1]); int thirdSegment = Convert.ToInt32(array[2]); int sumFirstAndSecondSegments = firstSegment + secondSegment; int sumFirstAndThirdSegments = firstSegment + thirdSegment; int sumSecondAndThirdSegments = secondSegment + thirdSegment; bool checkOne = sumFirstAndSecondSegments > thirdSegment; bool checkTwo = sumFirstAndThirdSegments > secondSegment; bool checkThree = sumSecondAndThirdSegments > firstSegment; if (checkOne && checkTwo && checkThree) { Console.Write("1 "); } else { Console.Write("0 "); } } else { Console.WriteLine("Major Problem"); } } }
namespace Shipwreck.TypeScriptModels.Expressions { public sealed class SuperExpression : Expression { public override ExpressionPrecedence Precedence => ExpressionPrecedence.Grouping; /// <inheritdoc /> /// <summary> /// This method always calls <see cref="IExpressionVisitor{T}.VisitSuper" />. /// </summary> public override void Accept<T>(IExpressionVisitor<T> visitor) => visitor.VisitSuper(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ToDoListApplication.BusinessLayer.Entities; using ToDoListApplication.BusinessLayer.Services.DataContracts; namespace ToDoListApplication.BusinessLayer.Mappers { public static class TaskDataMappingExtention { public static TaskData MapToTaskData(this Task entity, IList<Person> persons) { return new TaskData { Id = entity.Id, Description = entity.Description, CreatedOn = entity.CreationDate, AssignedTo = persons.SingleOrDefault(p => p.Id == entity.PersonId).MapToPersonData() }; } public static Task MapToTask(this TaskData entity) { return new Task { Id = entity.Id, Description = entity.Description, CreationDate = entity.CreatedOn, PersonId = entity.AssignedTo.Id }; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Scrabble { public partial class Scrabble : Form { Dictionary<string, string> dict = new Dictionary<string, string>(); public Scrabble() { InitializeComponent(); LoadDict(); } private void LoadDict() { string[] strArr = File.ReadAllLines(@"dict.txt", Encoding.UTF8); int emptyLineCount = 0; string key = string.Empty; foreach (string str in strArr) { if (String.IsNullOrEmpty(str)) { emptyLineCount++; } else { if (emptyLineCount != 2) { key = str; emptyLineCount = 0; } else { dict.Add(key, str); emptyLineCount = 0; key = string.Empty; } } } } private Dictionary<string, string> SearchPermutation(string[] chars, int n) { Dictionary<string, string> results = new Dictionary<string, string>(); List<string[]> permutations = PermutationAndCombination<string>.GetPermutation(chars, n); Parallel.ForEach(permutations, item => { string word = String.Join(string.Empty, item); string description = SearchWord(word); if (!string.IsNullOrEmpty(description)) { if (!results.ContainsKey(word)) { results.Add(word, description); } } }); return results; } private string SearchWord(string word) { string desctiption = string.Empty; if (dict.TryGetValue(word, out desctiption)) { return desctiption; } else { return string.Empty; } } private void search_Click(object sender, EventArgs e) { string[] chars = charactersBox.Text.Split(new char[] { ' ' }); Dictionary<string, string> results = SearchPermutation(chars, int.Parse(countBox.Text)); resultsBox.Clear(); foreach (var item in results) { resultsBox.Text = resultsBox.Text + item.Key + "\r\n" + item.Value + "\r\n"; } } } }
using SelectionCommittee.BLL.DataTransferObject; using System; using System.Collections.Generic; using System.Text; namespace SelectionCommittee.BLL.Interfaces { public interface IMarkSubjectService { void CreateRange(IEnumerable<MarkSubjectDTO> markSubjectsDTO); } }
using System; using UnityEngine; namespace UnityAtoms.BaseAtoms { /// <summary> /// Event Reference of type `Vector2`. Inherits from `AtomEventReference&lt;Vector2, Vector2Variable, Vector2Event, Vector2VariableInstancer, Vector2EventInstancer&gt;`. /// </summary> [Serializable] public sealed class Vector2EventReference : AtomEventReference< Vector2, Vector2Variable, Vector2Event, Vector2VariableInstancer, Vector2EventInstancer>, IGetEvent { } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Immutable; using System.IO; using System.Linq; namespace Vstack.Analyzers { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class VS1600NamespaceMustMatchFileLocation : DiagnosticAnalyzer { public const string DiagnosticId = "VS1600"; private const string Title = "Namespace must match file location."; private const string MessageFormat = "Namespace must match file location. Expected '{0}'."; private const string Description = "The namespaces must match file location."; private const string Category = "Documentation"; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.ValidateNotNullParameter(nameof(context)); context.RegisterSyntaxTreeAction(AnyalyzeSyntaxTree); } private static void AnyalyzeSyntaxTree(SyntaxTreeAnalysisContext context) { SyntaxNode root = context.Tree.GetRoot(); NamespaceDeclarationSyntax namespaceDeclaration = root .DescendantNodes() .OfType<NamespaceDeclarationSyntax>() .FirstOrDefault(); if (namespaceDeclaration != null) { string actualNamespace = namespaceDeclaration.Name.ToString(); string expectedNamespace = GetExpectedNamepace(context.Tree); if (actualNamespace != expectedNamespace) { context.ReportDiagnostic(Diagnostic.Create(Descriptor, namespaceDeclaration.Name.GetLocation(), expectedNamespace)); } } } private static string GetExpectedNamepace(SyntaxTree tree) { string projectPath = Path.GetDirectoryName(tree.FilePath); while (Directory.GetFiles(projectPath, "*.csproj", SearchOption.TopDirectoryOnly).Length == 0) { projectPath = Directory.GetParent(projectPath).ToString(); } string projectParentPath = Directory.GetParent(projectPath).ToString(); string documentRelativePath = Path.GetDirectoryName(tree.FilePath).Replace(projectParentPath, string.Empty).Substring(1); string expectedNamespace = documentRelativePath.Replace(Path.DirectorySeparatorChar, '.'); return expectedNamespace; } } }
using System; using System.Text; namespace XOXClient { class Program { public static string GetNameInput() { Console.WriteLine("Enter name:"); string name = Console.ReadLine(); return name; } static void Main(string[] args) { try { Console.WriteLine("Attempting to establish a connection to the server.."); Connection.Connect(args[0], Convert.ToInt32(args[1])); } catch (Exception e) { Console.WriteLine(e.Message); } } } }
namespace LightingBook.Test.Api.Common.Dto { public class CarDepot { public string Supplier { get; set; } public string Code { get; set; } public string FullCode { get; set; } public string Address { get; set; } } }
namespace ResolveUR.Library { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; class PackageConfig { const string Id = "id"; const string Version = "version"; const string DevelopmentDependency = "developmentDependency"; const string PackageNode = @"//*[local-name()='package']"; XmlDocument _packageConfigDocument; IDictionary<string, XmlNode> _packages; public string PackageConfigPath { get; set; } public string FilePath { get; set; } public bool Load() { // an entry in package config maps to hint path under project reference node as follows: // Entry : <package id="CsvHelper" version="2.7.0" targetFramework="net45" /> // Hint path : <HintPath>..\packages\CsvHelper.2.7.0\lib\net40-client\CsvHelper.dll</HintPath> // Folder in HintPath CsvHelper.2.7.0 is derieved by concatenation of Id and Version attributes of Entry // map versioned library CsvHelper.2.7.0 to package entries in method if (!File.Exists(PackageConfigPath) || _packageConfigDocument != null) return false; _packageConfigDocument = new XmlDocument(); _packageConfigDocument.Load(PackageConfigPath); var packageNodes = _packageConfigDocument.SelectNodes(PackageNode); if (packageNodes != null && packageNodes.Count > 0) _packages = new Dictionary<string, XmlNode>(); if (packageNodes == null) return false; foreach (var node in packageNodes.Cast<XmlNode>() .Where(node => node.Attributes != null && node.Attributes[DevelopmentDependency] == null)) _packages.Add($"{node.Attributes[Id].Value}.{node.Attributes[Version].Value}", node); // when references are cleaned up later, store package nodes that match hint paths for references that are ok to keep // at the conclusion of cleanup, rewrite packages config with saved package nodes to keep return true; } public void Remove(XmlNode referenceNode) { if (referenceNode.ChildNodes.Count == 0) return; var hintPath = getHintPath(referenceNode); foreach (var package in _packages) { if (!hintPath.Contains(package.Key)) continue; var packagePath = $"{hintPath.Substring(0, hintPath.IndexOf(package.Key, StringComparison.Ordinal))}{package.Key}"; var folderName = Path.GetDirectoryName(FilePath); if (folderName != null) packagePath = Path.Combine(folderName, packagePath); try { _packageConfigDocument.DocumentElement?.RemoveChild(package.Value); Directory.Delete(packagePath, true); } catch (DirectoryNotFoundException) { Console.WriteLine("The package was already deleted."); } break; } } string getHintPath(XmlNode referenceNode) { var node = referenceNode.ChildNodes.OfType<XmlNode>().FirstOrDefault(x => x.Name == "HintPath"); return node == null ? string.Empty : node.InnerXml; } public void Save() { _packageConfigDocument.Save(PackageConfigPath); } } }
using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows.Input; using Theatre.Model; using Theatre.Services; using Theatre.View; using Xamarin.Forms; namespace Theatre.ViewModel { public class ArticleListViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged = delegate { }; private ObservableCollection<Article> _articles; public ObservableCollection<Article> Articles { get => _articles; set { _articles = value; PropertyChanged(this, new PropertyChangedEventArgs("Other")); } } public INavigation Navigation { get; set; } public ICommand GoToDetailCommand { get; private set; } protected IDBService DBService; public ArticleListViewModel(IDBService dbService) { DBService = dbService; GoToDetailCommand = new Command<Performance>(GoToDetail); Init(); } public void Init(INavigation navigation) { Navigation = navigation; Articles = new ObservableCollection<Article>(DBService.GetArticles()); } public void Init() { Articles = new ObservableCollection<Article>(DBService.GetArticles()); } internal void GoToDetail(Performance performance) { var page = new DetailHomePage(new DetailHomeViewModel(performance)); Navigation.PushAsync(page, true); } } }
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.Navigation; using System.Windows.Shapes; namespace Exercise1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Calculate_Click(object sender, RoutedEventArgs e) { if (double.TryParse(MealCost.Text, out double mealCost)) { Cost.Text = $"{mealCost:C}"; if (TotalCost.IsChecked == true) { if (double.TryParse(TipPercent.Text, out double tipPercent)) { double tip = mealCost * (tipPercent / 100); Cost.Text = $"{mealCost + tip:C}"; } else { MessageBox.Show("Cant Parse tip percent"); return; } } } else { MessageBox.Show("Cant Parse meal cost"); return; } } } }
using System.Threading; using System.Windows.Forms.VisualStyles; using Framework.Core.Common; using Framework.Core.Helpers.Data; using Tests.Pages.Oberon; using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; namespace Tests.Pages.Oberon.Tenant { public class TenantBasePage : OberonBasePage { public TenantBasePage(Driver driver) : base(driver) { } #region Page Objects public IWebElement SaveButton { get { return _driver.FindElement(By.XPath("//input[@value='Save']")); } } public IWebElement Footer { get { return _driver.FindElement(By.CssSelector("#footer")); } } #endregion #region Methods /// <summary> /// creates feature array, sets features individually /// </summary> public void SetFeatures(string feature) { string[] features = {feature}; SetFeatures(features); } /// <summary> /// sets features individually /// </summary> public void SetFeatures(string[] features) { foreach (var feature in features) { IWebElement element = _driver.FindElement(By.Id(feature)); if ((!_driver.IsSelected(element))) //_driver.FindElement(By.Id(feature)))) { if (_driver.InternetExplorer() == true || _driver.Chrome() == true) { _driver.Click(element); } else { _driver.MoveToElementWithOffsetAndClick(element); } //element.Click(); //_driver.FindElement(By.Id(feature))); } } } /// <summary> /// creates feature array, unsets features individually /// </summary> public void UnsetFeatures(string feature) { string[] features = { feature }; UnsetFeatures(features); } /// <summary> /// unsets features individually /// </summary> public void UnsetFeatures(string[] features) { foreach (var feature in features) { IWebElement element = _driver.FindElement(By.Id(feature)); if ((_driver.IsSelected(element))) { if (_driver.InternetExplorer() == true || _driver.Chrome() == true) { _driver.Click(element); } else { _driver.MoveToElementWithOffsetAndClick(element); } } } } /// <summary> /// clicks save button, waits 3 seconds /// </summary> public void ClickSaveButton() { _driver.MoveToElement(Footer); _driver.Click(SaveButton); var detail = new TenantDetail(_driver); WaitForHeaderToDisplay(detail.HeaderLocator, detail.Header, detail.HeaderText); } /// <summary> /// Gets the selected status of a feature by its ID. /// </summary> public bool GetFeatureStatusById(string featureId) { IWebElement element = _driver.FindElement(By.Id(featureId)); return element.Selected; } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class back_to_menu : MonoBehaviour { public Text Asd_score; public Text normal_score; public Text total_score; public Text high_score; private void Start() { Asd_score.text = "ASD Score: " + PlayerPrefs.GetFloat("ASD_score", 0).ToString("0"); normal_score.text = "Normal Score: " + PlayerPrefs.GetFloat("Normal_score", 0).ToString("0"); total_score.text = "Total Score: " + (PlayerPrefs.GetFloat("ASD_score", 0) + PlayerPrefs.GetFloat("Normal_score", 0)).ToString("0"); high_score.text = "High Score: " + PlayerPrefs.GetFloat("HighScore", 0).ToString("0"); } public void gotomenu() { SceneManager.LoadScene("menu"); } public void gotoGame() { SceneManager.LoadScene("ASD_game_scene"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace Abhs.Data.ServiceDBContext { /// <summary> /// 线程单例类... /// </summary> public class ThreadSingleton { /// <summary> /// 获取EF数据库连接对象... /// </summary> /// <returns></returns> public static MathDbContext GetDBEntities() { System.Web.HttpContext context = System.Web.HttpContext.Current; if(context==null) return new MathDbContext(); if (context.Items["DBEntities"] == null) context.Items["DBEntities"] = new MathDbContext(); return context.Items["DBEntities"] as MathDbContext; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TDC_Union.ModelsPush { public class CommonModel { public string FName { get; set; } public string strVar { get; set; } } }
 namespace Pe.Stracon.SGC.Cross.Core.Base { public interface IGenericException { } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Security.Cryptography; using System.Text.RegularExpressions; namespace CinemaProject { internal static class Extensions { public static bool IsEmail(this string email) { if (Regex.IsMatch(email, @"[^@\s]+@[^@\.\s]+\.\w{2,}")) { return true; } else { return false; } } //encryption works only locally don't use for database purposes //this is for encryption public static string Protect(this string str) { byte[] entropy = Encoding.ASCII.GetBytes(Assembly.GetExecutingAssembly().FullName); byte[] data = Encoding.ASCII.GetBytes(str); string protectedData = Convert.ToBase64String(ProtectedData.Protect(data, entropy, DataProtectionScope.CurrentUser)); return protectedData; } //this is for decryption public static string Unprotect(this string str) { byte[] protectedData = Convert.FromBase64String(str); byte[] entropy = Encoding.ASCII.GetBytes(Assembly.GetExecutingAssembly().FullName); string data = Encoding.ASCII.GetString(ProtectedData.Unprotect(protectedData, entropy, DataProtectionScope.CurrentUser)); return data; } //this is for hashing public static string MD5Hash(this string password) { MD5 md5 = new MD5CryptoServiceProvider(); //compute hash from the bytes of text md5.ComputeHash(UTF8Encoding.UTF8.GetBytes(password)); //get hash result after compute it byte[] result = md5.Hash; StringBuilder strBuilder = new StringBuilder(); for (int i = 0; i < result.Length; i++) { //change it into 2 hexadecimal digits //for each byte strBuilder.Append(result[i].ToString("x2")); } return strBuilder.ToString(); } } }
using AsyncRAT_Sharp.Cryptography; using AsyncRAT_Sharp.Sockets; using System.Collections.Generic; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Windows.Forms; namespace AsyncRAT_Sharp { public static class Settings { public static List<Clients> Online = new List<Clients>(); public static List<string> Blocked = new List<string>(); public static long Sent { get; set; } public static long Received { get; set; } public static string CertificatePath = Application.StartupPath + "\\ServerCertificate.p12"; public static X509Certificate2 ServerCertificate; public static readonly string Version = "AsyncRAT 0.4.9E"; } }
using System; using System.Web.Mvc; using DevExpress.Web.Mvc; namespace DevExpress.Web.Demos { public partial class SchedulerController: DemoController { public ActionResult Editing() { return DemoView("Editing", SchedulerDataHelper.EditableDataObject); } public ActionResult EditingPartial() { return PartialView("EditingPartial", SchedulerDataHelper.EditableDataObject); } public ActionResult EditingPartialEditAppointment() { try { SchedulerDataHelper.UpdateEditableDataObject(); } catch(Exception e) { ViewData["SchedulerErrorText"] = e.Message; } return PartialView("EditingPartial", SchedulerDataHelper.EditableDataObject); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SpringHackApi.Models { public enum CouponCodeStatus { Used = 0, Unused = 1, } }
using System; using System.Collections.Generic; using System.Text; namespace BankAreUSEFCore.Domain.Models { class Address { public int Id { get; protected set; } public string Street { get; protected set; } public string City { get; protected set; } public string ZipCode { get; protected set; } public Address(string street, string city, string zipCode) { Street = street; City = city; ZipCode = zipCode; } } }
 using MediatR; using Microsoft.Extensions.DependencyInjection; using NerdStore.Catalog.Application.Services; using NerdStore.Catalog.Data; using NerdStore.Catalog.Data.Repository; using NerdStore.Catalog.Domain; using NerdStore.Core.Bus; namespace NerdStore.WebApp.MVC.Setup { public static class DependencyInjection { public static void RegisterServices(this IServiceCollection services) { // Mediator services.AddScoped<IMediatrHandler, MediatrHandler>(); // Notifications //services.AddScoped<INotificationHandler<DomainNotification>, DomainNotificationHandler>(); //// Event Sourcing //services.AddSingleton<IEventStoreService, EventStoreService>(); //services.AddSingleton<IEventSourcingRepository, EventSourcingRepository>(); // Catalogo services.AddScoped<IProductRepository, ProductRepository>(); services.AddScoped<IProductAppService, ProductAppService>(); services.AddScoped<IStockService, StockService>(); services.AddScoped<CatalogContext>(); //services.AddScoped<INotificationHandler<ProductAbaixoEstoqueEvent>, ProductEventHandler>(); //services.AddScoped<INotificationHandler<PedidoIniciadoEvent>, ProductEventHandler>(); //services.AddScoped<INotificationHandler<PedidoProcessamentoCanceladoEvent>, ProductEventHandler>(); //// Vendas //services.AddScoped<IPedidoRepository, PedidoRepository>(); //services.AddScoped<IPedidoQueries, PedidoQueries>(); //services.AddScoped<VendasContext>(); //services.AddScoped<IRequestHandler<AdicionarItemPedidoCommand, bool>, PedidoCommandHandler>(); //services.AddScoped<IRequestHandler<AtualizarItemPedidoCommand, bool>, PedidoCommandHandler>(); //services.AddScoped<IRequestHandler<RemoverItemPedidoCommand, bool>, PedidoCommandHandler>(); //services.AddScoped<IRequestHandler<AplicarVoucherPedidoCommand, bool>, PedidoCommandHandler>(); //services.AddScoped<IRequestHandler<IniciarPedidoCommand, bool>, PedidoCommandHandler>(); //services.AddScoped<IRequestHandler<FinalizarPedidoCommand, bool>, PedidoCommandHandler>(); //services.AddScoped<IRequestHandler<CancelarProcessamentoPedidoCommand, bool>, PedidoCommandHandler>(); //services.AddScoped<IRequestHandler<CancelarProcessamentoPedidoEstornarEstoqueCommand, bool>, PedidoCommandHandler>(); //services.AddScoped<INotificationHandler<PedidoRascunhoIniciadoEvent>, PedidoEventHandler>(); //services.AddScoped<INotificationHandler<PedidoEstoqueRejeitadoEvent>, PedidoEventHandler>(); //services.AddScoped<INotificationHandler<PedidoPagamentoRealizadoEvent>, PedidoEventHandler>(); //services.AddScoped<INotificationHandler<PedidoPagamentoRecusadoEvent>, PedidoEventHandler>(); //// Pagamento //services.AddScoped<IPagamentoRepository, PagamentoRepository>(); //services.AddScoped<IPagamentoService, PagamentoService>(); //services.AddScoped<IPagamentoCartaoCreditoFacade, PagamentoCartaoCreditoFacade>(); //services.AddScoped<IPayPalGateway, PayPalGateway>(); //services.AddScoped<IConfigurationManager, ConfigurationManager>(); //services.AddScoped<PagamentoContext>(); //services.AddScoped<INotificationHandler<PedidoEstoqueConfirmadoEvent>, PagamentoEventHandler>(); } } }
using System; using System.Collections.Generic; using System.Text; namespace School.Business.Models { public class StudentClassModel { public int UserId { get; set; } public int ClassId { get; set; } public string ClassName { get; set; } public string ClassDescription { get; set; } public decimal ClassPrice { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class PlayerWallet : MonoBehaviour { private int _bakedCakes; public int BakedCakes => _bakedCakes; public event UnityAction<int> CakeBalanceChanged; public void AddCakeProfit(int amount) { _bakedCakes += amount; CakeBalanceChanged?.Invoke(_bakedCakes); } public void WithdrawCakes(int amount) { _bakedCakes -= amount; CakeBalanceChanged?.Invoke(_bakedCakes); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Project.Object { class UserInfObject { private String username = ""; private String password = ""; private String name = ""; private int id ; private bool isLoggedIn = false; public UserInfObject(String username, String password, String name, int id = 0,bool isLoggedIn = false) { this.username = username; this.password = password; this.name = name; this.id = id; this.isLoggedIn = isLoggedIn; } public String getName() { return name; } public int getId() { return id; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Number { class Program { static void Main(string[] args) { // Максимальное значение int max = 100; // Колличество попыток int guesses = 0; // Предполагаемый минимум int guessMin = 0; // Предполагаемый максимум int guessMax = max / 2; // Загадываем число Console.WriteLine("Please choise number from 0 to 100"); // Запускаем цикл работающий пока предполагаемый минимум не будет равен максимуму while (guessMin != max) { // Увеличиваем колличество попыток guesses++; // Спрашиваем пользователя Console.WriteLine($"Your number between {guessMin} and {guessMax}?"); // Записываем ответ string responce = Console.ReadLine(); // Сверяем ответ с допустимыми символами if (responce?.ToLower().FirstOrDefault() == 'y') { // Переписываем максимальное значение на предполагаемый максимум max = guessMax; // Уменьшаем предполагаемое максимальное значение на 2 для нижней границы цикла guessMax = guessMax - (guessMax - guessMin) / 2; } else { // Заменяем предполагаемый минимум на предполагаемый максимум + 1 guessMin = guessMax + 1; // Определяем новую переменную для верхней границы цикла int remainingDifference = max - guessMax; // Округляем для точности вычислений и увеличиваем предполагаемый максимум на половину guessMax += (int)Math.Ceiling(remainingDifference / 2f); } // Из оставшихся 2х вариантов угадываем правильный if (guessMin + 1 == max) { // Увеличиваем колличество попыток guesses++; // Спрашиваем пользователя о том что предполагаемый минимум это правильный ответ Console.WriteLine($"Is your number {guessMin}?"); // Записываем ответ responce = Console.ReadLine(); // Сверяем ответ с правильными символами if (responce?.ToLower().FirstOrDefault() == 'y') { // Завершаем цикл break; } else { // Устанавливаем другое значение в качестве ответа guessMin = max; // Завершаем цикл break; } } } // Называем загаданный номер Console.WriteLine($"Your number is {guessMin}"); // Называем колличество попыток Console.WriteLine($"Guess in {guesses} guesses"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Pajaro : MonoBehaviour { Rigidbody rb; AudioSource audioSource; [SerializeField] GameObject prefabSangre; private int fuerza = 1300; private int gravedad = 20; public Text txPuntuacion; [SerializeField] AudioClip sonidoAlas; [SerializeField] AudioClip sonidoPunto; [SerializeField] GameObject botonReload; // Start is called before the first frame update void Start() { rb = GetComponent<Rigidbody>(); audioSource = GetComponent<AudioSource>(); } // Update is called once per frame void Update() { rb.AddForce(Vector3.down * gravedad); if (GameManager.playing == true) { if (rb.GetPointVelocity(transform.position).y < 0 && transform.rotation.x < 0.2) { transform.Rotate(5, 0, 0); } else if (rb.GetPointVelocity(transform.position).y > 0 && transform.rotation.x > -0.2) { transform.Rotate(-15, 0, 0); } } if (Input.GetKeyDown(KeyCode.Space) && rb.GetPointVelocity(transform.position).y < 0) { Saltar(); } } private void OnCollisionEnter(Collision collision) { Morir(); } private void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Limite") == true) { Morir(); } else { Puntuar(); } } private void Puntuar() { audioSource.PlayOneShot(sonidoPunto); GameManager.score++; txPuntuacion.text = "Score: " + GameManager.score.ToString(); } private void Morir() { botonReload.SetActive(true); Instantiate(prefabSangre, transform.position, transform.rotation); GameManager.playing = false; GameManager.score = 0; Destroy(gameObject); } private void Saltar() { audioSource.PlayOneShot(sonidoAlas); rb.AddForce(Vector3.up * fuerza); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Fina.Models { public class ProductViewModel { public int ID { get; set; } [Required] [DisplayName("კოდი")] public string Code { get; set; } [Required] [DisplayName("დასახელება")] public string Name { get; set; } [DataType(DataType.Currency)] [DisplayName("ფასი")] public decimal? Price { get; set; } [Required] [DisplayName("რაოდენობა")] public int Number { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; [System.Serializable] public class Weapon : Item { [Space(10)][Header("Weapon Information")] public WeaponType weaponType = WeaponType.Melee; public enum WeaponType { Melee, Gun }; [Space(10)][Header("Firing Variables")] public bool triggerHeld; public float timeLastFired; public float timeLastTriggered; [Space(10)][Header("Ammo Variables")] public int ammoCurrent; [Space(10)][Header("Accuracy Variables")] public float accuracyCurrent; // The current accuracy of the weapon [Space(10)][Header("Charge Variables")] public float chargeCurrent; // The current percentage of charge [Space(10)][Header("Weapon Attributes")] public WeaponAttributes baseAttributes; public WeaponAttributes combinedAttributes; [Space(10)][Header("Position Attributes")] public Transform barrelPoint; public Transform muzzleFlash; [System.Serializable] public class WeaponAttributes { [Header("Firing Attributes")] public bool automatic; public float firerate; public int burstCount; public float burstDelay; [Space(10)][Header("Ammo Attributes")] public int ammoMax; public int consumption; public bool consumePerBurst; [Space(10)][Header("Accuracy Attributes")] [Range(0, 1)] public float accuracyMax; // The maximum accuracy the weapon can have [Range(0, 1)] public float accuracyMin; // The minimum accuracy the weapon can have public float accuracyIncrement; // The amount of accuracy added to accuracyCurrent per second public float accuracyDecrement; // The amount of accuracy subtracted from accuracyCurrent per fire [Space(10)] [Header("Recoil Attributes")] public float recoilLinear; // The amount of velocity added to the weapon when fired public float recoilAngular; // The amount of angularVelocity added to the weapon when fired [Space(10)][Header("Charge Attributes")] public bool chargingEnabled; // Does the weapon use charging? public float chargeIncrement; // The amount charge increases per second public float chargeDecrement; // The amount charge decreases per second public float chargeDecrementPerShot; // The amount of charge lost once the weapon is fired public float chargeRequired; // The amount of charge required to fire public float chargeInfluenceVelocity; // The percentage of influence the charge amount has on projectile velocity [Space(10)][Header("Projectile Attributes & Spread Attributes")] public ProjectileAttributes projectileAttributes = new ProjectileAttributes(); public Projectile.ProjectileSpreadAttributes projectileSpreadAttributes; public WeaponAttributes(WeaponAttributes copiedAttributes) { automatic = copiedAttributes.automatic; firerate = copiedAttributes.firerate; burstCount = copiedAttributes.burstCount; burstDelay = copiedAttributes.burstDelay; ammoMax = copiedAttributes.ammoMax; consumption = copiedAttributes.consumption; consumePerBurst = copiedAttributes.consumePerBurst; accuracyMax = copiedAttributes.accuracyMax; accuracyMin = copiedAttributes.accuracyMin; accuracyIncrement = copiedAttributes.accuracyIncrement; accuracyDecrement = copiedAttributes.accuracyDecrement; recoilLinear = copiedAttributes.recoilLinear; recoilAngular = copiedAttributes.recoilAngular; chargingEnabled = copiedAttributes.chargingEnabled; chargeIncrement = copiedAttributes.chargeIncrement; chargeDecrement = copiedAttributes.chargeDecrement; chargeDecrementPerShot = copiedAttributes.chargeDecrementPerShot; chargeRequired = copiedAttributes.chargeRequired; chargeInfluenceVelocity = copiedAttributes.chargeInfluenceVelocity; projectileAttributes = new ProjectileAttributes(copiedAttributes.projectileAttributes); projectileSpreadAttributes = new Projectile.ProjectileSpreadAttributes(copiedAttributes.projectileSpreadAttributes); projectileAttributes.prefabProjectile = copiedAttributes.projectileAttributes.prefabProjectile; } public WeaponAttributes() { // All defaul values for attachment WeaponAttributes // booleans automatic = false; consumePerBurst = false; chargingEnabled = false; projectileSpreadAttributes.spreadType = Projectile.ProjectileSpreadAttributes.SpreadType.Circular; projectileAttributes.decelerationType = ProjectileAttributes.DecelerationType.Normal; projectileAttributes.isSticky = false; // percentages firerate = 0; burstDelay = 0; accuracyMax = 0; accuracyMin = 0; accuracyIncrement = 0; accuracyDecrement = 0; recoilLinear = 0; recoilAngular = 0; chargeIncrement = 0; chargeDecrement = 0; chargeDecrementPerShot = 0; chargeRequired = 0; chargeInfluenceVelocity = 0; projectileAttributes.damage = 0; projectileSpreadAttributes.spreadDeviation = 0; projectileAttributes.ricochetAngleMax = 0; projectileAttributes.velocityInitial = 0; projectileAttributes.gravity = 0; projectileAttributes.deceleration = 0; projectileAttributes.lifespan = 0; // additions burstCount = 0; ammoMax = 0; consumption = 0; projectileAttributes.ricochetCountInitial = 0; projectileAttributes.prefabProjectile = null; //projectileSpreads = copiedAttributes.projectileSpreads; } public WeaponAttributes(bool baseValues) { // All defaul values for attachment WeaponAttributes // booleans automatic = false; consumePerBurst = false; chargingEnabled = false; projectileSpreadAttributes.spreadType = Projectile.ProjectileSpreadAttributes.SpreadType.Circular; projectileAttributes.decelerationType = ProjectileAttributes.DecelerationType.Normal; projectileAttributes.isSticky = false; // percentages firerate = 1; burstDelay = 1; accuracyMax = 1; accuracyMin = 1; accuracyIncrement = 1; accuracyDecrement = 1; recoilLinear = 1; recoilAngular = 1; chargeIncrement = 1; chargeDecrement = 1; chargeDecrementPerShot = 1; chargeRequired = 1; chargeInfluenceVelocity = 1; projectileAttributes.damage = 1; projectileSpreadAttributes.spreadDeviation = 1; projectileAttributes.ricochetAngleMax = 1; projectileAttributes.velocityInitial = 1; projectileAttributes.gravity = 1; projectileAttributes.deceleration = 1; projectileAttributes.lifespan = 1; // additions burstCount = 0; ammoMax = 0; consumption = 0; projectileAttributes.ricochetCountInitial = 0; //projectileSpreads = copiedAttributes.projectileSpreads; projectileAttributes.prefabProjectile = null; } } [Space(10)][Header("Audio Info")] public AudioClip soundFireNormal; // The normal audio clip player when firing the weapon // Events public event Action eventAdjustAmmo; void Start () { UpdateCombinedAttributes(); } protected override void OnItemUpdate () { if (triggerHeld == false) { if (combinedAttributes.chargingEnabled == true) { chargeCurrent = Mathf.Clamp01(chargeCurrent - (combinedAttributes.chargeDecrement * Time.deltaTime)); } } } public void AdjustAmmo (int a) { ammoCurrent = (int)Mathf.Clamp(ammoCurrent + a, 0, combinedAttributes.ammoMax); if (eventAdjustAmmo != null) { eventAdjustAmmo.Invoke(); } } public void UpdateCombinedAttributes () { // Set combinedAttributes equal to the weapon's base attributes first combinedAttributes = new WeaponAttributes(baseAttributes); if (transform.Find("(BarrelPoint)")) { barrelPoint = transform.Find("(BarrelPoint)"); if (barrelPoint.Find("(MuzzleFlash)")) { muzzleFlash = barrelPoint.Find("(MuzzleFlash)"); } } if (attachments.Count > 0) { List<WeaponAttributes> allAttributes = new List<WeaponAttributes>(); // Add all of the currently used attributes to the allAttributes list for (int i = 0; i < attachments.Count; i++) { if (attachments[i] is Attachment) { // Is the current attachment actually an Attachment class Object Attachment attachmentObject = attachments[i] as Attachment; // Creating allAttributes List if (attachmentObject.isGrabbed == true && attachmentObject.attributesAlwaysPassive == false) { // Is the attachment currently being grabbed and alwaysPassive is false? allAttributes.Add(attachmentObject.attachmentAttributesActive); // If yes, add its active attributes } else { allAttributes.Add(attachmentObject.attachmentAttributesPassive); // If no, add its passive attributes } // Finding Barrel Point if (attachments[i].transform.Find("(BarrelPoint)") != null) { bool currentNodeWorks = true; for (int a = 0; a < attachments[i].attachmentNodes.Count; a++) { if (attachments[i].attachmentNodes[a].attachmentType == AttachmentNode.AttachmentType.Barrel && attachments[i].attachmentNodes[a].isAttached == false) { currentNodeWorks = false; } } if (currentNodeWorks == true) { barrelPoint = attachments[i].transform.Find("(BarrelPoint)"); } } } } // Combined all of the attachments' weapon attributes together in combinedAttributes WeaponAttributes combinedAttachmentAttributes = new WeaponAttributes(true); for (int j = 0; j < allAttributes.Count; j++) { // booleans combinedAttachmentAttributes.automatic = allAttributes[j].automatic == true ? allAttributes[j].automatic : combinedAttachmentAttributes.automatic; combinedAttachmentAttributes.consumePerBurst = allAttributes[j].consumePerBurst == true ? allAttributes[j].consumePerBurst : combinedAttachmentAttributes.consumePerBurst; combinedAttachmentAttributes.chargingEnabled = allAttributes[j].chargingEnabled == true ? allAttributes[j].chargingEnabled : combinedAttachmentAttributes.chargingEnabled; combinedAttachmentAttributes.projectileSpreadAttributes.spreadType = allAttributes[j].projectileSpreadAttributes.spreadType == Projectile.ProjectileSpreadAttributes.SpreadType.Custom ? allAttributes[j].projectileSpreadAttributes.spreadType : combinedAttachmentAttributes.projectileSpreadAttributes.spreadType; combinedAttachmentAttributes.projectileAttributes.decelerationType = allAttributes[j].projectileAttributes.decelerationType == ProjectileAttributes.DecelerationType.Smooth ? allAttributes[j].projectileAttributes.decelerationType : combinedAttachmentAttributes.projectileAttributes.decelerationType; combinedAttachmentAttributes.projectileAttributes.isSticky = allAttributes[j].projectileAttributes.isSticky == true ? allAttributes[j].projectileAttributes.isSticky : combinedAttachmentAttributes.projectileAttributes.isSticky; // percentages combinedAttachmentAttributes.firerate += allAttributes[j].firerate; combinedAttachmentAttributes.burstDelay += allAttributes[j].burstDelay; combinedAttachmentAttributes.accuracyMax += allAttributes[j].accuracyMax; combinedAttachmentAttributes.accuracyMin += allAttributes[j].accuracyMin; combinedAttachmentAttributes.accuracyIncrement += allAttributes[j].accuracyIncrement; combinedAttachmentAttributes.accuracyDecrement += allAttributes[j].accuracyDecrement; combinedAttachmentAttributes.recoilLinear += allAttributes[j].recoilLinear; combinedAttachmentAttributes.recoilAngular += allAttributes[j].recoilAngular; combinedAttachmentAttributes.chargeIncrement += allAttributes[j].chargeIncrement; combinedAttachmentAttributes.chargeDecrement += allAttributes[j].chargeDecrement; combinedAttachmentAttributes.chargeDecrementPerShot += allAttributes[j].chargeDecrementPerShot; combinedAttachmentAttributes.chargeRequired += allAttributes[j].chargeRequired; combinedAttachmentAttributes.chargeInfluenceVelocity += allAttributes[j].chargeInfluenceVelocity; combinedAttachmentAttributes.projectileAttributes.damage += allAttributes[j].projectileAttributes.damage; combinedAttachmentAttributes.projectileSpreadAttributes.spreadDeviation += allAttributes[j].projectileSpreadAttributes.spreadDeviation; combinedAttachmentAttributes.projectileAttributes.ricochetAngleMax += allAttributes[j].projectileAttributes.ricochetAngleMax; combinedAttachmentAttributes.projectileAttributes.velocityInitial += allAttributes[j].projectileAttributes.velocityInitial; combinedAttachmentAttributes.projectileAttributes.gravity += allAttributes[j].projectileAttributes.gravity; combinedAttachmentAttributes.projectileAttributes.deceleration += allAttributes[j].projectileAttributes.deceleration; combinedAttachmentAttributes.projectileAttributes.lifespan += allAttributes[j].projectileAttributes.lifespan; // additions combinedAttachmentAttributes.burstCount += allAttributes[j].burstCount; combinedAttachmentAttributes.ammoMax += allAttributes[j].ammoMax; combinedAttachmentAttributes.consumption += allAttributes[j].consumption; combinedAttachmentAttributes.projectileAttributes.ricochetCountInitial += allAttributes[j].projectileAttributes.ricochetCountInitial; // Prefabs combinedAttachmentAttributes.projectileAttributes.prefabProjectile = allAttributes[j].projectileAttributes.prefabProjectile != null ? allAttributes[j].projectileAttributes.prefabProjectile : combinedAttachmentAttributes.projectileAttributes.prefabProjectile; //projectileSpreads = copiedAttributes.projectileSpreads; } // Combined the weapon's baseWeaponAttributes with the combined Attachment attributes // booleans combinedAttributes.automatic = combinedAttachmentAttributes.automatic == true ? combinedAttachmentAttributes.automatic : combinedAttributes.automatic; combinedAttributes.consumePerBurst = combinedAttachmentAttributes.consumePerBurst == true ? combinedAttachmentAttributes.consumePerBurst : combinedAttributes.consumePerBurst; combinedAttributes.chargingEnabled = combinedAttachmentAttributes.chargingEnabled == true ? combinedAttachmentAttributes.chargingEnabled : combinedAttributes.chargingEnabled; combinedAttributes.projectileSpreadAttributes.spreadType = combinedAttachmentAttributes.projectileSpreadAttributes.spreadType == Projectile.ProjectileSpreadAttributes.SpreadType.Custom ? combinedAttachmentAttributes.projectileSpreadAttributes.spreadType : combinedAttributes.projectileSpreadAttributes.spreadType; combinedAttributes.projectileAttributes.decelerationType = combinedAttachmentAttributes.projectileAttributes.decelerationType == ProjectileAttributes.DecelerationType.Smooth ? combinedAttachmentAttributes.projectileAttributes.decelerationType : combinedAttributes.projectileAttributes.decelerationType; combinedAttributes.projectileAttributes.isSticky = combinedAttachmentAttributes.projectileAttributes.isSticky == true ? combinedAttachmentAttributes.projectileAttributes.isSticky : combinedAttributes.projectileAttributes.isSticky; // percentages combinedAttributes.firerate *= combinedAttachmentAttributes.firerate; combinedAttributes.burstDelay *= combinedAttachmentAttributes.burstDelay; combinedAttributes.accuracyMax *= combinedAttachmentAttributes.accuracyMax; combinedAttributes.accuracyMin *= combinedAttachmentAttributes.accuracyMin; combinedAttributes.accuracyIncrement *= combinedAttachmentAttributes.accuracyIncrement; combinedAttributes.accuracyDecrement *= combinedAttachmentAttributes.accuracyDecrement; combinedAttributes.recoilLinear *= combinedAttachmentAttributes.recoilLinear; combinedAttributes.recoilAngular *= combinedAttachmentAttributes.recoilAngular; combinedAttributes.chargeIncrement *= combinedAttachmentAttributes.chargeIncrement; combinedAttributes.chargeDecrement *= combinedAttachmentAttributes.chargeDecrement; combinedAttributes.chargeDecrementPerShot *= combinedAttachmentAttributes.chargeDecrementPerShot; combinedAttributes.chargeRequired *= combinedAttachmentAttributes.chargeRequired; combinedAttributes.chargeInfluenceVelocity *= combinedAttachmentAttributes.chargeInfluenceVelocity; combinedAttributes.projectileAttributes.damage *= combinedAttachmentAttributes.projectileAttributes.damage; combinedAttributes.projectileSpreadAttributes.spreadDeviation *= combinedAttachmentAttributes.projectileSpreadAttributes.spreadDeviation; combinedAttributes.projectileAttributes.ricochetAngleMax *= combinedAttachmentAttributes.projectileAttributes.ricochetAngleMax; combinedAttributes.projectileAttributes.velocityInitial *= combinedAttachmentAttributes.projectileAttributes.velocityInitial; combinedAttributes.projectileAttributes.gravity *= combinedAttachmentAttributes.projectileAttributes.gravity; combinedAttributes.projectileAttributes.deceleration *= combinedAttachmentAttributes.projectileAttributes.deceleration; combinedAttributes.projectileAttributes.lifespan *= combinedAttachmentAttributes.projectileAttributes.lifespan; // additions combinedAttributes.burstCount += combinedAttachmentAttributes.burstCount; combinedAttributes.ammoMax += combinedAttachmentAttributes.ammoMax; combinedAttributes.consumption += combinedAttachmentAttributes.consumption; combinedAttributes.projectileAttributes.ricochetCountInitial += combinedAttachmentAttributes.projectileAttributes.ricochetCountInitial; //projectileSpreads = copiedAttributes.projectileSpreads; combinedAttributes.projectileAttributes.prefabProjectile = combinedAttachmentAttributes.projectileAttributes.prefabProjectile != null ? combinedAttachmentAttributes.projectileAttributes.prefabProjectile : combinedAttributes.projectileAttributes.prefabProjectile; } } public override string GetItemType() { return "Weapon"; } }
using log4net.Core; using System; using System.Collections.Generic; using System.Linq; using System.Net; using com.Sconit.Entity.MSG; using com.Sconit.Entity.CUST; namespace com.Sconit.Service { public class BaseMgr { protected static log4net.ILog pubSubLog = log4net.LogManager.GetLogger("Log.PubSubErrLog"); } }
namespace Spring.Net.Sample.ConsoleApp.MyCodes { public interface IVehicleDriver { void Drive(); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using JustRipeFarm.ClassEntity; using MySql.Data.MySqlClient; namespace JustRipeFarm { public partial class FormOrder : Form { List<Product> productLists; List<Customer> customerLists; public string state = ""; public Order ord; public FormOrder() { InitializeComponent(); } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void btnDone_Click(object sender, EventArgs e) { if (state == "Edit") { UpdateOrder(); } else { if (String.IsNullOrEmpty(textBox1.Text)) { if (String.IsNullOrEmpty(Convert.ToString(comboBox1.Text))) { if (String.IsNullOrEmpty(Convert.ToString(textBox2.Text))) { if (String.IsNullOrEmpty(Convert.ToString(textBox3.Text))) { if (String.IsNullOrEmpty(Convert.ToString(textBox4.Text))) { if (String.IsNullOrEmpty(Convert.ToString(comboBox2.Text))) { if (String.IsNullOrEmpty(Convert.ToString(dateTimePicker1.Text))) { if (String.IsNullOrEmpty(Convert.ToString(dateTimePicker2.Text))) { if (String.IsNullOrEmpty(Convert.ToString(textBox5.Text))) { if (String.IsNullOrEmpty(Convert.ToString(textBox6.Text))) { if (String.IsNullOrEmpty(Convert.ToString(textBox7.Text))) { MessageBox.Show("Please fill up all the box"); } MessageBox.Show("Please fill up all the box"); } MessageBox.Show("Please fill up all the box"); } MessageBox.Show("Please fill up all the box"); } MessageBox.Show("Please fill up all the box"); } MessageBox.Show("Please fill up all the box"); } MessageBox.Show("Please fill up all the box"); } MessageBox.Show("Please fill up all the box"); } MessageBox.Show("Please fill up all the box"); } MessageBox.Show("Please fill up all the box"); } MessageBox.Show("Please fill up all the box"); } else { AddOrder(); } } } private void FormOrder_Load(object sender, EventArgs e) { InsertSQL order1= new InsertSQL(); //productLists = order1.GetPorductList(); if (state == "Edit") { textBox1.Text = ord.Description; comboBox1.Text = ord.Product_id.ToString(); textBox2.Text = ord.Quantity_box.ToString(); textBox3.Text = ord.Weight.ToString(); textBox4.Text = ord.PalletAllocation.ToString(); comboBox2.Text = ord.Customer_id.ToString(); dateTimePicker1.Value = ord.Order_date; dateTimePicker2.Value = ord.Collection_date; textBox5.Text = ord.Price.ToString(); textBox6.Text = ord.Status; textBox7.Text = ord.Remark; } } public void UpdateOrder() { Order ordi = new Order(); ordi.Id = ord.Id; ordi.Description = textBox1.Text; ordi.Product_id = Int32.Parse(comboBox1.Text); ordi.Quantity_box = Int32.Parse(textBox2.Text); ordi.Weight = Double.Parse(textBox3.Text); ordi.PalletAllocation = int.Parse(textBox4.Text); ordi.Customer_id = int.Parse(comboBox2.Text); ordi.Order_date = this.dateTimePicker2.Value; ordi.Collection_date = this.dateTimePicker2.Value; ordi.Price = double.Parse(textBox5.Text); ordi.Status = textBox6.Text; ordi.Remark = textBox7.Text; UpdateSQL ordHnd = new UpdateSQL(); int changerecord = ordHnd.UpdateOrder(ordi); MessageBox.Show(changerecord + " Your record is added"); this.Close(); } public void AddOrder() { Order ord = new Order(); ord.Description = textBox1.Text; ord.Product_id = Int32.Parse(comboBox1.Text); ord.Quantity_box = Int32.Parse(textBox2.Text); ord.Weight = Int32.Parse(textBox3.Text); ord.PalletAllocation = int.Parse(textBox4.Text); ord.Customer_id = int.Parse(comboBox2.Text); ord.Order_date = this.dateTimePicker1.Value; ord.Collection_date = this.dateTimePicker2.Value; ord.Price = double.Parse(textBox5.Text); ord.Status = textBox6.Text; ord.Remark = textBox7.Text; InsertSQL ordHnd = new InsertSQL(); int addrecord = ordHnd.addNewOrder(ord); MessageBox.Show(addrecord + "Your record is added"); this.Close(); } //public List<Crop> GetCropList() //{ // List<Crop> cropLists = new List<Crop>(); // MySqlDataReader rdr = null; // try // { // string stm = "SELECT * FROM crop"; // MySqlCommand cmd = new MySqlCommand(stm, MysqlDbc.Instance.getConn()); // rdr = cmd.ExecuteReader(); // while (rdr.Read()) // { // Crop cr = new Crop(); // cr.Id = rdr.GetInt32("id"); // cr.Name = rdr.GetString("name"); // cr.Type = rdr.GetString("type"); // cr.Quantity_plot = rdr.GetInt32("quantity_plot"); // cr.Remark = rdr.GetString("remark"); // Console.WriteLine("crop => " + cr); // cropLists.Add(cr); // } // } // catch (MySqlException ex) // { // Console.WriteLine("Error: {0}", ex.ToString()); // } // finally // { // if (rdr != null) // { // rdr.Close(); // } // } // return cropLists; //} public void testDataPassedtoHere() { // can delete later //if (state == "Edit") //{ // Console.WriteLine("Order Details =>"); // Console.WriteLine(ord.Customer_id); // Console.WriteLine(ord.Description); // Console.WriteLine(ord.PalletAllocation); // Console.WriteLine(ord.Order_date); // Console.WriteLine(ord.Collection_date); // Console.WriteLine("order details end"); //} } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SharpNES.Utility; namespace SharpNES.Test { class Program { static void Main(string[] args) { // Test logging var logger = new Logger<DefaultFormater, ConsoleStream>(LogLevel.Debug3); logger.Log(LogLevel.Info, "Main", "This is an Info message"); logger.Log(LogLevel.Warning, "Main", "This is an Warning message"); logger.Log(LogLevel.Error, "Main", "This is an Error message"); logger.Log(LogLevel.Fatal, "Main", "This is an Fatal message"); logger.Log(LogLevel.Debug, "Main", "This is a Debug message"); logger.Log(LogLevel.Debug2, "Main", "This is an Debug2 message"); logger.Log(LogLevel.Debug3, "Main", "This is an Debug3 message"); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //Por teclado se ingresa el valor hora, el nombre, la antigüedad (en años) y la cantidad de horas trabajadas en el mes de N empleados de una fábrica. //Se pide calcular el importe a cobrar teniendo en cuenta que el total (que resulta de multiplicar el valor hora por la cantidad de horas trabajadas), hay que sumarle la cantidad de años trabajados multiplicados por $ 150, y al total de todas esas operaciones restarle el 13% en concepto de descuentos. Mostrar el recibo correspondiente con el nombre, la antigüedad, el valor hora, el total a cobrar en bruto, el total de descuentos y el valor neto a cobrar de todos los empleados ingresados. Nota: Utilizar estructuras repetitivas y selectivas. namespace Ejercicio_08 { class Ejercicio_08 { static void Main(string[] args) { Console.Title = "Ejercicio 08"; float importeBruto; float importeNeto; // float total; float porcentajeDescuento; char respuesta = 's'; bool seguir = true; bool respuestaIncorrecta = false; do { Console.Write("Ingresar valor hora: "); float.TryParse(Console.ReadLine(), out float valorHora); Console.Write("Ingresar nombre: "); int.TryParse(Console.ReadLine(), out int nombre); Console.Write("Ingresar antiguedad: "); int.TryParse(Console.ReadLine(), out int antigüedad); Console.Write("Ingresar cantidad de horas trabajadas: "); int.TryParse(Console.ReadLine(), out int horasTrabajadas); importeBruto = (valorHora * horasTrabajadas) + (antigüedad * 150); porcentajeDescuento = importeBruto * (float)0.13; importeNeto = importeBruto - porcentajeDescuento; Console.WriteLine("Nombre: {0} \nAntiguedad: {1} \nValor hora: {2} \nTotal bruto: {3} \nDescuentos: {4} \nValor neto: {5}\n\n", nombre, antigüedad, valorHora, importeBruto, porcentajeDescuento, importeNeto); ; do { Console.Write("Continuar? s/n: "); char.TryParse(Console.ReadLine(), out respuesta); respuesta = char.ToLower(respuesta); if (respuesta == 'n') { seguir = false; //respuestaIncorrecta = false; } else if (respuesta != 's') { Console.WriteLine("Respuesta invalida."); respuestaIncorrecta = true; } } while (respuestaIncorrecta); } while (seguir); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Core.Abstract; using Core.Entities; namespace WebUI.Mocks { public class TrainInfoParserMock : ITrainInfoParser { public IEnumerable<Station> ParseStations(string stationsJson) { return new List<Station>() { new Station() }; } public IEnumerable<Wagon> ParseWagons(string wagonsJson) { throw new NotImplementedException(); } public IEnumerable<Train> ParseTrains(string trainsJson) { throw new NotImplementedException(); } public TicketRequestId ParseTicketRequestId(string requestIdJson) { throw new NotImplementedException(); } } }
// *********************************************************************** // Assembly : Alabo.App.Share // Author : zkclo // Created : 03-06-2018 // // Last Modified By : zkclo // Last Modified On : 04-06-2018 // *********************************************************************** // <copyright file="ViewAdminReward.cs" company="Alabo.App.Share"> // Copyright (c) . All rights reserved. // </copyright> // <summary></summary> // *********************************************************************** using Alabo.App.Share.Rewards.Domain.Entities; using Alabo.App.Share.Rewards.Domain.Enums; using Alabo.Domains.Enums; using Alabo.Framework.Basic.AutoConfigs.Domain.Configs; using Alabo.Framework.Tasks.Queues.Models; using Alabo.Users.Entities; using Alabo.Web.Mvc.Attributes; using Alabo.Web.Mvc.ViewModel; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using ZKCloud.Open.Share.Models; namespace Alabo.App.Share.Rewards.ViewModels { /// <summary> /// Class ViewAdminReward. /// </summary> [ClassProperty(Name = "分润数据", Icon = "fa fa-puzzle-piece", Description = "分润数据")] public class ViewAdminReward : BaseViewModel { /// <summary> /// Gets or sets the reward. /// </summary> /// <value>The reward.</value> public Reward Reward { get; set; } /// <summary> /// Gets or sets the share user. /// </summary> /// <value>The share user.</value> public User ShareUser { get; set; } /// <summary> /// Gets or sets the order user. /// </summary> /// <value>The order user.</value> public User OrderUser { get; set; } /// <summary> /// Gets or sets the type of the money. /// </summary> /// <value>The type of the money.</value> public MoneyTypeConfig MoneyType { get; set; } /// <summary> /// Gets or sets the share module. /// </summary> /// <value>The share module.</value> public ShareModule ShareModule { get; set; } /// <summary> /// Gets or sets the task module attribute. /// </summary> /// <value>The task module attribute.</value> public TaskModuleAttribute TaskModuleAttribute { get; set; } /// <summary> /// 根据Id自动生成12位序列号 /// </summary> [Display(Name = "编号")] [Field(ListShow = true, EditShow = true, SortOrder = 1, Link = "/Admin/Reward/Edit?id=[[RewardId]]", Width = "75")] public string Serial { get { var searSerial = $"9{Reward.Id.ToString().PadLeft(9, '0')}"; if (Reward.Id.ToString().Length == 10) { searSerial = $"{Reward.Id.ToString()}"; } return searSerial; } } public long RewardId { get; set; } public long OrderUserId { get; set; } public long ShareUserId { get; set; } public Guid ModuleId { get; set; } public long ShareModuleId { get; set; } /// <summary> /// 获得分润用户 /// </summary> /// <value>The share user.</value> [Required] [Display(Name = "分润用户")] [Field(ListShow = true, EditShow = false, SortOrder = 2, Link = "/admin/user/edit?id=[[ShareUserId]]", Width = "100")] public string ShareUserName { get; set; } /// <summary> /// 触发分润用户 /// </summary> [Required] [Display(Name = "触发用户")] [Field(ListShow = true, EditShow = false, SortOrder = 3, Link = "/admin/user/edit?id=[[OrderUserId]]", Width = "100")] public string OrderUserName { get; set; } /// <summary> /// 所属维度 /// </summary> [Required] [Display(Name = "所属维度")] [Field(ListShow = true, EditShow = false, SortOrder = 4, Link = "/Admin/Reward/ModuleConfigList?moduleid=[[ModuleId]]", Width = "100")] public string TaskModuleAttributeName { get; set; } /// <summary> /// 奖金/配置 /// </summary> [Required] [Display(Name = "奖金/配置")] [Field(ListShow = true, EditShow = false, SortOrder = 5, Link = "/Admin/Reward/EditMoudle?id=[[ShareModuleId]]&moduleId=[[ModuleId]]", Width = "100")] public string ShareModuleName { get; set; } /// <summary> /// 资产账户 /// </summary> [Required] [Display(Name = "资产账户")] [Field(ListShow = true, EditShow = false, SortOrder = 6, LabelColor = LabelColor.Brand, Width = "100")] public string MoneyTypeName { get; set; } /// <summary> /// 分润金额 /// </summary> [Required] [Display(Name = "分润金额")] [Field(ListShow = true, EditShow = false, SortOrder = 7, TableDispalyStyle = TableDispalyStyle.Code, Width = "100")] public decimal RewardAmount { get; set; } /// <summary> /// 账后金额 /// </summary> [Required] [Display(Name = "账后金额")] [Field(ListShow = true, EditShow = false, SortOrder = 8, TableDispalyStyle = TableDispalyStyle.Code, Width = "100")] public decimal AfterAmount { get; set; } /// <summary> /// 详情 /// </summary> [Required] [Display(Name = "详情")] [Field(ListShow = true, EditShow = false, SortOrder = 9, Width = "300")] public string Intro { get; set; } /// <summary> /// 状态 /// </summary> [Required] [Display(Name = "状态")] [Field(ListShow = true, EditShow = false, SortOrder = 10, Width = "80")] public FenRunStatus Status { get; set; } /// <summary> /// 分润时间 /// </summary> [Required] [Display(Name = "分润时间")] [Field(ListShow = true, EditShow = false, SortOrder = 11, Width = "110")] public string CreateTimeStr { get; set; } /// <summary> /// 获取链接 /// </summary> public IEnumerable<ViewLink> ViewLinks() { var quickLinks = new List<ViewLink> { new ViewLink("明细", "/Admin/Reward/Edit?id=[[RewardId]]", Icons.Edit, LinkType.ColumnLink) }; return quickLinks; } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Plotter.Tweet; using Plotter.Tweet.Processing; using Plotter.Tweet.Processing.Commands; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Plotter.Tests { [TestClass] public class DefaultTests : TestBase { [TestMethod] public void DefaultCommandTest_Empty() { var result = TestTweet(new Tweet.Tweet() { CreatorScreenName = "anna", Text = "" }); Assert.AreEqual("@anna " + DefaultCommand.DefaultMessage, result.GetMessageForSending()); } [TestMethod] public void DefaultCommandTest_Nonsense() { var result = TestTweet(new Tweet.Tweet() { CreatorScreenName = "anna", Text = "dzjfhuhf" }); Assert.AreEqual("@anna " + DefaultCommand.DefaultMessage, result.GetMessageForSending()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CharactersInrange { class Program { static void Main(string[] args) { char symbol1 = char.Parse(Console.ReadLine()); char symbol2 = char.Parse(Console.ReadLine()); CharactersBetweenSymbols(symbol1, symbol2); } static void CharactersBetweenSymbols(char sym1,char sym2) { for(char i=sym1;i<sym2;i++) { Console.WriteLine(i); } } } }
using ProgFrog.Interface.Model; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ProgFrog.WebApi.ViewModel { public class ProgrammingTaskViewModel { public string Id { get; set; } public string Description { get; set; } public ICollection<ParamsAndResults> ParamsAndResults { get; set; } = new List<ParamsAndResults>(); } }
using UnityEngine; namespace Assets.Scripts.Controllers.UsableObjects { public class CokeMachineInteractive : UsableObject { public GameObject CokePrefab; public Transform CokeSpawnPosition; protected override void Init() { base.Init(); var gmGo = GameObject.FindWithTag("GameManager"); if (gmGo != null) GameManager = gmGo.GetComponent<GameManager>(); } public override void Use(GameManager gameManager) { base.Use(gameManager); if (CurrencyManager.CurrentCurrency < 60) { GameManager.Player.MainHud.ShowHudText(Localization.Get("no_money"), HudTextColor.Red); } else { SpawnCoke(); CurrencyManager.AddCurrency(-60); } } private void SpawnCoke() { Instantiate(CokePrefab, CokeSpawnPosition.position, Quaternion.identity); SoundManager.PlaySFX(WorldConsts.AudioConsts.CokeMachine); } } }
using System; using System.Collections.Generic; using System.Text; using System.Web; using System.Collections.Specialized; namespace NunoGomes.Web.Configuration { public class ShortIDsProvider : NamingProvider { #region Private Fields private const string ID_PREFIX = "T"; private static object KeepLongIDsAttributeValueKey = new object(); #endregion Private Fields #region Public Methods private bool KeepOriginalID(System.Web.UI.Control control) { bool keepOriginalIDs = this.KeepOriginalIDs; #region KeepLongIDs Attribute Value Management if (!keepOriginalIDs) { if (HttpContext.Current.Items.Contains(KeepLongIDsAttributeValueKey)) { keepOriginalIDs = (bool)HttpContext.Current.Items[KeepLongIDsAttributeValueKey]; } else { string path = System.Web.HttpContext.Current.Request.Path.Replace(System.Web.HttpContext.Current.Request.ApplicationPath, string.Empty); if (this.ExceptionList != null && this.ExceptionList.Contains(path)) { keepOriginalIDs = true; ; } else { if (control.Page != null) { object[] atts = control.Page.GetType().GetCustomAttributes(true); foreach (Attribute att in atts) { if (att is KeepOriginalIDsAttribute) { keepOriginalIDs = ((KeepOriginalIDsAttribute)att).Enabled; break; } } } } HttpContext.Current.Items[KeepLongIDsAttributeValueKey] = keepOriginalIDs; } } #endregion KeepLongIDs Attribute Value Management return keepOriginalIDs; } #endregion Public Methods #region NamingProvider Implementation /// <summary> /// Generates the Control ID. /// </summary> /// <param name="name">The controls name.</param> /// <param name="control">The control.</param> /// <returns></returns> public override string SetControlID(string name, System.Web.UI.Control control) { if (this.KeepOriginalID(control)) { return name; } if (control == null) { throw new ArgumentNullException("control"); } if (control.NamingContainer == null) { return name; } NamingContainerControlCollection controlsCollection = control.NamingContainer.Controls as NamingContainerControlCollection; if (controlsCollection == null) { return name; } string shortid = null; ; if (!controlsCollection.ContainsName(name)) { shortid = string.Format("{0}{1}", ID_PREFIX, controlsCollection.GetUniqueControlSufix()); if (string.IsNullOrEmpty(name)) { name = shortid; } controlsCollection.RegisterControl(shortid, name, control); } else { shortid = control.ID; } return shortid; } #endregion NamingProvider Implementation } }
using System; using UBaseline.Shared.Node; using Uintra.Features.OpenGraph.Models; namespace Uintra.Features.OpenGraph.Services.Contracts { public interface IOpenGraphService { OpenGraphObject GetOpenGraphObject(INodeModel nodeModel, string defaultUrl = null); OpenGraphObject GetOpenGraphObject(Guid activityId, string defaultUrl = null); OpenGraphObject GetOpenGraphObject(string url); } }
using System; using System.ComponentModel; using System.Timers; using System.Windows; using System.Windows.Controls; namespace CODE.Framework.Wpf.Theme.Metro.Controls { /// <summary> /// Tab Control used specifically as a view host in a Metro Shell /// </summary> public class ShellTabControl : TabControl { /// <summary> /// Initializes a new instance of the <see cref="ShellTabControl"/> class. /// </summary> public ShellTabControl() { var descriptor = DependencyPropertyDescriptor.FromProperty(SelectedIndexProperty, typeof (TabControl)); if (descriptor != null) descriptor.AddValueChanged(this, (s, e) => { var mustRaisePageSwitchEvent = !HomePageVisible; if (SelectedIndex > -1 && HomePageVisible) { mustRaisePageSwitchEvent = false; HomePageVisible = false; } if (SelectedIndex == -1 && Items.Count == 0 && !HomePageVisible) { mustRaisePageSwitchEvent = false; HomePageVisible = true; } if (mustRaisePageSwitchEvent) { try { RaiseEvent(new RoutedEventArgs(PageSwitchedEvent, this)); } catch { } } }); } /// <summary>This event fires whenever the user switches to a different view (but not to and from the start page)</summary> public static readonly RoutedEvent PageSwitchedEvent = EventManager.RegisterRoutedEvent("PageSwitched", RoutingStrategy.Bubble, typeof (RoutedEventHandler), typeof (ShellTabControl)); /// <summary>This event fires whenever the user switches to a different view (but not to and from the start page)</summary> public event RoutedEventHandler PageSwitched { add { AddHandler(PageSwitchedEvent, value); } remove { RemoveHandler(PageSwitchedEvent, value); } } /// <summary> /// Called when <see cref="M:System.Windows.FrameworkElement.ApplyTemplate"/> is called. /// </summary> public override void OnApplyTemplate() { base.OnApplyTemplate(); if (Template == null) return; var headers = Template.FindName("HeaderPanel", this) as UIElement; if (headers != null) headers.MouseLeftButtonUp += (s, e) => { if (HomePageVisible) { HomePageVisible = false; if (SelectedIndex < 0 && _lastSelectedPage > -1) SelectedIndex = _lastSelectedPage; } }; var home = Template.FindName("HomePanel", this) as UIElement; if (home != null) home.MouseLeftButtonUp += (s, e) => MakeHomePageVisible(); } /// <summary> /// Makes the home page visible. /// </summary> public void MakeHomePageVisible() { if (!HomePageVisible) HomePageVisible = true; _lastSelectedPage = SelectedIndex; var timer = new Timer(300); timer.Elapsed += ((s2, e2) => { timer.Stop(); Dispatcher.BeginInvoke(new Action(HidePages), null); }); timer.Start(); } private void HidePages() { SelectedIndex = -1; } private int _lastSelectedPage = -1; /// <summary> /// Title for the home item in the tabs /// </summary> /// <value>The home title.</value> public string HomeTitle { get { return (string) GetValue(HomeTitleProperty); } set { SetValue(HomeTitleProperty, value); } } /// <summary> /// Title for the home item in the tabs /// </summary> public static readonly DependencyProperty HomeTitleProperty = DependencyProperty.Register("HomeTitle", typeof (string), typeof (ShellTabControl), new UIPropertyMetadata("Home")); /// <summary> /// Defines whether the homepage is the currently visible element /// </summary> /// <value> /// <c>true</c> if home page visible; otherwise, <c>false</c>. /// </value> public bool HomePageVisible { get { return (bool) GetValue(HomePageVisibleProperty); } set { SetValue(HomePageVisibleProperty, value); } } /// <summary> /// Defines whether the homepage is the currently visible element /// </summary> public static readonly DependencyProperty HomePageVisibleProperty = DependencyProperty.Register("HomePageVisible", typeof (bool), typeof (ShellTabControl), new UIPropertyMetadata(false)); /// <summary> /// Visual for the homepage /// </summary> /// <value> /// The home page. /// </value> public UIElement HomePage { get { return (UIElement) GetValue(HomePageProperty); } set { SetValue(HomePageProperty, value); } } /// <summary> /// Visual for the homepage /// </summary> public static readonly DependencyProperty HomePageProperty = DependencyProperty.Register("HomePage", typeof (UIElement), typeof (ShellTabControl), new UIPropertyMetadata(null)); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class FollowerCount : MonoBehaviour { private Text followerCount; // Start is called before the first frame update void Start() { followerCount = GetComponent<Text>(); } // Update is called once per frame void Update() { followerCount.text = "Followers:\n" + ( LineLeader.GetLeaderRosterSize() - 1 ); } }
using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace CG.Web.MegaApiClient.Tests.Context { [CollectionDefinition("AuthenticatedLoginTests")] public class AuthenticatedLoginTestsCollection : ICollectionFixture<AuthenticatedTestContext> { } public class AuthenticatedTestContext : TestContext, IDisposable { private const string MegaApiClientPasswordEnvironment = "MEGAAPICLIENT_PASSWORD"; internal const string Username = "megaapiclient@yopmail.com"; internal static readonly string Password = Environment.GetEnvironmentVariable(MegaApiClientPasswordEnvironment); internal const string FileLink = "https://mega.nz/#!bkwkHC7D!AWJuto8_fhleAI2WG0RvACtKkL_s9tAtvBXXDUp2bQk"; internal const string FolderLink = "https://mega.nz/#F!e1ogxQ7T!ee4Q_ocD1bSLmNeg9B6kBw"; internal const string FileId = "P8BBzaTS"; internal const string FolderId = "e5IjHLLJ"; internal const string SubFolderId = "CghQlTCa"; /* Storage layout +-Root (bsxVBKLL) | +-SharedFolder (e5IjHLLJ) (Outgoing Share) | |-SharedFile.jpg (P8BBzaTS) | +-SharedSubFolder (CghQlTCa) (Outgoing Share) +-Trash (j0wEGbTZ) +-Inbox (zhITTbIJ) +-Contacts +-SharedRemoteFolder (b0I0QDhA) (Incoming Share) |-SharedRemoteFile.jpg (e5wjkSJB) +-SharedRemoteSubFolder (KhZSWI7C) (Incoming Share / Subfolder of SharedRemoteFolder) |-SharedRemoteSubFile.jpg (HtonzYYY) +-SharedRemoteSubSubFolder (z1YCibCT) */ private readonly string[] systemNodes = { "bsxVBKLL", // Root "j0wEGbTZ", // Trash "zhITTbIJ", // Inbox }; private readonly string[] permanentFoldersRootNodes = { FolderId // SharedFolder }; private readonly string[] permanentFoldersNodes = { SubFolderId, // SharedSubFolder }; private readonly string[] permanentRemoteFoldersNodes = { "b0I0QDhA", // SharedRemoteFolder "KhZSWI7C", // SharedRemoteSubFolder "z1YCibCT", // SharedRemoteSubSubFolder }; private readonly string[] permanentFilesNodes = { FileId, // SharedFile.jpg }; private readonly string[] permanentRemoteFilesNodes = { "e5wjkSJB", // SharedRemoteFile.jpg "HtonzYYY", // SharedRemoteSubFile.jpg }; public string PermanentFilesNode { get { return this.permanentFilesNodes[0]; } } public virtual void Dispose() { this.Client.Logout(); } protected override void ConnectClient(IMegaApiClient client) { Assert.False(string.IsNullOrEmpty(Password), $"Environment variable {MegaApiClientPasswordEnvironment} not set."); client.Login(Username, Password); } protected override IEnumerable<string> GetProtectedNodes() { return this.systemNodes .Concat(this.permanentFoldersRootNodes) .Concat(this.permanentFoldersNodes) .Concat(this.permanentFilesNodes) .Concat(this.permanentRemoteFoldersNodes) .Concat(this.permanentRemoteFilesNodes); } protected override IEnumerable<string> GetPermanentNodes() { return this.permanentFoldersRootNodes; } } }
namespace GatewayEDI.Logging { /// <summary> Responsible for finding and creating <see cref="ILoggerFactory" /> /// instances which are being used to create loggers of a given implementation. </summary> public interface IFactoryResolver { /// <summary> Determines a factory which in turn creates an /// <see cref="ILog" /> instance based on a request for a named logger. </summary> /// <param name="logName"> The name of the requested logger. This name will also be used to determine the factory that is responsible to create the logger instance. </param> /// <returns> A factory which in turn is responsible for creating a given <see cref="ILog" /> implementation. </returns> ILogFactory GetFactory(string logName); } }
using CoreLocation; using MapKit; using System; using UIKit; using Xamarians.Maps; using Xamarians.Maps.iOS; using Xamarin.Forms; using Xamarin.Forms.Maps.iOS; using Xamarin.Forms.Platform.iOS; using System.Collections.ObjectModel; using Xamarin.Forms.Maps; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CoreGraphics; [assembly: ExportRenderer(typeof(ExtendedMap), typeof(ExtendedMapRenderer))] namespace Xamarians.Maps.iOS { public class ExtendedMapRenderer : MapRenderer { List<MKAnnotation> annotations = new List<MKAnnotation>(); static ExtendedMap element; MKMapView nativeMap; //bool isLoaded = false; MapDelegate mapDelegate; static MKCircleRenderer circleRenderer; static MKPolylineRenderer polylineRenderer; bool isCircle; static bool isLoaded = false; public new static void Init() { } protected override void OnElementChanged(ElementChangedEventArgs<View> e) { base.OnElementChanged(e); if (isLoaded) { nativeMap.RemoveOverlays(nativeMap.Overlays); } if (e.NewElement == null) return; if (e.OldElement != null) { nativeMap = Control as MKMapView; } element = Element as ExtendedMap; mapDelegate = new MapDelegate(); nativeMap = Control as MKMapView; nativeMap.Delegate = null; nativeMap.Delegate = mapDelegate; var formsMap = (ExtendedMap)e.NewElement; CLLocationCoordinate2D[] coords = new CLLocationCoordinate2D[element.RouteCoordinates.Count]; int index = 0; int idCounter = 1; string icon = ""; icon = element.ImageSource; foreach (var circle in element.Circles) { var annot = new CustomAnnotation(new CLLocationCoordinate2D(circle.Position.Latitude, circle.Position.Longitude), element.CustomPins.FirstOrDefault().Label, "", false, icon); annot.Id = idCounter++; nativeMap.AddAnnotation(annot); //pinCollection.Add(annot.Id, item); annotations.Add(annot); var circleOverlay = MKCircle.Circle(new CLLocationCoordinate2D(circle.Position.Latitude, circle.Position.Longitude), circle.Radius); nativeMap.AddOverlay(circleOverlay); } foreach (var position in element.RouteCoordinates) { var annot = new CustomAnnotation(new CLLocationCoordinate2D(position.Latitude, position.Longitude), element.CustomPins.FirstOrDefault().Label, "", false, icon); annot.Id = idCounter++; nativeMap.AddAnnotation(annot); //pinCollection.Add(annot.Id, item); annotations.Add(annot); coords[index] = new CLLocationCoordinate2D(position.Latitude, position.Longitude); index++; } var routeOverlay = MKPolyline.FromCoordinates(coords); nativeMap.AddOverlay(routeOverlay); } public class MapDelegate : MKMapViewDelegate { bool _regionChanged = false; public event EventHandler RegionChangedEvent; public event EventHandler<MKUserLocation> UserLocationChanged; protected string annotationId = "MapAnnotation"; public override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation) { MKAnnotationView annotationView = null; MKPinAnnotationView annotationPinView = null; if (annotation is MKUserLocation) return null; var cAnnotation = annotation as CustomAnnotation; if (annotation is CustomAnnotation) { // show conference annotation annotationView = mapView.DequeueReusableAnnotation(annotationId); if (annotationView == null) { annotationView = new MKAnnotationView(annotation, annotationId); } if (annotationPinView == null) { annotationPinView = new MKPinAnnotationView(annotation, annotationId); } annotationView.CanShowCallout = true; UIImage image = (annotationPinView as MKPinAnnotationView).Image; if (!string.IsNullOrWhiteSpace(((CustomAnnotation)annotation).Icon)) { image = UIImage.FromBundle(((CustomAnnotation)annotation).Icon); annotationView.Image = image; annotationView.CenterOffset = new CGPoint(0, -image.Size.Height / 2); } else { annotationView.Image = image; annotationView.CenterOffset = new CGPoint(9, -image.Size.Height/3); } var detailButton = UIButton.FromType(UIButtonType.InfoLight); //// detailButton.SetImage(UIImage.FromFile("ic_lesson_hotspot_start.png"), UIControlState.Normal); detailButton.TouchUpInside += (s, e) => { if (cAnnotation.Id != 0) { element.HandleClick(); } }; annotationView.RightCalloutAccessoryView = detailButton; } return annotationView; } public override MKOverlayRenderer OverlayRenderer(MKMapView mapView, IMKOverlay overlayWrapper) { var type = overlayWrapper.GetType(); var overlay = overlayWrapper as IMKOverlay; if (overlay is MKPolyline || type == typeof(MKPolyline)) { if (polylineRenderer == null) { polylineRenderer = new MKPolylineRenderer(overlay as MKPolyline); //polylineRenderer.FillColor = UIColor.Blue; polylineRenderer.StrokeColor = UIColor.Red; polylineRenderer.LineWidth = 5; isLoaded = true; } return polylineRenderer; } else if (overlay is MKCircle) { if (circleRenderer == null) { circleRenderer = new MKCircleRenderer(overlay as MKCircle); circleRenderer.FillColor = UIColor.Red; circleRenderer.Alpha = 0.2f; isLoaded = true; } return circleRenderer; } return base.OverlayRenderer(mapView, overlayWrapper); } } } public class CustomAnnotation : MKAnnotation { string title, subtitle; CLLocationCoordinate2D coordinate; public EventHandler<CLLocationCoordinate2D> DragEnd; public EventHandler Clicked; public bool IsLocationIcon { get; set; } #region Overridden Properties public override CLLocationCoordinate2D Coordinate { get { return coordinate; } } public override string Title { get { return title; } } public override string Subtitle { get { return subtitle; } } #endregion public int Id { get; set; } public string Icon { get; set; } public bool IsDraggable { get; set; } public CustomAnnotation(CLLocationCoordinate2D coordinate, string title, string subtitle, bool locationIcon, string icon) { this.coordinate = coordinate; this.title = title; this.subtitle = subtitle; this.Icon = icon; this.IsLocationIcon = locationIcon; } } }
using System.Collections.Generic; using UnityEngine; using Zenject; using MapGeneration; namespace Pathfinding { public class AStarPathfinding : MonoBehaviour { private SignalBus signalBus; private MapGenerator mapGenerator; [Inject] public void Initialize(SignalBus _signalBus, MapGenerator _mapGenerator) { signalBus = _signalBus; mapGenerator = _mapGenerator; } public void FindPath(Vector2 startPosition, Vector2 endPosition) { AStarNode startNode = mapGenerator.nodes[(int)startPosition.x, (int)startPosition.y] as AStarNode; AStarNode endNode = mapGenerator.nodes[(int)endPosition.x, (int)endPosition.y] as AStarNode; List<AStarNode> unvisitedNodes = new List<AStarNode>(); HashSet<AStarNode> visitedNodes = new HashSet<AStarNode>(); unvisitedNodes.Add(startNode); while (unvisitedNodes.Count > 0) { AStarNode currentNode = unvisitedNodes[0]; for (int i = 1; i < unvisitedNodes.Count; i++) { if (unvisitedNodes[i].FCost < currentNode.FCost || unvisitedNodes[i].FCost == currentNode.FCost && unvisitedNodes[i].HCost < currentNode.HCost) { currentNode = unvisitedNodes[i]; } } unvisitedNodes.Remove(currentNode); visitedNodes.Add(currentNode); if (currentNode == endNode) { signalBus.Fire(new PathFoundSignal() { startingNode = startNode, endNode = endNode }); return; } foreach (AStarNode neighbour in currentNode.Neighbours) { if (neighbour.IsObstructed || visitedNodes.Contains(neighbour)) { continue; } int MoveCost = (int)currentNode.GCost + NodeDistanceCalculator.GetDistance(currentNode.Position, neighbour.Position); if (MoveCost < neighbour.GCost || !unvisitedNodes.Contains(neighbour)) { neighbour.GCost = MoveCost; neighbour.HCost = NodeDistanceCalculator.GetDistance(neighbour.Position, endNode.Position); neighbour.Parent = currentNode; if (!unvisitedNodes.Contains(neighbour)) { unvisitedNodes.Add(neighbour); } } } } } } }
using System.Linq; using GridMvc; using Welic.Dominio.Models.Marketplaces.Entityes; namespace WebApi.Models.Grids { public class CustomFieldsGrid : Grid<MetaField> { public CustomFieldsGrid(IQueryable<MetaField> items) : base(items) { } } }
namespace Slayer.Models { public class Character { public Dice HitDice { get; set; } public string Name { get; set; } public int Experience { get; set; } public int CurrentHps { get; set; } public int Strength { get; set; } public int Stamina { get; set; } public int Wisdom { get; set; } public int AvailableStatPoints { get; set; } public int Level { get; set; } public int Gold { get; set; } public Weapon Weapon { get; set; } public Shield Shield { get; set; } public Armor Armor { get; set; } public Character() { Level = 1; AvailableStatPoints = 5; CurrentHps = MaxHps(); Strength = 20; Stamina = 20; Wisdom = 20; Gold = 200; } public int MaxHps() { return Stamina*5; } public void LevelUp() { if (Experience < ExperienceTable.GetBaseXpForLevel(Level + 1) || Level == 20) return; Level++; AvailableStatPoints++; CurrentHps = MaxHps(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Victory : MonoBehaviour { public charBehaviour charScript; public UIScript timer; private int ennemies; private GameObject[] boufs; // Start is called before the first frame update void Start() { boufs = GameObject.FindGameObjectsWithTag("bouf"); ennemies = boufs.Length; } void Update() { if(charScript.poid >= ennemies && timer.timing >= 0) { timer.SendMessage("win"); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace TheQuest.Models { public class Map { [Key] public int MapId { get; set; } public float Longitude { get; set; } public float Latitude { get; set; } public string Name { get; set; } public float Size { get; set; } public ICollection<Enemy> Enemies { get; set; } public ICollection<Character> Characters { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio11 { class NumerosReais { static void Main(string[] args) { { { float F = 345.3456f; double D = 6.89765432127866; decimal DE = 1234567897654300.14567896543m; Console.WriteLine(F + "<" + D + "<" + DE); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnParticles : MonoBehaviour { public Vector3 min; public Vector3 max; public GameObject water; public int numWater = 10; public float waterSpeed = 1; public GameObject air; public int numAir = 10; public float airSpeed = 10; // Use this for initialization void Start () { for (int i = 0; i < numWater; ++i) { GameObject p = Instantiate (water, new Vector3 (Random.Range (min.x, max.x), Random.Range (min.y, max.y), Random.Range (min.z, max.z)), new Quaternion ()); Vector3 velocity = new Vector3 (Random.Range (-1f, 1f), Random.Range (-1f, 1f), Random.Range (-1f, 1f)); velocity.Normalize (); velocity.Scale (new Vector3 (waterSpeed, waterSpeed, waterSpeed)); p.GetComponent<Rigidbody> ().velocity = velocity; } for (int i = 0; i < numAir; ++i) { GameObject p = Instantiate (air, new Vector3 (Random.Range (min.x, max.x), Random.Range (min.y, max.y), Random.Range (min.z, max.z)), new Quaternion ()); Vector3 velocity = new Vector3 (Random.Range (-1f, 1f), Random.Range (-1f, 1f), Random.Range (-1f, 1f)); velocity.Normalize (); velocity.Scale (new Vector3 (airSpeed, airSpeed, airSpeed)); p.GetComponent<Rigidbody> ().velocity = velocity; } } // Update is called once per frame void Update () { } }
using IntegrationAdapters.Controllers; using IntegrationAdaptersTests.DataFactory; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Xunit; using Moq; using IntegrationAdapters.MicroserviceComunicator; using IntegrationAdapters.Dtos; namespace IntegrationAdaptersTests.UnitTests { public class ApiRegisterTests { [Fact] public async void Successfully_registers_api() { var pharmacy = CreatePharmacy.CreateValidTestObject(); var controller = GetPharmacyController(); var result = await controller.ApiRegister(new PharmacySystemDTO { Name = pharmacy.Name, ApiKey = pharmacy.ApiKey, Url = pharmacy.Url }); Assert.IsType<RedirectToActionResult>(result); } [Fact] public async void Does_not_successfully_register_api() { var pharmacy = CreatePharmacy.CreateInvalidTestObject(); var controller = GetPharmacyController(); controller.ModelState.AddModelError("Url", "Required"); var result = await controller.ApiRegister(new PharmacySystemDTO { Name = pharmacy.Name, ApiKey = pharmacy.ApiKey, Url = pharmacy.Url }); Assert.IsType<BadRequestObjectResult>(result); } private PharmacyController GetPharmacyController() { var mockService = new Mock<IPharmacySystemService>(); var tempData = new TempDataDictionary(new DefaultHttpContext(), Mock.Of<ITempDataProvider>()) { ["Success"] = "Registration successful!" }; return new PharmacyController(mockService.Object) { TempData = tempData }; } } }
using Microsoft.Xna.Framework; using Terraria; using Terraria.ModLoader; using Terraria.ID; using System; namespace StarlightRiver.Items.Vitric { public class VitricBow : ModItem { public override void SetDefaults() { item.width = 38; item.height = 34; item.useStyle = 5; item.useAnimation = 28; item.useTime = 28; item.shootSpeed = 8f; item.shoot = 1; item.knockBack = 2f; item.damage = 12; item.useAmmo = AmmoID.Arrow; item.rare = 2; item.UseSound = SoundID.Item5; item.noMelee = true; item.ranged = true; } public override bool Shoot(Player player, ref Vector2 position, ref float speedX, ref float speedY, ref int type, ref int damage, ref float knockBack) { Vector2 aim = Vector2.Normalize(Main.MouseWorld - player.Center); int proj = Projectile.NewProjectile(player.Center, (aim * 8.5f).RotatedBy(0.1f), type, damage, knockBack, player.whoAmI); Main.projectile[proj].scale = 0.5f; Main.projectile[proj].damage /= 2; Main.projectile[proj].noDropItem = true; int proj2 = Projectile.NewProjectile(player.Center, (aim * 8.5f).RotatedBy(-0.1f), type, damage, knockBack, player.whoAmI); Main.projectile[proj2].scale = 0.5f; Main.projectile[proj2].damage /= 2; Main.projectile[proj2].noDropItem = true; return true; } public override void SetStaticDefaults() { DisplayName.SetDefault("Vitric Bow"); Tooltip.SetDefault("Shoots two arrows at once"); } } }
using Microsoft.Extensions.Configuration; using System; namespace TelegramFootballBot.Core { public static class AppSettings { private static readonly IConfiguration _configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json", false, true).Build(); public static TimeSpan DistributionTime => TimeSpan.Parse(_configuration["distributionTime"]); public static TimeSpan GameDay => TimeSpan.Parse(_configuration["gameDay"]); public static int BotOwnerChatId => int.Parse(_configuration["botOwnerChatId"]); public static bool NotifyOwner { get; set; } = true; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; namespace NPCAI.Actions { public class FollowAction : Action { public float StoppingDistance { get { return stoppingDistance; } set { stoppingDistance = value; } } private float stoppingDistance = 0.8f; private Transform target; //different constructors depending on how many points already existing at //time of action creaction and what format they're in. public FollowAction (NavMeshAgent agent) { this.agent = agent; updateRequired = true; } public FollowAction (NavMeshAgent agent, Transform target) { this.agent = agent; this.target = target; updateRequired = true; } public FollowAction (NavMeshAgent agent, Transform target, float stoppingDistance) { this.agent = agent; this.target = target; this.stoppingDistance = stoppingDistance; updateRequired = true; } public Transform GetTarget () { return target; } public void SetTarget (Transform target) { this.target = target; GotoTarget(); } void GotoTarget () { // Returns if no points have been set up if (target == null) return; // Set the agent to go to the currently selected destination. agent.destination = target.position; // Enabling auto-braking means the agent will slow down //as it approaches the target. agent.autoBraking = true; //The agent will stop within StoppingDistance of the target. agent.stoppingDistance = StoppingDistance; } //Overriding methods from Action abstract class. public override void StartAction () { base.StartAction(); GotoTarget(); } public override void UpdateAction () { base.UpdateAction(); GotoTarget(); } public override void ResumeAction () { base.ResumeAction(); GotoTarget(); } } }
namespace PlanetHunters.Data.Store { using DTO; using Models; using System; using System.Collections.Generic; public static class DiscoveryStore { public static void AddDiscovery(IEnumerable<DiscoveryDto> discoveries) { using (var context = new PlanetHuntersContext()) { foreach (var discoveryDto in discoveries) { if (discoveryDto.DateMade == null ) { Console.WriteLine("Invalid data format."); } else { var discovery = new Discovery { DateMade = discoveryDto.DateMade, Observers = null, Pioneers = null, Planets = null, Stars = null, TelescopeUsed = TelescopeStore.GetTelescopeByName(discoveryDto.Telescope) }; context.Discoveries.Add(discovery); Console.WriteLine($"Discovery ({discovery.DateMade}-{discovery.TelescopeUsed.Name}) with {discovery.Stars.Count} star(s), {discovery.Planets.Count} planet(s), {discovery.Pioneers.Count} pioneer(s) and {discovery.Observers.Count} observers successfully imported."); } } context.SaveChanges(); } } } }
using Alabo.Domains.Repositories; using Alabo.Industry.Cms.Articles.Domain.Entities; using MongoDB.Bson; namespace Alabo.Industry.Cms.Articles.Domain.Repositories { public interface IArticleRepository : IRepository<Article, ObjectId> { } }
using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { private Rigidbody2D rigidbody; public float speed; Animation animation; // public GameObject MAX; float moveHorizontal, moveVertical; Vector2 movement; // Use this for initialization void Start () { rigidbody = GetComponent<Rigidbody2D>(); animation = GetComponent<Animation>(); animation.Play("idle"); movement = new Vector2(0.0f, 0.0f); } // Update is called once per frame void Update () { if (Input.GetKey("up")) { animation.Play("jump"); } else if (Input.GetKey("space")) { animation.Play("flip"); } else if (Input.GetKey("down")) { animation.Play("walk"); speed = 0.5f; moveHorizontal = (rigidbody.gameObject.transform.position.x) + 0.5f; rigidbody.velocity = (movement * speed) * -1; transform.position = new Vector3((transform.position.x + 0.25f), 0f, 0f); } else if (Input.GetKey("right")) { animation.Play("run"); moveHorizontal = (rigidbody.gameObject.transform.position.x)+1.0f; speed = 1f; movement = new Vector2(moveHorizontal, 0.0f); rigidbody.velocity = (movement * speed)*-1; transform.position = new Vector3((transform.position.x+0.5f),0f,0f); } // speed = 0f; else { rigidbody.velocity = new Vector2(0f,0f); animation.Play("idle"); } } void FixedUpdate() { } }
namespace SAAS.FrameWork.Mq.Mng { public interface IServerMqBuilder { IServerMq BuildMq(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BallScript : MonoBehaviour { private AudioSource wallsound; private AudioSource badwallhit; public int playerThatScores = 0; public EasyPong mainScript; // Use this for initialization void Start () { AudioSource[] soundsource = GetComponents<AudioSource>(); wallsound = soundsource[0]; badwallhit = soundsource[1]; } // Update is called once per frame void Update () { } private void OnCollisionEnter(Collision collision) { if (collision.collider.tag == "Wall") { // play the sound wallsound.Play(); } else if (collision.collider.tag == "player1wall") { badwallhit.Play(); playerThatScores = 1; Debug.Log("PLAYER THAT SCORE IS" + playerThatScores); mainScript.RegisterScore(playerThatScores); } else if (collision.collider.tag == "player2wall") { badwallhit.Play(); playerThatScores = 2; Debug.Log("PLAYER THAT SCORE IS" + playerThatScores); mainScript.RegisterScore(playerThatScores); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Text; using WebStore.Domain.Entities.Base; namespace WebStore.Domain.Entities { [Table("Products")] public class Product : ProductEntity { [ForeignKey("SectionId")] public virtual Section Section { get; set; } [ForeignKey("BrandId")] public virtual Brand Brand { get; set; } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using MSTestFramework.Actions; using MSTestFramework.DataProvider; using MSTestFramework.Helpers; using NLog.Internal; using OpenQA.Selenium; using System.IO; using System.Linq; using System.Reflection; using System.Threading; namespace MSTestFramework.Tests { [TestClass] public class BrowserActionsTests : TestHelper { [TestMethod] [TestProperty("TestType", "UI")] public void PageTitleTest() { var browserActions = new BrowserActions(Driver); Driver.Url = "http://the-internet.herokuapp.com/"; Assert.AreEqual("The Internet", browserActions.GetPageTitle(), "The page titles didn't match."); } [TestMethod] [TestProperty("TestType", "UI")] public void UrlTest() { var browserActions = new BrowserActions(Driver); Driver.Url = "http://the-internet.herokuapp.com/"; Assert.AreEqual("http://the-internet.herokuapp.com/", browserActions.GetUrl(), "The url's didn't match."); } [TestMethod] [TestProperty("TestType", "UI")] public void SwitchToNewestWindowTest() { var browserActions = new BrowserActions(Driver); var elementActions = new ElementActions(Driver); Driver.Url = "http://the-internet.herokuapp.com/"; elementActions.Click(By.XPath("//a[text()='Multiple Windows']")); elementActions.Click(By.XPath("//a[text()='Click Here']")); browserActions.SwitchToNewestWindow(); Assert.AreEqual("New Window", browserActions.GetPageTitle(), "The newest window page title didn't match."); } [TestMethod] [TestProperty("TestType", "UI")] public void SwitchToWindowWithNameTest() { var browserActions = new BrowserActions(Driver); var elementActions = new ElementActions(Driver); Driver.Url = "http://the-internet.herokuapp.com/"; elementActions.Click(By.XPath("//a[text()='Multiple Windows']")); elementActions.Click(By.XPath("//a[text()='Click Here']")); var windows = Driver.WindowHandles; browserActions.SwitchToWindow(windows.Last()); Assert.AreEqual("New Window", browserActions.GetPageTitle(), "The newest window page title didn't match."); } [TestMethod] [TestProperty("TestType", "UI")] [DoNotParallelize] public void DownloadFileTest() { var elementActions = new ElementActions(Driver); Driver.Url = "http://the-internet.herokuapp.com/"; elementActions.Click(By.XPath("//a[text()='File Download']")); var items = elementActions.GetElementsAsList(By.XPath("//div[@class='example']/a")); var downloadFile = items[1].Text; var downloadPath = string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DownloadLocation"].ToString()) ? $"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\\downloads\\" : System.Configuration.ConfigurationManager.AppSettings["DownloadLocation"]; FileHelper.DeleteFile(downloadPath, downloadFile); elementActions.Click(items[1]); FileHelper.WaitForFileDownload(downloadFile, downloadPath); Assert.IsTrue(File.Exists($"{downloadPath}\\{downloadFile}"), "The file wasn't downloaded successfully."); } [TestMethod] [TestProperty("TestType", "UI")] [DoNotParallelize] public void CustomDownloadFileLocationTest() { var elementActions = new ElementActions(Driver); Driver.Url = "http://the-internet.herokuapp.com/"; elementActions.Click(By.XPath("//a[text()='File Download']")); var items = elementActions.GetElementsAsList(By.XPath("//div[@class='example']/a")); var downloadFile = items[1].Text; var downloadPath = string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DownloadLocation"].ToString()) ? $"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\\downloads\\" : System.Configuration.ConfigurationManager.AppSettings["DownloadLocation"]; FileHelper.DeleteFile(downloadPath, downloadFile); elementActions.Click(items[1]); FileHelper.WaitForFileDownload(downloadFile, downloadPath); Assert.IsTrue(File.Exists($"{downloadPath}\\{downloadFile}"), "The file wasn't downloaded successfully."); } [TestMethod] [TestProperty("TestType", "UI")] [DoNotParallelize] public void DeleteFileTest() { var elementActions = new ElementActions(Driver); Driver.Url = "http://the-internet.herokuapp.com/"; elementActions.Click(By.XPath("//a[text()='File Download']")); var items = elementActions.GetElementsAsList(By.XPath("//div[@class='example']/a")); var downloadFile = items[1].Text; var downloadPath = string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["DownloadLocation"].ToString()) ? $"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\\downloads\\" : System.Configuration.ConfigurationManager.AppSettings["DownloadLocation"]; FileHelper.DeleteFile(downloadPath, downloadFile); elementActions.Click(items[1]); FileHelper.WaitForFileDownload(downloadFile, downloadPath); FileHelper.DeleteFile(downloadPath, downloadFile); Assert.IsFalse(File.Exists($"{downloadPath}\\{downloadFile}"), "The file wasn't deleted successfully."); } } }
using System; using System.ComponentModel; using System.Threading.Tasks; using Xamarin.Forms; using KSF_Surf.ViewModels; using KSF_Surf.Models; namespace KSF_Surf.Views { [DesignTimeVisible(false)] public partial class MapsMapPRPage : ContentPage { private readonly MapsViewModel mapsViewModel; private readonly string mapsMapTitle; private bool hasLoaded = false; // objects used by "Personal Record" call private MapPRInfoDatum prInfoData; // variables for filters private readonly EFilter_Game game; private EFilter_Mode currentMode = EFilter_Mode.none; private readonly EFilter_Mode defaultMode = BaseViewModel.propertiesDict_getMode(); private readonly string map; private readonly bool hasZones; private readonly bool hasStages; private EFilter_PlayerType playerType; private string playerValue; private string playerSteamID; private string playerRank; private readonly string meSteamID = BaseViewModel.propertiesDict_getSteamID(); public MapsMapPRPage(string title, EFilter_Game game, string map, bool hasZones, bool hasStages) { mapsMapTitle = title; this.game = game; this.map = map; this.hasZones = hasZones; this.hasStages = hasStages; playerValue = meSteamID; playerSteamID = meSteamID; playerType = EFilter_PlayerType.me; mapsViewModel = new MapsViewModel(); InitializeComponent(); Title = mapsMapTitle + " " + EFilter_ToString.toString(defaultMode) + "]"; if (!hasZones) ZoneRecordsOption.IsVisible = false; if (!hasStages) CCPOption.IsVisible = false; } // UI ----------------------------------------------------------------------------------------------- #region UI private async Task ChangePR(EFilter_Mode newMode, EFilter_PlayerType newPlayerType, string newPlayerValue) { if (currentMode == newMode && newPlayerType == playerType && newPlayerValue == playerValue) return; var prInfoDatum = await mapsViewModel.GetMapPRInfo(game, newMode, map, newPlayerType, newPlayerValue); prInfoData = prInfoDatum?.data; if (prInfoData is null || prInfoData.basicInfo is null) { hidePR(); await DisplayAlert("Could not find player profile!", "Invalid SteamID or rank.", "OK"); return; } currentMode = newMode; playerType = newPlayerType; playerValue = newPlayerValue; playerSteamID = prInfoData.basicInfo.steamID; Title = mapsMapTitle + " " + EFilter_ToString.toString(currentMode) + "]"; PRTitleLabel.Text = String_Formatter.toEmoji_Country(prInfoData.basicInfo.country) + " " + prInfoData.basicInfo.name; if (prInfoData.time is null || prInfoData.time == "0") // no main completion { hidePR(); return; } displayPR(); playerRank = prInfoData.rank.ToString(); LayoutPRInfo(); } // Displaying Changes ------------------------------------------------------------------------------- private void LayoutPRInfo() { bool isR1 = (prInfoData.rank == 1); CPROption.IsVisible = !isR1; if (hasStages) CCPOption.IsVisible = !isR1; PagesStack.IsVisible = !(!hasZones && isR1); // Info ----------------------------------------------------------------- string time = String_Formatter.toString_RankTime(prInfoData.time) + " (WR"; if (isR1) { if (prInfoData.r2Diff is null || prInfoData.r2Diff == "0") { time += " N/A"; } else { time += "-" + String_Formatter.toString_RankTime(prInfoData.r2Diff.Substring(1)); } } else { time += "+" + String_Formatter.toString_RankTime(prInfoData.wrDiff); } TimeLabel.Text = time + ")"; string rank = prInfoData.rank + "/" + prInfoData.totalRanks; if (!(prInfoData.group is null)) { if (isR1) { rank = "[WR] " + rank; } else if (prInfoData.rank <= 10) { rank = "[Top10] " + rank; } else { rank = "[G" + prInfoData.group + "] " + rank; } } RankLabel.Text = rank; CompletionsLabel.Text = prInfoData.count; if (!(prInfoData.attempts is null)) { string percent = String_Formatter.toString_CompletionPercent(prInfoData.count, prInfoData.attempts); CompletionsLabel.Text += "/" + prInfoData.attempts + " (" + percent + ")"; } if (!(prInfoData.total_time is null)) { ZoneTimeLabel.Text = String_Formatter.toString_PlayTime(prInfoData.total_time, true); } else { ZoneTimeLabel.Text = ""; } DateSetLabel.Text = String_Formatter.toString_KSFDate(prInfoData.date); if (!(prInfoData.date_lastplayed is null)) { LastPlayedLabel.Text = String_Formatter.toString_LastOnline(prInfoData.date_lastplayed); } else { LastPlayedLabel.Text = ""; } // Velocity ------------------------------------------------------------- string units = " u/s"; AvgVelLabel.Text = ((int)double.Parse(prInfoData.avgvel)) + units; StartVelLabel.Text = ((int)double.Parse(prInfoData.startvel)) + units; EndVelLabel.Text = ((int)double.Parse(prInfoData.endvel)) + units; // First Completion ----------------------------------------------------- if (!(prInfoData.first_date is null)) { FirstDateLabel.Text = String_Formatter.toString_KSFDate(prInfoData.first_date); FirstTimeLabel.Text = String_Formatter.toString_PlayTime(prInfoData.first_timetaken, true); FirstAttemptsLabel.Text = prInfoData.first_attempts; } else { FirstDateLabel.Text = ""; FirstTimeLabel.Text = ""; FirstAttemptsLabel.Text = ""; } } private void hidePR() { playerRank = ""; CPROption.IsVisible = false; CCPOption.IsVisible = false; if (!hasZones) PagesStack.IsVisible = false; PRStack.IsVisible = false; NoPRLabel.IsVisible = true; } private void displayPR() { CPROption.IsVisible = true; if (hasStages) CCPOption.IsVisible = true; PagesStack.IsVisible = true; PRStack.IsVisible = true; NoPRLabel.IsVisible = false; } #endregion // Event Handlers ---------------------------------------------------------------------------------- #region events protected override async void OnAppearing() { if (!hasLoaded) { hasLoaded = true; await ChangePR(defaultMode, playerType, playerValue); LoadingAnimation.IsRunning = false; MapsMapPRScrollView.IsVisible = true; } } private async void Filter_Pressed(object sender, EventArgs e) { if (hasLoaded && BaseViewModel.hasConnection()) { await Navigation.PushAsync(new MapsMapPRFilterPage(ApplyFilters, currentMode, playerType, playerSteamID, playerRank, defaultMode, meSteamID)); } else { await DisplayNoConnectionAlert(); } await MapsMapPRScrollView.ScrollToAsync(0, 0, true); } internal async void ApplyFilters(EFilter_Mode newMode, EFilter_PlayerType newPlayerType, string newPlayerValue) { LoadingAnimation.IsRunning = true; await ChangePR(newMode, newPlayerType, newPlayerValue); LoadingAnimation.IsRunning = false; } private async void PR_Tapped(object sender, EventArgs e) { PRButton.Style = App.Current.Resources["TappedStackStyle"] as Style; if (BaseViewModel.hasConnection()) { await Navigation.PushAsync(new MapsMapPRDetailsPage(Title, game, currentMode, defaultMode, map, playerSteamID)); } else { await DisplayNoConnectionAlert(); } PRButton.Style = App.Current.Resources["UntappedStackStyle"] as Style; } private async void CPR_Tapped(object sender, EventArgs e) { CPRButton.Style = App.Current.Resources["TappedStackStyle"] as Style; if (BaseViewModel.hasConnection()) { await Navigation.PushAsync(new MapsMapCPRPage(Title, game, currentMode, map, playerSteamID)); } else { await DisplayNoConnectionAlert(); } CPRButton.Style = App.Current.Resources["UntappedStackStyle"] as Style; } private async void CCP_Tapped(object sender, EventArgs e) { CCPButton.Style = App.Current.Resources["TappedStackStyle"] as Style; if (BaseViewModel.hasConnection()) { await Navigation.PushAsync(new MapsMapCCPPage(Title, game, currentMode, map, playerSteamID)); } else { await DisplayNoConnectionAlert(); } CCPButton.Style = App.Current.Resources["UntappedStackStyle"] as Style; } private async Task DisplayNoConnectionAlert() { await DisplayAlert("Could not connect to KSF!", "Please connect to the Internet.", "OK"); } #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class ScroolDown : MonoBehaviour { public float speedscrool; private bool sopro; private Vector3 targetposition; public float speed; private EnemyIA inimigo; private string originaltag; private IEnumerator cair; void Awake () { sopro = false; originaltag = tag; cair = Cair (); } void Start(){ StartCoroutine (cair); } void OnTriggerEnter2D(Collider2D other) { if (other.CompareTag("TriggerChupa")) { tag=("ChupaFood"); sopro = true; targetposition = other.transform.position; inimigo = other.GetComponentInParent<EnemyIA>(); } } void OnEnable(){ Controller.OnDeath += Parar; } void OnDisable(){ Controller.OnDeath -= Parar; } void Parar(){ StopCoroutine (cair); } public IEnumerator Cair(){ while (true) { if(!sopro){ transform.Translate (0.0f, -1 * Time.deltaTime * FoodManager.speedscrool, 0); } else{ transform.position = Vector3.MoveTowards(transform.position, targetposition, speed * Time.deltaTime); if(!inimigo.chupar){ tag=originaltag; sopro=false; } } yield return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GDS.Entity { [Serializable] public class ModelBase { public int Id { get; set; } public DateTime? CreateTime { get; set; } //创建时间 public string CreateBy { get; set; } //创建人 public DateTime? UpdateTime { get; set; } //最后修改时间 public string UpdateBy { get; set; } //最后人 //public DateTime? DeleteTime { get; set; } //删除时间 //public string DeleteBy { get; set; } //删除人 public int IsDelete { get; set; } //1表示删除 public string Remark { get; set; } //备注 描述信息 } }
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using service.Models; namespace service { [Produces("application/json")] [Route("api/[controller]")] public class EkycController : ControllerBase { public Logmodel log = new Logmodel(); private Dictionary<object, object> Apiflow_default_condition; private Dictionary<object, object> raw_data; [HttpGet] public async Task<IActionResult> Get() { return StatusCode(200, "Ekyc"); } [HttpPost] public async Task<IActionResult> Post() { Logmodel log = new Logmodel(); var body = ""; using (var mem = new MemoryStream()) using (var reader = new StreamReader(mem)) { Request.Body.CopyTo(mem); body = reader.ReadToEnd(); mem.Seek(0, SeekOrigin.Begin); body = reader.ReadToEnd(); } object Datalake = ""; var Datalake_status = ""; var request_data = JObject.Parse(body); Openaccount open = new Openaccount(); Check_customer chk = new Check_customer(); try { switch (request_data["apiname"].ToString()) { case "dipchip": Apiflow_default_condition = new Dictionary<object, object>(); _ = log.swan_core_log("EKYC"," transter Tiger diffship : " + JsonConvert.SerializeObject(body)); try { _ = log.swan_core_log("EKYC", " Data before Save : " + JsonConvert.SerializeObject(request_data)); Mysqlhawk hawk = new Mysqlhawk(); var param_ins = new Dictionary<object, object>(); param_ins.Add("channel", "Tiger_Windows"); param_ins.Add("date_request", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); param_ins.Add("citizenid", request_data["data"]["Id"].ToString()); param_ins.Add("ThaiName", request_data["data"]["ThaiName"].ToString()); param_ins.Add("EngName", request_data["data"]["EngName"].ToString()); param_ins.Add("EnglishNameWithPrefix", request_data["data"]["EnglishNameWithPrefix"].ToString()); param_ins.Add("EnglishSurname", request_data["data"]["EnglishSurname"].ToString()); param_ins.Add("DateOfBirth", request_data["data"]["DateOfBirth"].ToString()); param_ins.Add("ThaiDOB", request_data["data"]["ThaiDOB"].ToString()); param_ins.Add("Gender", request_data["data"]["Gender"].ToString()); param_ins.Add("BP1", request_data["data"]["BP1"].ToString()); param_ins.Add("Issuer", request_data["data"]["Issuer"].ToString()); param_ins.Add("IssuerCode", request_data["data"]["IssuerCode"].ToString()); param_ins.Add("DateOfIssue", request_data["data"]["DateOfIssue"].ToString()); param_ins.Add("ThaiDOI", request_data["data"]["ThaiDOI"].ToString()); param_ins.Add("DateOfExpiry", request_data["data"]["DateOfExpiry"].ToString()); param_ins.Add("ThaiDOE", request_data["data"]["ThaiDOE"].ToString()); param_ins.Add("TypeCode", request_data["data"]["TypeCode"].ToString()); param_ins.Add("Address", request_data["data"]["Address"].ToString()); param_ins.Add("PhotoId", request_data["data"]["PhotoId"].ToString()); param_ins.Add("photo_raw", request_data["data"]["images"].ToString()); param_ins.Add("chipid", request_data["data"]["ChipId"].ToString()); param_ins.Add("status", "Y"); param_ins.Add("consent_dopa", "N"); param_ins.Add("consent_date", ""); param_ins.Add("consent_status", ""); param_ins.Add("user_request", ""); var ins_data = hawk.data_ins("trn_dopa", JsonConvert.SerializeObject(param_ins)); _ = log.swan_core_log("EKYC", " Inse Tiger diffship : " + JsonConvert.SerializeObject(ins_data)); Apiflow_default_condition.Add("apiname", request_data["apiname"].ToString()); Apiflow_default_condition.Add("version", request_data["version"].ToString()); Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Apiflow_default_condition.Add("response", "transfer data Complete"); Datalake_status = "true"; } catch (Exception e) { _ = log.swan_core_log("EKYC", " Inse Tiger diffship Error : " + e.ToString()); Apiflow_default_condition = new Dictionary<object, object>(); Apiflow_default_condition.Add("info", "Web Api Access Not allow"); Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Apiflow_default_condition.Add("response", e.ToString()); Datalake_status = "fail"; } break; case "dipchip_android": Apiflow_default_condition = new Dictionary<object, object>(); _ = log.swan_core_log("EKYC", " transter Tiger diffship : " + JsonConvert.SerializeObject(body)); try { Mysqlhawk hawk = new Mysqlhawk(); var param_ins = new Dictionary<object, object>(); param_ins.Add("channel", "android"); param_ins.Add("date_request", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); param_ins.Add("citizenid", request_data["data"]["Id"].ToString()); param_ins.Add("ThaiName", request_data["data"]["ThaiName"].ToString()); param_ins.Add("EngName", request_data["data"]["EngName"].ToString()); param_ins.Add("EnglishNameWithPrefix", request_data["data"]["EnglishNameWithPrefix"].ToString()); param_ins.Add("EnglishSurname", request_data["data"]["EnglishSurname"].ToString()); param_ins.Add("DateOfBirth", request_data["data"]["DateOfBirth"].ToString()); param_ins.Add("ThaiDOB", request_data["data"]["ThaiDOB"].ToString()); param_ins.Add("Gender", request_data["data"]["Gender"].ToString()); param_ins.Add("BP1", request_data["data"]["BP1"].ToString()); param_ins.Add("Issuer", request_data["data"]["Issuer"].ToString()); param_ins.Add("IssuerCode", request_data["data"]["IssuerCode"].ToString()); param_ins.Add("DateOfIssue", request_data["data"]["DateOfIssue"].ToString()); param_ins.Add("ThaiDOI", request_data["data"]["ThaiDOI"].ToString()); param_ins.Add("DateOfExpiry", request_data["data"]["DateOfExpiry"].ToString()); param_ins.Add("ThaiDOE", request_data["data"]["ThaiDOE"].ToString()); param_ins.Add("TypeCode", request_data["data"]["TypeCode"].ToString()); param_ins.Add("Address", request_data["data"]["Address"].ToString()); param_ins.Add("PhotoId", request_data["data"]["PhotoId"].ToString()); param_ins.Add("photo_raw", request_data["data"]["images"].ToString()); param_ins.Add("chipid", request_data["data"]["ChipId"].ToString()); param_ins.Add("status", "Y"); param_ins.Add("consent_dopa", "N"); param_ins.Add("consent_date", ""); param_ins.Add("consent_status", ""); param_ins.Add("user_request", ""); var ins_data = hawk.data_ins("trn_dopa", JsonConvert.SerializeObject(param_ins)); _ = log.swan_core_log("EKYC", " Inse Tiger diffship : " + JsonConvert.SerializeObject(ins_data)); Apiflow_default_condition.Add("apiname", request_data["apiname"].ToString()); Apiflow_default_condition.Add("version", request_data["version"].ToString()); Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Apiflow_default_condition.Add("response", "transfer data Complete"); Datalake_status = "true"; } catch (Exception e) { _ = log.swan_core_log("EKYC", " Inse Tiger diffship Error : " + e.ToString()); Apiflow_default_condition = new Dictionary<object, object>(); Apiflow_default_condition.Add("info", "Web Api Access Not allow"); Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Apiflow_default_condition.Add("response", e.ToString()); Datalake_status = "fail"; } break; case "dipchip_ios": Apiflow_default_condition = new Dictionary<object, object>(); _ = log.swan_core_log("EKYC", " transter Tiger diffship : " + JsonConvert.SerializeObject(body)); try { Mysqlhawk hawk = new Mysqlhawk(); var param_ins = new Dictionary<object, object>(); param_ins.Add("channel", "ios"); param_ins.Add("date_request", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); param_ins.Add("citizenid", request_data["data"]["Id"].ToString()); param_ins.Add("ThaiName", request_data["data"]["ThaiName"].ToString()); param_ins.Add("EngName", request_data["data"]["EngName"].ToString()); param_ins.Add("EnglishNameWithPrefix", request_data["data"]["EnglishNameWithPrefix"].ToString()); param_ins.Add("EnglishSurname", request_data["data"]["EnglishSurname"].ToString()); param_ins.Add("DateOfBirth", request_data["data"]["DateOfBirth"].ToString()); param_ins.Add("ThaiDOB", request_data["data"]["ThaiDOB"].ToString()); param_ins.Add("Gender", request_data["data"]["Gender"].ToString()); param_ins.Add("BP1", request_data["data"]["BP1"].ToString()); param_ins.Add("Issuer", request_data["data"]["Issuer"].ToString()); param_ins.Add("IssuerCode", request_data["data"]["IssuerCode"].ToString()); param_ins.Add("DateOfIssue", request_data["data"]["DateOfIssue"].ToString()); param_ins.Add("ThaiDOI", request_data["data"]["ThaiDOI"].ToString()); param_ins.Add("DateOfExpiry", request_data["data"]["DateOfExpiry"].ToString()); param_ins.Add("ThaiDOE", request_data["data"]["ThaiDOE"].ToString()); param_ins.Add("TypeCode", request_data["data"]["TypeCode"].ToString()); param_ins.Add("Address", request_data["data"]["Address"].ToString()); param_ins.Add("PhotoId", request_data["data"]["PhotoId"].ToString()); param_ins.Add("photo_raw", request_data["data"]["images"].ToString()); param_ins.Add("chipid", request_data["data"]["ChipId"].ToString()); param_ins.Add("status", "Y"); param_ins.Add("consent_dopa", "N"); param_ins.Add("consent_date", ""); param_ins.Add("consent_status", ""); param_ins.Add("user_request", ""); var ins_data = hawk.data_ins("trn_dopa", JsonConvert.SerializeObject(param_ins)); _ = log.swan_core_log("EKYC", " Inse Tiger diffship : " + JsonConvert.SerializeObject(ins_data)); Apiflow_default_condition.Add("apiname", request_data["apiname"].ToString()); Apiflow_default_condition.Add("version", request_data["version"].ToString()); Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Apiflow_default_condition.Add("response", "transfer data Complete"); Datalake_status = "true"; } catch (Exception e) { _ = log.swan_core_log("EKYC", " Inse Tiger diffship Error : " + e.ToString()); Apiflow_default_condition = new Dictionary<object, object>(); Apiflow_default_condition.Add("info", "Web Api Access Not allow"); Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Apiflow_default_condition.Add("response", e.ToString()); Datalake_status = "fail"; } break; case "nfc": Apiflow_default_condition = new Dictionary<object, object>(); _ = log.swan_core_log("EKYC", " transter Tiger diffship : " + JsonConvert.SerializeObject(body)); try { Mysqlhawk hawk = new Mysqlhawk(); var param_ins = new Dictionary<object, object>(); param_ins.Add("channel", "nfc"); param_ins.Add("date_request", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); param_ins.Add("citizenid", request_data["data"]["Id"].ToString()); param_ins.Add("ThaiName", request_data["data"]["ThaiName"].ToString()); param_ins.Add("EngName", request_data["data"]["EngName"].ToString()); param_ins.Add("EnglishNameWithPrefix", request_data["data"]["EnglishNameWithPrefix"].ToString()); param_ins.Add("EnglishSurname", request_data["data"]["EnglishSurname"].ToString()); param_ins.Add("DateOfBirth", request_data["data"]["DateOfBirth"].ToString()); param_ins.Add("ThaiDOB", request_data["data"]["ThaiDOB"].ToString()); param_ins.Add("Gender", request_data["data"]["Gender"].ToString()); param_ins.Add("BP1", request_data["data"]["BP1"].ToString()); param_ins.Add("Issuer", request_data["data"]["Issuer"].ToString()); param_ins.Add("IssuerCode", request_data["data"]["IssuerCode"].ToString()); param_ins.Add("DateOfIssue", request_data["data"]["DateOfIssue"].ToString()); param_ins.Add("ThaiDOI", request_data["data"]["ThaiDOI"].ToString()); param_ins.Add("DateOfExpiry", request_data["data"]["DateOfExpiry"].ToString()); param_ins.Add("ThaiDOE", request_data["data"]["ThaiDOE"].ToString()); param_ins.Add("TypeCode", request_data["data"]["TypeCode"].ToString()); param_ins.Add("Address", request_data["data"]["Address"].ToString()); param_ins.Add("PhotoId", request_data["data"]["PhotoId"].ToString()); param_ins.Add("photo_raw", request_data["data"]["images"].ToString()); param_ins.Add("chipid", request_data["data"]["ChipId"].ToString()); param_ins.Add("status", "Y"); param_ins.Add("consent_dopa", "N"); param_ins.Add("consent_date", ""); param_ins.Add("consent_status", ""); param_ins.Add("user_request", ""); var ins_data = hawk.data_ins("trn_dopa", JsonConvert.SerializeObject(param_ins)); _ = log.swan_core_log("EKYC", " Inse Tiger diffship : " + JsonConvert.SerializeObject(ins_data)); Apiflow_default_condition.Add("apiname", request_data["apiname"].ToString()); Apiflow_default_condition.Add("version", request_data["version"].ToString()); Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Apiflow_default_condition.Add("response", "transfer data Complete"); Datalake_status = "true"; } catch (Exception e) { _ = log.swan_core_log("EKYC", " Inse Tiger diffship Error : " + e.ToString()); Apiflow_default_condition = new Dictionary<object, object>(); Apiflow_default_condition.Add("info", "Web Api Access Not allow"); Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Apiflow_default_condition.Add("response", e.ToString()); Datalake_status = "fail"; } break; case "consent_dopa": Apiflow_default_condition = new Dictionary<object, object>(); _ = log.swan_core_log("dopa", " Request consent dopa : " + JsonConvert.SerializeObject(body)); try { //Mysqlhawk hawk = new Mysqlhawk(); var laser_data = new Dictionary<object, object>(); laser_data.Add("apiname", "laser"); laser_data.Add("PIN", request_data["PIN"].ToString()); laser_data.Add("FirstName", request_data["FirstName"].ToString()); laser_data.Add("LastName", request_data["LastName"].ToString()); laser_data.Add("BirthDay", request_data["BirthDay"].ToString()); laser_data.Add("Laser", request_data["Laser"].ToString()); _ = log.swan_core_log("dopa", " Cleansin EKYC : " + JsonConvert.SerializeObject(laser_data)); var dopadata = await Dopa_model.call_service_dopa("lasercode", JsonConvert.SerializeObject(laser_data)); _ = log.swan_core_log("dopa", " Request consent dopa data : " + JsonConvert.SerializeObject(dopadata)); Apiflow_default_condition.Add("apiname", request_data["apiname"].ToString()); Apiflow_default_condition.Add("version", request_data["version"].ToString()); Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Apiflow_default_condition.Add("response", dopadata["status"].ToString()); Datalake_status = "true"; } catch (Exception e) { _ = log.swan_core_log("dopa", " Error : " + e.ToString()); Apiflow_default_condition = new Dictionary<object, object>(); Apiflow_default_condition.Add("info", "Web Api Access Not allow"); Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Apiflow_default_condition.Add("response", e.ToString()); Datalake_status = "fail"; } break; case "consent_ndid": Apiflow_default_condition = new Dictionary<object, object>(); _ = log.swan_core_log("EKYC", " transter Tiger diffship : " + JsonConvert.SerializeObject(body)); try { // Mysqlhawk hawk = new Mysqlhawk(); var ndid_raw_data = new Dictionary<object, object>(); ndid_raw_data.Add("cardid", request_data["cardid"].ToString()); ndid_raw_data.Add("idps", request_data["idps"].ToString()); var ndid_data = await NDID_model.call_service_ndid("verifly_request", JsonConvert.SerializeObject(ndid_raw_data)); // นำ ข้อมูลมา Prse ต่อ Apiflow_default_condition.Add("apiname", request_data["apiname"].ToString()); Apiflow_default_condition.Add("version", request_data["version"].ToString()); Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Apiflow_default_condition.Add("response", ndid_data); Datalake_status = "true"; } catch (Exception e) { _ = log.swan_core_log("EKYC", " Inse Tiger diffship Error : " + e.ToString()); Apiflow_default_condition = new Dictionary<object, object>(); Apiflow_default_condition.Add("info", "Web Api Access Not allow"); Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Apiflow_default_condition.Add("response", e.ToString()); Datalake_status = "fail"; } break; default: Apiflow_default_condition = new Dictionary<object, object>(); Apiflow_default_condition.Add("info", "Web Api Access Not allow"); Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Datalake_status = "fail"; break; } } catch (Exception e) { Apiflow_default_condition = new Dictionary<object, object>(); Apiflow_default_condition.Add("Error", e.ToString()); Apiflow_default_condition.Add("info", "Web Api Access Not allow"); Apiflow_default_condition.Add("response time", DateTime.Now.ToString("dd-MM-yyy HH':'mm':'ss")); Datalake_status = " "; } var status_api = ""; if (Datalake_status == "Create") { status_api = "201"; } else if (Datalake_status == "true") { status_api = "200"; } else if (Datalake_status == "fail") { status_api = "400"; } else if (Datalake_status == " ") { status_api = "500"; } return StatusCode(Int32.Parse(status_api), Apiflow_default_condition); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace StackingCups_CS { public class Program { public static bool isNumeric(string g){ int m; bool is_numeric = int.TryParse(g, out m); return is_numeric; } public static void Main(string[] args) { int num = int.Parse(Console.ReadLine()); List<string> list = new List<string>(); for(int i=0;i<num;i++){ string input = Console.ReadLine(); list.Add(input); } var dict = new Dictionary<int, string>(); var whatever = new List<int>(); for(int j=0;j<num;j++){ string[] g = list[j].Split(); if(isNumeric(g[0])){ int temp = int.Parse(g[0]) / 2; dict[temp] = g[1]; // whatever.Add(temp); }else{ dict[int.Parse(g[1])] = g[0]; // whatever.Add(int.Parse(g[1])); } } var list_ = dict.Keys.ToList(); list_.Sort(); foreach(var key in list_){ Console.WriteLine(dict[key]); } } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using System.Linq; using System.Diagnostics; using NLog; namespace JhinBot.Services { public interface IBotServiceProvider : IServiceProvider, IEnumerable<object> { T GetService<T>(); } public class ServiceProvider : IBotServiceProvider { public class ServiceProviderBuilder { private ConcurrentDictionary<Type, object> _dict = new ConcurrentDictionary<Type, object>(); private readonly Logger _log; public ServiceProviderBuilder() { _log = LogManager.GetCurrentClassLogger(); } public ServiceProviderBuilder AddManual<T>(T obj) { _dict.TryAdd(typeof(T), obj); return this; } public ServiceProvider Build() { return new ServiceProvider(_dict); } public ServiceProviderBuilder LoadFrom(Assembly assembly) { var allTypes = assembly.GetTypes(); var services = new Queue<Type>(allTypes .Where(x => x.GetInterfaces().Contains(typeof(IService)) && !x.GetTypeInfo().IsInterface && !x.GetTypeInfo().IsAbstract) .ToArray()); var interfaces = new HashSet<Type>(allTypes .Where(x => x.GetInterfaces().Contains(typeof(IService)) && x.GetTypeInfo().IsInterface)); var alreadyFailed = new Dictionary<Type, int>(); var sw = Stopwatch.StartNew(); var swInstance = new Stopwatch(); while (services.Count > 0) { var type = services.Dequeue(); //get a type i need to make an instance of if (_dict.TryGetValue(type, out _)) // if that type is already instantiated, skip continue; var ctor = type.GetConstructors()[0]; var argTypes = ctor .GetParameters() .Select(x => x.ParameterType) .ToArray(); // get constructor argument types i need to pass in var args = new List<object>(argTypes.Length); foreach (var arg in argTypes) //get constructor arguments from the dictionary of already instantiated types { if (_dict.TryGetValue(arg, out var argObj)) //if i got current one, add it to the list of instances and move on args.Add(argObj); else //if i failed getting it, add it to the end, and break { services.Enqueue(type); if (alreadyFailed.ContainsKey(type)) { alreadyFailed[type]++; if (alreadyFailed[type] > 3) _log.Warn(type.Name + " wasn't instantiated in the first 3 attempts. Missing " + arg.Name + " type"); } else alreadyFailed.Add(type, 1); break; } } if (args.Count != argTypes.Length) continue; // _log.Info("Loading " + type.Name); swInstance.Restart(); var instance = ctor.Invoke(args.ToArray()); swInstance.Stop(); if (swInstance.Elapsed.TotalSeconds > 5) _log.Info($"{type.Name} took {swInstance.Elapsed.TotalSeconds:F2}s to load."); var interfaceType = interfaces.FirstOrDefault(x => instance.GetType().GetInterfaces().Contains(x)); if (interfaceType != null) _dict.TryAdd(interfaceType, instance); _dict.TryAdd(type, instance); } sw.Stop(); _log.Info($"All services loaded in {sw.Elapsed.TotalSeconds:F2}s"); return this; } } private readonly ImmutableDictionary<Type, object> _services; private ServiceProvider() { } public ServiceProvider(IDictionary<Type, object> services) { _services = services.ToImmutableDictionary(); } public T GetService<T>() { return (T)((IServiceProvider)(this)).GetService(typeof(T)); } object IServiceProvider.GetService(Type serviceType) { _services.TryGetValue(serviceType, out var toReturn); return toReturn; } IEnumerator IEnumerable.GetEnumerator() => _services.Values.GetEnumerator(); public IEnumerator<object> GetEnumerator() => _services.Values.GetEnumerator(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class NoDestroy : MonoBehaviour { private static Dictionary<string, GameObject> _instances = new Dictionary<string, GameObject>(); public string ID; void Awake() { if (_instances.ContainsKey(ID)) { var existing = _instances[ID]; if (existing != null) { if (ReferenceEquals(gameObject, existing)) return; Destroy(gameObject); return; } } _instances[ID] = gameObject; DontDestroyOnLoad(gameObject); } }
namespace OpenApiLib.Json.Models { public class MessageJson<T> : AbstractJson { public T Data { get; set; } public ErrorJson Error { get; set; } } }
// Copyright (c) 2020, mParticle, Inc // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using MP.Json; using MP.Json.Validation; using Xunit; namespace JsonSchemaTestSuite.Draft4 { public class Dependencies { /// <summary> /// 1 - dependencies /// </summary> [Theory] [InlineData( "neither", "{ }", true )] [InlineData( "nondependant", "{ 'foo':1 }", true )] [InlineData( "with dependency", "{ 'bar':2, 'foo':1 }", true )] [InlineData( "missing dependency", "{ 'bar':2 }", false )] [InlineData( "ignores arrays", "[ 'bar' ]", true )] [InlineData( "ignores strings", "'foobar'", true )] [InlineData( "ignores other non-objects", "12", true )] public void DependenciesTest(string desc, string data, bool expected) { // dependencies Console.Error.WriteLine(desc); string schemaData = "{ 'dependencies':{ 'bar':[ 'foo' ] } }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft4 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 2 - multiple dependencies /// </summary> [Theory] [InlineData( "neither", "{ }", true )] [InlineData( "nondependants", "{ 'bar':2, 'foo':1 }", true )] [InlineData( "with dependencies", "{ 'bar':2, 'foo':1, 'quux':3 }", true )] [InlineData( "missing dependency", "{ 'foo':1, 'quux':2 }", false )] [InlineData( "missing other dependency", "{ 'bar':1, 'quux':2 }", false )] [InlineData( "missing both dependencies", "{ 'quux':1 }", false )] public void MultipleDependencies(string desc, string data, bool expected) { // multiple dependencies Console.Error.WriteLine(desc); string schemaData = "{ 'dependencies':{ 'quux':[ 'foo', 'bar' ] } }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft4 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 3 - multiple dependencies subschema /// </summary> [Theory] [InlineData( "valid", "{ 'bar':2, 'foo':1 }", true )] [InlineData( "no dependency", "{ 'foo':'quux' }", true )] [InlineData( "wrong type", "{ 'bar':2, 'foo':'quux' }", false )] [InlineData( "wrong type other", "{ 'bar':'quux', 'foo':2 }", false )] [InlineData( "wrong type both", "{ 'bar':'quux', 'foo':'quux' }", false )] public void MultipleDependenciesSubschema(string desc, string data, bool expected) { // multiple dependencies subschema Console.Error.WriteLine(desc); string schemaData = "{ 'dependencies':{ 'bar':{ 'properties':{ 'bar':{ 'type':'integer' }, 'foo':{ 'type':'integer' } } } } }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft4 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } /// <summary> /// 4 - dependencies with escaped characters /// </summary> [Theory] [InlineData( "valid object 1", @"{ 'foo\nbar':1, 'foo\rbar':2 }", true )] [InlineData( "valid object 2", @"{ 'a':2, 'b':3, 'c':4, 'foo\tbar':1 }", true )] [InlineData( "valid object 3", @"{ ""foo\""bar"":2, ""foo'bar"":1 }", true )] [InlineData( "invalid object 1", @"{ 'foo':2, 'foo\nbar':1 }", false )] [InlineData( "invalid object 2", @"{ 'a':2, 'foo\tbar':1 }", false )] [InlineData( "invalid object 3", @"{ ""foo'bar"":1 }", false )] [InlineData( "invalid object 4", @"{ 'foo\'bar':2 }", false )] public void DependenciesWithEscapedCharacters(string desc, string data, bool expected) { // dependencies with escaped characters Console.Error.WriteLine(desc); string schemaData = @"{ ""dependencies"":{ ""foo\tbar"":{ ""minProperties"":4 }, ""foo\nbar"":[ ""foo\rbar"" ], ""foo\""bar"":[ ""foo'bar"" ], ""foo'bar"":{ ""required"":[ ""foo\""bar"" ] } } }"; MPJson schemaJson = MPJson.Parse(schemaData); MPJson json = MPJson.Parse(data); MPSchema schema = schemaJson; var validator = new JsonValidator { Strict = true, Version = SchemaVersion.Draft4 }; bool actual = validator.Validate(schema, json); Assert.Equal(expected, actual); } } }
using System; namespace DomainEventsExemplo.Domain.Entites { internal class Encomenda { public Encomenda(int clienteId, int objetoId) { ClienteId = clienteId; ObjetoId = objetoId; } public Encomenda(int clienteId, int objetoId, DateTime dataEntregaPrevista) { ClienteId = clienteId; ObjetoId = objetoId; DataEntregaPrevista = dataEntregaPrevista; } public int ClienteId { get; } public int ObjetoId { get; } public DateTime DataEntregaPrevista { get; } = DateTime.Now.AddDays(7); } }
using SciVacancies.Domain.Enums; using SciVacancies.Domain.Events; using SciVacancies.ReadModel.Core; using System; using MediatR; using NPoco; using AutoMapper; namespace SciVacancies.ReadModel.EventHandlers { public class VacancyApplicationEventsHandler : INotificationHandler<VacancyApplicationCreated>, INotificationHandler<VacancyApplicationUpdated>, INotificationHandler<VacancyApplicationRemoved>, INotificationHandler<VacancyApplicationApplied>, INotificationHandler<VacancyApplicationCancelled>, INotificationHandler<VacancyApplicationWon>, INotificationHandler<VacancyApplicationPretended>, INotificationHandler<VacancyApplicationLost> { private readonly IDatabase _db; public VacancyApplicationEventsHandler(IDatabase db) { _db = db; } public void Handle(VacancyApplicationCreated message) { var vacancyApplication = Mapper.Map<VacancyApplication>(message); using (var transaction = _db.GetTransaction()) { _db.Insert(vacancyApplication); if (vacancyApplication.attachments != null) { foreach (var at in vacancyApplication.attachments) { if (at.guid == Guid.Empty) at.guid = Guid.NewGuid(); at.vacancyapplication_guid = vacancyApplication.guid; _db.Insert(at); } } transaction.Complete(); } } public void Handle(VacancyApplicationUpdated message) { var vacancyApplication = _db.SingleById<VacancyApplication>(message.VacancyApplicationGuid); var updatedVacancyApplication = Mapper.Map<VacancyApplication>(message); //TODO - без костыля updatedVacancyApplication.creation_date = vacancyApplication.creation_date; //updatedVacancyApplication.read_id = vacancyApplication.read_id; using (var transaction = _db.GetTransaction()) { _db.Update(updatedVacancyApplication); //TODO - без удаления _db.Execute(new Sql($"DELETE FROM res_vacancyapplication_attachments WHERE vacancyapplication_guid = @0", message.VacancyApplicationGuid)); if (updatedVacancyApplication.attachments != null) { foreach (var at in updatedVacancyApplication.attachments) { if (at.guid == Guid.Empty) at.guid = Guid.NewGuid(); at.vacancyapplication_guid = vacancyApplication.guid; _db.Insert(at); } } transaction.Complete(); } } public void Handle(VacancyApplicationRemoved message) { using (var transaction = _db.GetTransaction()) { _db.Execute(new Sql($"UPDATE res_vacancyapplications SET status = @0, update_date = @1 WHERE guid = @2", VacancyApplicationStatus.Removed, message.TimeStamp, message.VacancyApplicationGuid)); transaction.Complete(); } } public void Handle(VacancyApplicationApplied message) { using (var transaction = _db.GetTransaction()) { _db.Execute(new Sql($"UPDATE res_vacancyapplications SET apply_date = @0, status = @1, update_date = @2 WHERE guid = @3", message.TimeStamp, VacancyApplicationStatus.Applied, message.TimeStamp, message.VacancyApplicationGuid)); transaction.Complete(); } } public void Handle(VacancyApplicationCancelled message) { using (var transaction = _db.GetTransaction()) { _db.Execute(new Sql($"UPDATE res_vacancyapplications SET status = @0, update_date = @1 WHERE guid = @2", VacancyApplicationStatus.Cancelled, message.TimeStamp, message.VacancyApplicationGuid)); transaction.Complete(); } } public void Handle(VacancyApplicationWon message) { using (var transaction = _db.GetTransaction()) { _db.Execute(new Sql($"UPDATE res_vacancyapplications SET status = @0, update_date = @1 WHERE guid = @2", VacancyApplicationStatus.Won, message.TimeStamp, message.VacancyApplicationGuid)); transaction.Complete(); } } public void Handle(VacancyApplicationPretended message) { using (var transaction = _db.GetTransaction()) { _db.Execute(new Sql($"UPDATE res_vacancyapplications SET status = @0, update_date = @1 WHERE guid = @2", VacancyApplicationStatus.Pretended, message.TimeStamp, message.VacancyApplicationGuid)); transaction.Complete(); } } public void Handle(VacancyApplicationLost message) { using (var transaction = _db.GetTransaction()) { _db.Execute(new Sql($"UPDATE res_vacancyapplications SET status = @0, update_date = @1 WHERE guid = @2", VacancyApplicationStatus.Lost, message.TimeStamp, message.VacancyApplicationGuid)); transaction.Complete(); } } } }
using System; using MongoFeeder.Services; using System.Collections.Generic; namespace MongoFeeder { class Program { static void Main(string[] args) { } } }
using System.Drawing; namespace gView.Framework.Symbology.UI { /// <summary> /// Zusammenfassung für FormColorTransparency. /// </summary> public class FormColorTransparency : System.Windows.Forms.Form { private System.Windows.Forms.Panel panelPreview; private System.Windows.Forms.TrackBar trackBar1; private System.Windows.Forms.Button btnOk; private System.Windows.Forms.Button btnCancel; /// <summary> /// Erforderliche Designervariable. /// </summary> private System.ComponentModel.Container components = null; private Color _color; public FormColorTransparency(Color color) { InitializeComponent(); _color = color; trackBar1.Value = _color.A; } public Color Color { get { return _color; } } /// <summary> /// Die verwendeten Ressourcen bereinigen. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Vom Windows Form-Designer generierter Code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormColorTransparency)); this.panelPreview = new System.Windows.Forms.Panel(); this.trackBar1 = new System.Windows.Forms.TrackBar(); this.btnOk = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit(); this.SuspendLayout(); // // panelPreview // this.panelPreview.AccessibleDescription = null; this.panelPreview.AccessibleName = null; resources.ApplyResources(this.panelPreview, "panelPreview"); this.panelPreview.BackgroundImage = null; this.panelPreview.Font = null; this.panelPreview.Name = "panelPreview"; this.panelPreview.Paint += new System.Windows.Forms.PaintEventHandler(this.panelPreview_Paint); // // trackBar1 // this.trackBar1.AccessibleDescription = null; this.trackBar1.AccessibleName = null; resources.ApplyResources(this.trackBar1, "trackBar1"); this.trackBar1.BackgroundImage = null; this.trackBar1.Font = null; this.trackBar1.Maximum = 255; this.trackBar1.Name = "trackBar1"; this.trackBar1.TickFrequency = 26; this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll); // // btnOk // this.btnOk.AccessibleDescription = null; this.btnOk.AccessibleName = null; resources.ApplyResources(this.btnOk, "btnOk"); this.btnOk.BackgroundImage = null; this.btnOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOk.Font = null; this.btnOk.Name = "btnOk"; // // btnCancel // this.btnCancel.AccessibleDescription = null; this.btnCancel.AccessibleName = null; resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.BackgroundImage = null; this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Font = null; this.btnCancel.Name = "btnCancel"; // // FormColorTransparency // this.AccessibleDescription = null; this.AccessibleName = null; resources.ApplyResources(this, "$this"); this.BackgroundImage = null; this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOk); this.Controls.Add(this.trackBar1); this.Controls.Add(this.panelPreview); this.Font = null; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Icon = null; this.Name = "FormColorTransparency"; ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private void panelPreview_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { Rectangle rect = new Rectangle(20, 20, panelPreview.Width - 40, panelPreview.Height - 40); using (SolidBrush brush = new SolidBrush(Color.White)) { e.Graphics.FillRectangle(brush, 0, 0, panelPreview.Width, panelPreview.Height); } using (Pen pen = new Pen(Color.Black, 3)) { e.Graphics.DrawLine(pen, 0, 0, panelPreview.Width, panelPreview.Height); e.Graphics.DrawLine(pen, panelPreview.Width, 0, 0, panelPreview.Height); } using (SolidBrush brush = new SolidBrush(_color)) { e.Graphics.FillRectangle(brush, rect); } using (Pen pen = new Pen(Color.Black)) { e.Graphics.DrawRectangle(pen, rect); } } private void trackBar1_Scroll(object sender, System.EventArgs e) { _color = Color.FromArgb(trackBar1.Value, _color.R, _color.G, _color.B); panelPreview.Refresh(); } } }
using Dorisol1019.MemorialArchiver.Server.Domain.Memorial; using Dorisol1019.MemorialArchiver.Shared.Models.Memorials; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Dorisol1019.MemorialArchiver.Server.Infrastracture.Memorial { public class InMemoryMemorialRepository<T> : IMemorialRepository<T> { private static Dictionary<long, T> dic = new Dictionary<long, T>(); private static long id = 1; public void Create(IMemorialCreateRequest<T> request) { dic.Add(id, request.ToEntity(id)); id++; } public IEnumerable<T>? GetAll() { if (!dic.Any()) { return null; } return dic.Values; } } }