text
stringlengths
13
6.01M
namespace JhinBot.Enums { public enum ExceptionType { Exception, NullReference, IndexOutOfRange, StackOverflow, DivideByZero } }
using CitizenFX.Core; using FivePD.API; using System; using System.Threading.Tasks; using static CitizenFX.Core.Native.API; using Newtonsoft.Json.Linq; using FivePD.API.Utils; using System.Collections.Generic; using MenuAPI; using System.Linq; #pragma warning disable 1998 namespace IntuitiveMenus { class Trunk { string AnimDict = "mini@repair"; internal async Task OpenTrunk() { float triggerDistance = 1.0f; // Find entities in front of player Vector3 rayEndCoords = GetOffsetFromEntityInWorldCoords(PlayerPedId(), 0.0f, triggerDistance+3, -0.7f); int rayHandle = StartShapeTestRay(Game.PlayerPed.Position.X, Game.PlayerPed.Position.Y, Game.PlayerPed.Position.Z, rayEndCoords.X, rayEndCoords.Y, rayEndCoords.Z, 2, PlayerPedId(), 0); bool _Hit = false; int _vehicleHandle = 0; Vector3 _endCoords = new Vector3(); Vector3 _surfaceNormal = new Vector3(); GetShapeTestResult(rayHandle, ref _Hit, ref _endCoords, ref _surfaceNormal, ref _vehicleHandle); // Check if the entity hit is an emergency vehicle (class 18) if (DoesEntityExist(_vehicleHandle) && GetVehicleClass(_vehicleHandle) == 18) { // Find the back of the vehicle and check if it's within the trigger distance Vector3 offsetFromVehicle = GetOffsetFromEntityGivenWorldCoords(_vehicleHandle, Game.PlayerPed.Position.X, Game.PlayerPed.Position.Y, Game.PlayerPed.Position.Z); Vector3 vehicleDimensionsMinimum = new Vector3(); Vector3 vehicleDimensionsMaximum = new Vector3(); GetModelDimensions((uint)GetEntityModel(_vehicleHandle), ref vehicleDimensionsMinimum, ref vehicleDimensionsMaximum); Vector3 trunkOffset = vehicleDimensionsMinimum - offsetFromVehicle; if (trunkOffset.X < triggerDistance && trunkOffset.Y < triggerDistance && trunkOffset.Z < triggerDistance && trunkOffset.Y > -0.25) { if (Utilities.IsPlayerOnDuty()) { // Request the animation dictionary and wait for it to be loaded RequestAnimDict(AnimDict); int maxretries = 0; while (!HasAnimDictLoaded(AnimDict) && maxretries < 10) { await BaseScript.Delay(25); maxretries++; } // Check if the trunk is open or closed and act accordingly if (GetVehicleDoorAngleRatio(_vehicleHandle, 5) > 0) { SetVehicleDoorShut(_vehicleHandle, 5, false); StopAnimTask(PlayerPedId(), AnimDict, "fixing_a_ped", 4f); } else { _ = OpenMenu(_vehicleHandle); SetCurrentPedWeapon(PlayerPedId(), (uint)GetHashKey("WEAPON_UNARMED"), true); SetVehicleDoorOpen(_vehicleHandle, 5, false, false); if (HasAnimDictLoaded(AnimDict)) { TaskPlayAnim( PlayerPedId(), // ped AnimDict, // Anim Dictionary "fixing_a_ped", // Animation 4.0f, // Blend in speed 4.0f, // Blend out speed -1, // Duration 1, // Flag 0.5f, // Playback Rate false, // Lock X false, // Lock Y false // Lock Z ); } await BaseScript.Delay(100); SetEntityNoCollisionEntity(PlayerPedId(), _vehicleHandle, true); } } else { Common.DisplayNotification("You need to be on duty to access the trunk!"); } } else if (IsEntityPlayingAnim(PlayerPedId(), AnimDict, "fixing_a_ped", 3)) { StopAnimTask(PlayerPedId(), AnimDict, "fixing_a_ped", 4f); } } } internal async Task OpenMenu(int vehicleHandle) { PlayerData playerData = Utilities.GetPlayerData(); Menu menu = new Menu("Trunk"); MenuController.AddMenu(menu); MenuItem menuItem_SpikeStrips = new MenuItem("Get spike strip"); if (SpikeStripVehicles.Contains(GetEntityModel(vehicleHandle))) { menu.AddMenuItem(menuItem_SpikeStrips); } // Check which loadouts are available for the player in the trunk and create the menu buttons for it foreach (Loadout _Loadout in Loadouts) { bool _isAllowed = false; if (_Loadout.IsAvailableForEveryone) _isAllowed = true; else if (_Loadout.UseRanks) { if (_Loadout.AvailableForRanks.Contains(playerData.Rank)) _isAllowed = true; } else if (!_Loadout.UseRanks) { if (_Loadout.AvailableForDepartments.Contains(playerData.DepartmentID)) _isAllowed = true; else if (_Loadout.AvailableForDepartments.Count == 1) _isAllowed = true; } if (_isAllowed) { bool _missesWeapon = false; foreach (var _Weapon in _Loadout.Weapons) { if (!_missesWeapon && !HasPedGotWeapon(PlayerPedId(), (uint)GetHashKey(_Weapon.Model), false)) _missesWeapon = true; } MenuItem _menuButton = new MenuItem((_missesWeapon ? "Take" : "Put back") + " " + _Loadout.Name); _menuButton.ItemData = new Tuple<bool, List<Weapon>>(_missesWeapon, _Loadout.Weapons); menu.AddMenuItem(_menuButton); } } MenuItem menuItem_RefillAmmo = new MenuItem("Refill Ammo"); menuItem_RefillAmmo.ItemData = new Dictionary<string, int>(); // Iterate through normal loadouts foreach (Loadout _Loadout in Common.Loadouts) { bool _isAllowed = false; if (_Loadout.IsAvailableForEveryone) _isAllowed = true; else if (_Loadout.UseRanks) { if (_Loadout.AvailableForRanks.Contains(playerData.Rank)) _isAllowed = true; } else if (!_Loadout.UseRanks) { if (_Loadout.AvailableForDepartments.Contains(playerData.DepartmentID)) _isAllowed = true; } if (_isAllowed) { foreach(Weapon _Weapon in _Loadout.Weapons) { menuItem_RefillAmmo.ItemData[_Weapon.Model] = _Weapon.Ammo; } } } // Iterate through trunk loadouts foreach (Loadout _Loadout in Loadouts) { bool _isAllowed = false; if (_Loadout.IsAvailableForEveryone) _isAllowed = true; else if (_Loadout.UseRanks) { if (_Loadout.AvailableForRanks.Contains(playerData.Rank)) _isAllowed = true; } else if (!_Loadout.UseRanks) { if (_Loadout.AvailableForDepartments.Contains(playerData.DepartmentID)) _isAllowed = true; else if (_Loadout.AvailableForDepartments.Count == 1) _isAllowed = true; } if (_isAllowed) { foreach (Weapon _Weapon in _Loadout.Weapons) { menuItem_RefillAmmo.ItemData[_Weapon.Model] = _Weapon.Ammo; } } } menu.AddMenuItem(menuItem_RefillAmmo); menu.OnItemSelect += (_menu, _item, _index) => { if(_item.Index == menuItem_SpikeStrips.Index) { SetControlNormal(0, 21, 2.0f); SetControlNormal(0, 38, 1.0f); _item.Text = "Spike strips added"; _item.Enabled = false; } else if (_item.Index == menuItem_RefillAmmo.Index) { Dictionary<string, int> _itemData = _item.ItemData; foreach (KeyValuePair<string, int> _RefillItem in _itemData) { uint _weaponHash = (uint)GetHashKey(_RefillItem.Key); if(GetAmmoInPedWeapon(PlayerPedId(), _weaponHash) < _RefillItem.Value) SetPedAmmo(PlayerPedId(), _weaponHash, _RefillItem.Value); } } else { // Give the weapon to the player Tuple<bool, List<Weapon>> _ItemData = _item.ItemData; if (_ItemData.Item1) { foreach (Weapon _Weapon in _ItemData.Item2) { uint _weaponHash = (uint)GetHashKey(_Weapon.Model); GiveWeaponToPed(PlayerPedId(), _weaponHash, _Weapon.Ammo, false, true); SetPedAmmo(PlayerPedId(), _weaponHash, _Weapon.Ammo); // Need to call this; GiveWeaponToPed always adds ammo up if (_Weapon.Components.Length > 0) { foreach (string _weaponComponent in _Weapon.Components) { GiveWeaponComponentToPed(PlayerPedId(), _weaponHash, (uint)GetHashKey(_weaponComponent)); } } } _item.Text = _item.Text.Replace("Take", "Put back"); } else { foreach (Weapon _Weapon in _ItemData.Item2) { uint _weaponHash = (uint)GetHashKey(_Weapon.Model); RemoveWeaponFromPed(PlayerPedId(), _weaponHash); } _item.Text = _item.Text.Replace("Put back", "Take"); } _item.ItemData = new Tuple<bool, List<Weapon>>(!_ItemData.Item1, _ItemData.Item2); } }; // Stop animation and close the trunk when player exits vehicle menu.OnMenuClose += (_menu) => { StopAnimTask(PlayerPedId(), AnimDict, "fixing_a_ped", 4f); SetVehicleDoorShut(vehicleHandle, 5, false); vehicleHandle = 0; }; menu.OpenMenu(); } internal List<Loadout> Loadouts = new List<Loadout>(); internal List<int> SpikeStripVehicles = new List<int>(); } }
using System; using System.Diagnostics; using System.Linq; using System.Web.UI; using HTB.Database; using System.Text; using System.Collections; using HTB.Database.HTB.StoredProcs; using HTB.v2.intranetx.global_files; using HTBExtras.KingBill; using HTBReports; using HTBUtilities; using System.Data; using HTB.v2.intranetx.util; using HTB.v2.intranetx.permissions; using HTBDailyKosten; using HTB.Database.Views; using HTBExtras; namespace HTB.v2.intranetx.aktenink { public partial class ViewAktInk : Page, IWorkflow { public string AktId; public qryCustAktEdit QryInkassoakt = new qryCustAktEdit(); private ArrayList _intAktList = new ArrayList(); private ArrayList _invoiceList = new ArrayList(); private ArrayList _inkassoAktions = new ArrayList(); private readonly ArrayList _interventionAktions = new ArrayList(); public readonly ArrayList AktionsList = new ArrayList(); private ArrayList _docsList = new ArrayList(); private double _initialAmount; private double _initialAmountPay; private double _initialClientCosts; private double _initialClientCostsPay; private double _interest; private double _interestPay; private double _collectionCosts; private double _collectionCostsPay; private double _collectionInterest; private double _collectionInterestPay; private double _balanceDue; private double _totalPay; private double _unappliedPay; public PermissionsEditAktInk Permissions = new PermissionsEditAktInk(); private spGetNextWorkflowActionCode _nextWflActionCode; protected void Page_Load(object sender, EventArgs e) { var sw = new Stopwatch(); sw.Start(); Permissions.LoadPermissions(GlobalUtilArea.GetUserId(Session)); if (Request.QueryString["ID"] != null && !Request.QueryString["ID"].Trim().Equals("")) { AktId = Request.QueryString["ID"]; LoadRecords(); CombineActions(); SetTotalInvoiceAmounts(); if (!IsPostBack) { GlobalUtilArea.LoadDropdownList(ddlLawyer, "SELECT * FROM tblLawyer ORDER BY LawyerName1 ASC", typeof(tblLawyer), "LawyerID", "LawyerName1", false); SetValues(); } Session["tmpInkAktID"] = Request.QueryString["ID"]; } if (!Permissions.GrantInkassoEdit) ddlSendBericht.Enabled = false; // lblLoadingTimes.Text = sw.ElapsedMilliseconds.ToString(); sw.Stop(); } private void LoadRecords() { int aktId = GlobalUtilArea.GetZeroIfConvertToIntError(Request.QueryString["ID"]); _interventionAktions.Clear(); ArrayList[] results = HTBUtils.GetMultipleListsFromStoredProcedure("spGetInkassoAktDataView", new ArrayList { new StoredProcedureParameter("aktId", SqlDbType.Int, aktId) }, new[] { typeof(qryCustAktEdit), typeof(tblCustInkAktInvoice), typeof(qryCustInkAktAktionen), typeof(qryDoksInkAkten), typeof(tblAktenInt), typeof(spGetNextWorkflowActionCode), } ); try { QryInkassoakt = (qryCustAktEdit) results[0][0]; _invoiceList = results[1]; _inkassoAktions = results[2]; _docsList = results[3]; _intAktList = results[4]; _nextWflActionCode = (spGetNextWorkflowActionCode) results[5][0]; } catch { } if (_intAktList != null && _intAktList.Count > 0) { foreach (tblAktenInt intAkt in _intAktList) { HTBUtils.AddListToList(HTBUtils.GetSqlRecords("SELECT * FROM qryInktAktAction WHERE AktIntActionAkt = " + intAkt.AktIntID + " ORDER BY AktIntActionDate DESC", typeof (qryInktAktAction)), _interventionAktions); if (intAkt.AktIntStatus < 2) { var sb = new StringBuilder("<strong><font color=\"red\">ACHTUNG: Akt ist beim Aussendienst!!!<br/>Status: "); sb.Append(GlobalUtilArea.GetInterventionAktStatusText(intAkt.AktIntStatus)); if (intAkt.AktIntStatus == 1 && intAkt.AKTIntDruckkennz == 1) sb.Append(" [gedruckt]"); sb.Append("</font></strong>"); _interventionAktions.Add(new qryInktAktAction { AktIntActionAkt = intAkt.AktIntID, AktIntActionTime = DateTime.Now, AktIntActionTypeCaption = sb.ToString(), AktIntActionLatitude = 0, AktIntActionLongitude = 0, AktIntActionAddress = "" }); } HTBUtils.AddListToList(HTBUtils.GetSqlRecords("SELECT * FROM qryDoksIntAkten WHERE AktIntID = " + intAkt.AktIntID, typeof (qryDoksIntAkten)), _docsList); } } } private void SetValues() { lblCustInkAktID.Text = QryInkassoakt.CustInkAktID.ToString(); if (QryInkassoakt.CustInkAktOldID != "") { lblCustInkAktID.Text+=(" [" + QryInkassoakt.CustInkAktOldID + "]"); } lblCustInkAktEnterDate.Text = QryInkassoakt.CustInkAktEnterDate.ToShortDateString(); lblAuftraggeber.Text = "<strong>" + QryInkassoakt.AuftraggeberName1 + "</strong>&nbsp;" + QryInkassoakt.AuftraggeberName2 + "<br/>" + QryInkassoakt.AuftraggeberStrasse + "<br>" + QryInkassoakt.AuftraggeberLKZ + "&nbsp;" + QryInkassoakt.AuftraggeberPLZ + "&nbsp;" + QryInkassoakt.AuftraggeberOrt; lblKlient.Text = "<strong>" + QryInkassoakt.KlientName1 + "</strong>&nbsp;" + QryInkassoakt.KlientName2 + "<br/>" + QryInkassoakt.KlientStrasse + "<br/>" + QryInkassoakt.KlientLKZ + "&nbsp;" + QryInkassoakt.KlientPLZ + "&nbsp;" + QryInkassoakt.KlientOrt; lblCustInkAktKunde.Text = !QryInkassoakt.CustInkAktKunde.Trim().Equals("") ? QryInkassoakt.CustInkAktKunde : "Keine Rechnungsnummer vorhanden!"; lblCustInkAktGothiaNr.Text = !string.IsNullOrEmpty(QryInkassoakt.CustInkAktGothiaNr) ? QryInkassoakt.CustInkAktGothiaNr.ToString() : "&nbsp;"; lblCustInkAktInvoiceDate.Text = QryInkassoakt.CustInkAktInvoiceDate.ToShortDateString(); lblGegner.Text = "<strong><a href=\"#\" onClick=\"MM_openBrWindow('../../intranet/gegner/editgegner.asp?poprefresh=true&GegnerID="+QryInkassoakt.CustInkAktGegner+"','popWindow','menubar=yes,scrollbars=yes,resizable=yes,width=800,height=600')\">"; lblGegner.Text += QryInkassoakt.GegnerLastName1 + ", " + QryInkassoakt.GegnerLastName2 + "</a></strong><br/>"; lblGegner.Text += QryInkassoakt.GegnerLastStrasse + "<br/>"; lblGegner.Text += QryInkassoakt.GegnerLastZipPrefix + "&nbsp;" + QryInkassoakt.GegnerLastZip + "&nbsp;" + QryInkassoakt.GegnerLastOrt; lblKlient.Text = "<strong><a href=\"#\" onClick=\"MM_openBrWindow('/v2/intranet/klienten/editklient.asp?poprefresh=true&ID=" + QryInkassoakt.CustInkAktKlient + "','popWindow','menubar=yes,scrollbars=yes,resizable=yes,width=800,height=600')\">"; lblKlient.Text += "<strong>"+QryInkassoakt.KlientName1.Trim() + "</strong>&nbsp;" + QryInkassoakt.KlientName2.Trim() + "</strong></a><br/>"; lblKlient.Text += QryInkassoakt.KlientStrasse + "<br/>"; lblKlient.Text += QryInkassoakt.KlientLKZ + "&nbsp;" + QryInkassoakt.KlientPLZ + "&nbsp;" + QryInkassoakt.KlientOrt; /* lblForderung.Text = HTBUtils.FormatCurrency(_initialAmount); lblZahlungen.Text = HTBUtils.FormatCurrency(_initialAmountPay); lblKostenKlientSumme.Text = HTBUtils.FormatCurrency(_initialClientCosts); lblKostenKlientZahlungen.Text = HTBUtils.FormatCurrency(_initialClientCostsPay); lblZinsen.Text = HTBUtils.FormatCurrency(_interest); lblZinsenZahlungen.Text = HTBUtils.FormatCurrency(_interestPay); lblEcpZinsen.Text = HTBUtils.FormatCurrency(_collectionInterest); lblEcpZinsenZahlungen.Text = HTBUtils.FormatCurrency(_collectionInterestPay); lblKostenSumme.Text = HTBUtils.FormatCurrency(_collectionCosts); lblKostenZahlungen.Text = HTBUtils.FormatCurrency(_collectionCostsPay); double totalAmount = (_initialAmount + _initialClientCosts + _interest + _collectionCosts + _collectionInterest); //totalPay = (initialAmountPay + initialClientCostsPay + interestPay + collectionCostsPay + collectionInterestPay); _balanceDue = totalAmount - _totalPay; lblSumGesFortBUE.Text = HTBUtils.FormatCurrency(totalAmount); lblSumGesZahlungenBUE.Text = HTBUtils.FormatCurrency(_totalPay); lblSaldo.Text = HTBUtils.FormatCurrency(_balanceDue); if (_unappliedPay > 0) lblUnappliedPay.Text = "Unapplied Zahlung: " + HTBUtils.FormatCurrency(_unappliedPay); else lblUnappliedPay.Text = "&nbsp;"; txtMemo.Text = QryInkassoakt.CustInkAktMemo; ddlLawyer.SelectedValue = QryInkassoakt.CustInkAktLawyerId.ToString(); ddlSendBericht.SelectedValue = QryInkassoakt.CustInkAktSendBericht ? "1" : "0"; lblCustInkAktNextWFLStep.Text = QryInkassoakt.CustInkAktNextWFLStep.ToShortDateString(); lblNetWflAction.Text = _nextWflActionCode != null ? CtlWorkflow.GetActionText(_nextWflActionCode.WfpActionCode) : ""; if (_intAktList.Count > 0) { var intAkt = (tblAktenInt) _intAktList[0]; if (intAkt != null) { var user = (tblUser)HTBUtils.GetSqlSingleRecord("SELECT * FROM tblUser WHERE UserID = " + intAkt.AktIntSB, typeof (tblUser)); if(user != null) { lblAussendienst.Text = user.UserVorname + " " + user.UserNachname; trAussendienst.Visible = true; } string intAktStatus = GlobalUtilArea.GetInterventionAktStatusText(intAkt.AktIntStatus); if (intAkt.AktIntStatus == 1 && intAkt.AKTIntDruckkennz == 1) intAktStatus += " [gedruckt]"; lblInterventionStatus.Text = intAktStatus; trInterventionStatus.Visible = true; } } PopulateDocumentsGrid();*/ } #region Event Handlers protected void btnCancel_Click(object sender, EventArgs e) { if (GlobalUtilArea.IsPopUp(Request)) bdy.Attributes.Add("onLoad", "window.close()"); else if (GlobalUtilArea.GetEmptyIfNull(Request[GlobalHtmlParams.RETURN_TO_URL_ON_CANCEL]) == GlobalHtmlParams.BACK) bdy.Attributes.Add("onLoad", "javascript:history.go(-2)"); else ShowParentScreen(); } #endregion public void ShowParentScreen() { Response.Redirect("../../intranet/aktenink/AktenStaff.asp?" + Session["var"]); } private void SetTotalInvoiceAmounts() { _unappliedPay = 0; foreach (tblCustInkAktInvoice inv in _invoiceList) { if (!inv.IsVoid()) { if (inv.IsPayment()) { _totalPay += inv.InvoiceAmount; _unappliedPay += inv.InvoiceBalance; } else { switch (inv.InvoiceType) { case tblCustInkAktInvoice.INVOICE_TYPE_ORIGINAL: _initialAmount += inv.InvoiceAmount; _initialAmountPay += inv.InvoiceAmount - inv.InvoiceBalance; break; case tblCustInkAktInvoice.INVOICE_TYPE_CLIENT_COST: _initialClientCosts += inv.InvoiceAmount; _initialClientCostsPay += inv.InvoiceAmount - inv.InvoiceBalance; break; case tblCustInkAktInvoice.INVOICE_TYPE_INTEREST_CLIENT: case tblCustInkAktInvoice.INVOICE_TYPE_INTEREST_CLIENT_ORIGINAL: _interest += inv.InvoiceAmount; _interestPay += inv.InvoiceAmount - inv.InvoiceBalance; break; case tblCustInkAktInvoice.INVOICE_TYPE_INTEREST_COLECTION: _collectionInterest += inv.InvoiceAmount; _collectionInterestPay += inv.InvoiceAmount - inv.InvoiceBalance; break; default: _collectionCosts += inv.InvoiceAmount; _collectionCostsPay += inv.InvoiceAmount - inv.InvoiceBalance; break; } } } } } private void CombineActions() { tblAktenInt intAkt = _intAktList.Count == 0 ? null : (tblAktenInt)_intAktList[0]; foreach (qryCustInkAktAktionen inkAction in _inkassoAktions) AktionsList.Add(new InkassoActionRecord(inkAction, intAkt)); foreach (qryInktAktAction intAction in _interventionAktions) { var action = new InkassoActionRecord(intAction, intAkt); if(!string.IsNullOrEmpty(intAction.AktIntActionAddress)) { action.ActionCaption += "<BR/><I>" + intAction.AktIntActionAddress+"</I>"; } else if (action.AktIntActionLatitude > 0 && action.AktIntActionLongitude > 0) { string address = GlobalUtilArea.GetAddressFromLatitudeAndLongitude(action.AktIntActionLatitude, action.AktIntActionLongitude); if(!string.IsNullOrEmpty(address)) { action.ActionCaption += "<BR/><I>" + address+"</I>"; // Update Action [set address based on coordinates] try { var set = new RecordSet(); set.ExecuteNonQuery("UPDATE tblAktenIntAction SET AktIntActionAddress = " + address + " WHERE AktIntActionID = " + intAction.AktIntActionID); } catch { } } } AktionsList.Add(action); } AktionsList.Sort(new InkassoActionRecordComparer()); } #region Gets Methods public bool IsInkassoAction(Record rec) { return rec is qryCustInkAktAktionen; } public string GetActionType(Record rec) { if (rec is qryCustInkAktAktionen) return ((qryCustInkAktAktionen)rec).KZKZ; return ""; } public string GetDeleteActionURL(Record rec) { if (rec is qryCustInkAktAktionen) { var action = (qryCustInkAktAktionen)rec; var sb = new StringBuilder("../global_forms/GlobalDelete.aspx?titel=Position%20löschen&amp;frage=Sie%20sind%20dabei%20diese%20Position%20zu%20löschen:&amp;strTable=tblCustInkAktAktion&amp;strTextField="); if (action.CustInkAktAktionCaption != null && action.CustInkAktAktionCaption.Trim() != string.Empty) sb.Append("CustInkAktAktionCaption"); else sb.Append("CustInkAktAktionMemo"); sb.Append("&amp;strColumn=CustInkAktAktionID&amp;ID="); sb.Append(action.CustInkAktAktionID); return sb.ToString(); } return ""; } public string GetEditActionURL(Record rec) { if (rec is qryCustInkAktAktionen) { return "EditInkAction.aspx?ID="+((qryCustInkAktAktionen)rec).CustInkAktAktionID; } return ""; } public bool HasIntervention() { return _intAktList.Count > 0; } public string GetInterventionMemo() { var intAkt = GetInterventionAkt(); if (intAkt != null) { var sb = new StringBuilder("<strong>&nbsp;&nbsp;&nbsp;&nbsp;Original Memo: </strong><br/>"); sb.Append(intAkt.AktIntOriginalMemo.Replace(Environment.NewLine, "<BR/>")); sb.Append("<BR/><BR/><strong>&nbsp;&nbsp;&nbsp;&nbsp;Aussendienst Memo: </strong>"); sb.Append(intAkt.AKTIntMemo.Replace(Environment.NewLine, "<BR/>")); return sb.ToString(); } return ""; } public string GetInverventionURL() { var intAkt = GetInterventionAkt(); if (intAkt != null) { var sb = new StringBuilder("<strong>&nbsp;&nbsp;&nbsp;&nbsp;"); sb.Append(intAkt.AktIntID.ToString()); sb.Append(":&nbsp;&nbsp;</strong>"); sb.Append("<a href=\"../aktenint/editaktint.aspx?"); GlobalUtilArea.AppendHtmlParamIfNotEmpty(sb, GlobalHtmlParams.ID, intAkt.AktIntID.ToString(), false); GlobalUtilArea.AppendHtmlParamIfNotEmpty(sb, GlobalHtmlParams.RETURN_TO_URL_ON_SUBMIT, GlobalHtmlParams.BACK); sb.Append("\">"); sb.Append("<img src=\"/v2/intranet/images/edit.gif\" width=\"16\" height=\"16\" border=\"0\" title=\"&Auml;ndern.\">"); sb.Append("</a>&nbsp;&nbsp;&nbsp;"); sb.Append("<a href=\"../aktenint/workaktint.aspx?"); GlobalUtilArea.AppendHtmlParamIfNotEmpty(sb, GlobalHtmlParams.ID, intAkt.AktIntID.ToString(), false); GlobalUtilArea.AppendHtmlParamIfNotEmpty(sb, GlobalHtmlParams.RETURN_TO_URL_ON_SUBMIT, GlobalHtmlParams.BACK); sb.Append("\">"); sb.Append("<img src=\"/v2/intranet/images/arrow16.gif\" width=\"16\" height=\"16\" border=\"0\" title=\"Buchen.\">"); sb.Append("</a>&nbsp;&nbsp;&nbsp;"); return sb.ToString(); //return "<a href=\"../aktenint/workaktint.aspx?ID=" + intAkt.AktIntID + "&" + GlobalHtmlParams.RETURN_TO_URL_ON_SUBMIT + "=" + GlobalHtmlParams.BACK + "\">" + intAkt.AktIntID + "</a>"; } return ""; } private tblAktenInt GetInterventionAkt() { return _intAktList.Count == 0 ? null : (tblAktenInt)_intAktList[0]; } #endregion #region Documents private void PopulateDocumentsGrid() { DataTable dt = GetDocumentsDataTableStructure(); foreach (Record rec in _docsList) { if (rec is qryDoksInkAkten) { DataRow dr = dt.NewRow(); var doc = (qryDoksInkAkten) rec; int mahnungsNumber = GetDocMahnungNumber(doc.DokCaption); var sb = new StringBuilder("<a href=\"javascript:void(window.open('"); if (mahnungsNumber > 0) { // the actual link sb.Append("DeleteMahnung.aspx?"); sb.Append(GlobalHtmlParams.INKASSO_AKT); sb.Append("="); sb.Append(doc.CustInkAktID.ToString()); GlobalUtilArea.AppendHtmlParamIfNotEmpty(sb, GlobalHtmlParams.MAHNUNG_NUMBER, mahnungsNumber.ToString()); GlobalUtilArea.AppendHtmlParamIfNotEmpty(sb, GlobalHtmlParams.DOCUMENT_ID, doc.DokID.ToString()); } else { sb.Append("../global_forms/GlobalDelete.aspx?titel=Position%20löschen&amp;frage=Sie%20sind%20dabei%20diese%20Position%20zu%20löschen:&amp;strTable=tblDokument&amp;strTextField=DokAttachment&amp;strColumn=DokID&amp;ID="); sb.Append(doc.DokID); } // continue with the popup params sb.Append("','_blank','toolbar=no,menubar=no'))\">"); sb.Append("<img src=\"../../intranet/images/delete2hover.gif\" width=\"16\" height=\"16\" alt=\"L&ouml;scht diesen Datensatz.\" style=\"border-color:White;border-width:0px;\"/>"); sb.Append("</a>"); dr["DeleteUrl"] = sb.ToString(); dr["DokAttachment"] = GetDocAttachmentLink(doc.DokAttachment); dr["DokChangeDate"] = doc.DokChangeDate.ToShortDateString(); dr["DokTypeCaption"] = doc.DokTypeCaption; dr["DokCaption"] = doc.DokCaption; dr["DokUser"] = doc.UserVorname + " " + doc.UserNachname; dt.Rows.Add(dr); } else if (rec is qryDoksIntAkten) { DataRow dr = dt.NewRow(); var doc = (qryDoksIntAkten) rec; var sb = new StringBuilder("<a href=\"javascript:void(window.open('"); sb.Append("/v2/intranet/global_forms/globaldelete.asp?strTable=tblDokument&frage=Sind%20Sie%20sicher,%20dass%20sie%20dieses%20Dokument%20l&#246;schen%20wollen?&strTextField=DokAttachment&strColumn=DokID&ID="); sb.Append(doc.DokID); // continue with the popup params sb.Append("','_blank','toolbar=no,menubar=no'))\">"); sb.Append("<img src=\"../../intranet/images/delete2hover.gif\" width=\"16\" height=\"16\" alt=\"L&ouml;scht diesen Datensatz.\" style=\"border-color:White;border-width:0px;\"/>"); sb.Append("</a>"); dr["DeleteUrl"] = sb.ToString(); dr["DokAttachment"] = GetDocAttachmentLink(doc.DokAttachment); dr["DokChangeDate"] = doc.DokCreationTimeStamp.ToShortDateString(); dr["DokTypeCaption"] = doc.DokTypeCaption; dr["DokCaption"] = doc.DokCaption; dr["DokUser"] = doc.UserVorname + " " + doc.UserNachname; dt.Rows.Add(dr); } } // gvDocs.DataSource = dt; // gvDocs.DataBind(); // gvDocs.Columns[0].Visible = Permissions.GrantInkassoDokumentDel; } private DataTable GetDocumentsDataTableStructure() { var dt = new DataTable(); dt.Columns.Add(new DataColumn("DeleteUrl", typeof(string))); dt.Columns.Add(new DataColumn("DeletePopupUrl", typeof(string))); dt.Columns.Add(new DataColumn("DokChangeDate", typeof(string))); dt.Columns.Add(new DataColumn("DokTypeCaption", typeof(string))); dt.Columns.Add(new DataColumn("DokCaption", typeof(string))); dt.Columns.Add(new DataColumn("DokUser", typeof(string))); dt.Columns.Add(new DataColumn("DokAttachment", typeof(string))); return dt; } private int GetDocMahnungNumber(string docCaption) { if(docCaption.IndexOf("Mahnung") >= 0) { try { int mahnungsNum = Convert.ToInt32(docCaption.Substring(8)); return mahnungsNum; } catch { } } return 0; } private string GetDocAttachmentLink(string attachment) { var sb = new StringBuilder("<a href=\"javascript:void(window.open('../../intranet/documents/files/"); sb.Append(attachment); sb.Append("','popSetAction','menubar=yes,scrollbars=yes,resizable=yes,width=800,height=800,top=10'))\">"); sb.Append(attachment); sb.Append("</a>"); return sb.ToString(); } #endregion protected void btnMahnung_Click(object sender, EventArgs e) { var kostenCalc = new KostenCalculator(); kostenCalc.GenerateNewMahnung(QryInkassoakt.CustInkAktID); var mahMgr = new MahnungManager(); mahMgr.GenerateMahnungen(GlobalUtilArea.GetUserId(Session)); // refresh screen Response.Redirect("EditAktInk.aspx?ID=" + QryInkassoakt.CustInkAktID); } public string GetKlientID() { return QryInkassoakt.KlientID.ToString(); } public string GetSelectedMainStatus() { return null; } public string GetSelectedSecondaryStatus() { return null; } } }
using System; class ExerciseNullableType { static void Main() { int? firstNumber = null; Console.WriteLine("The value of the first number is: {0}!", firstNumber); firstNumber = 3; Console.WriteLine("The same number with new assigned value of 3 is equal to -> {0}!", firstNumber); Console.WriteLine(); double? secondNumber = null; Console.WriteLine("The value of the second number is: {0}!", secondNumber); secondNumber = 10.5; Console.WriteLine("The same second number with new assigned value of 10.5 is equal to -> {0}!", secondNumber); } }
using CsvHelper; using System; using System.Collections.Generic; using System.Data; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Organogram { class Program { static void Main(string[] args) { try { using (var reader = new StreamReader(System.IO.Directory.GetCurrentDirectory() + "\\companies_data.csv")) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { //fit csv records into List of Person types csv.Configuration.HasHeaderRecord = false; var records = csv.GetRecords<Person>().ToList(); //order list by Id var orderedList = records.OrderBy(p => p.Id).ToList(); var root = orderedList.First(); //find and set children of each record in the list foreach (var person in orderedList) { var children = orderedList.Where(p => p.ParentId == person.Id).ToList(); if (children.Any()) { person.Children = children; } } //print Organogram root.PrintStructure("", true); //print all records sorted by Row Id Console.WriteLine(); foreach (var person in orderedList) { Console.WriteLine($"{person.Id} - {person.FirstName} {person.LastName}, {person.Company}, {person.Position}, {person.City}"); } Console.ReadKey(); } } catch(Exception ex) { Console.WriteLine(ex.Message); } } } }
using System; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Testing; using Xunit; namespace BookLibrary.Tests.Controllers { [Collection("TestCollection")] public class HomeControllerTests { private readonly WebApplicationFactory<Startup> _factory; private readonly HttpClient _client; public HomeControllerTests(WebApplicationFactory<Startup> factory) { _factory = factory; _client = _factory.CreateClient(); } [Fact] public async Task IndexOnGet_WhenEnteringWelcomePage_ReturnsViewResult() { // Arrange & Act var response = await _client.GetAsync("/"); // Assert response.EnsureSuccessStatusCode(); Assert.NotNull(response.Content); var responseString = await response.Content.ReadAsStringAsync(); Assert.Contains("Welcome", responseString); } } }
using System; namespace CursoCSharp.Fundamentos { class PrimeiroPrograma { public static void Executar() { /* Escreve uma nova linha de texto no * console e mantém o ponto de inserção na mesma linha */ Console.Write("Primeiro "); /* Escreve uma nova linha de texto no * console e coloca o ponto de inserção na próxima linha */ Console.WriteLine("Programa"); Console.WriteLine("Terminou!"); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using GraphicalEditor.Enumerations; namespace GraphicalEditor.Converters { class IsRoomTypeToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { TypeOfMapObject typeOfSelectedObject = (TypeOfMapObject)value; if (CheckIsRoomType(typeOfSelectedObject)) return Visibility.Visible; else return Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } private Boolean CheckIsRoomType(TypeOfMapObject typeOfMapObject) => typeOfMapObject == TypeOfMapObject.EXAMINATION_ROOM || typeOfMapObject == TypeOfMapObject.HOSPITALIZATION_ROOM || typeOfMapObject == TypeOfMapObject.OPERATION_ROOM; } }
using UnityEngine; using UnityEditor; using System.Threading.Tasks; [InitializeOnLoad] public class AutosaveOnRun { static float elapsedTime; static readonly float saveTime = 180; static bool printSaveWarning = true; static bool canSave = true; static AutosaveOnRun() { Debug.Log("Auto save enabled"); OnEditorUpdate(); } async static void OnEditorUpdate() { while(true) { CheckIfAppIsInPlayMode(); DisableSavingOnPlay(); if (canSave) { PrintsSaveWarning(); elapsedTime++; if (elapsedTime >= saveTime) { elapsedTime = 0; printSaveWarning = true; if (!EditorApplication.isPlaying) { EditorApplication.SaveScene(); Debug.Log($"Saving current scene.... {EditorApplication.currentScene}"); } else { Debug.Log("Saving abandon... game is currently playing! Don't save the the duration of playtime."); canSave = false; } } await Task.Delay(1000); } else await Task.Delay(1000); } } private static void PrintsSaveWarning() { if (elapsedTime + 5 > saveTime && printSaveWarning) { Debug.Log("Saving the game in 5 secs..."); printSaveWarning = false; } } private static void DisableSavingOnPlay() { if (EditorApplication.isPlaying && canSave) { Debug.Log("Saving abandon... game is currently playing! Don't save the the duration of playtime."); canSave = false; } } static void CheckIfAppIsInPlayMode() { if (!EditorApplication.isPlaying && !canSave) { canSave = true; Debug.Log("Autosave resumes"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ExplodeModel : MonoBehaviour { //Lists to Hold the rigidbodies and the joints private Rigidbody[] _rbs; private Joint[] _joints; private bool _exploded; private float _timer; //Tuneables public float ExplodeForce; public float ExplodeTorque; public float DespawnTime; // Start is called before the first frame update void Start() { _rbs = GetComponentsInChildren<Rigidbody>(); _joints = GetComponentsInChildren<Joint>(); _exploded = false; _timer = DespawnTime; } private void Update() { if (_exploded) { _timer -= Time.deltaTime; if (_timer <= 0) { Destroy(gameObject); } } } public void Explode() { //If the joints are not null, turn off joints if (_joints != null) { foreach (Joint joint in _joints) { joint.breakForce = 0.01f; } } //If the rigidbodies are not null... if (_rbs != null) { foreach (Rigidbody rb in _rbs) { //Turn on gravity rb.useGravity = true; //Become dynamic rb.isKinematic = false; //Add a force Vector3 direction = Random.insideUnitSphere.normalized; rb.AddForce(direction * ExplodeForce); //Add a torque rb.AddTorque(direction * ExplodeTorque); } } _exploded = true; } }
using System; using System.Collections; using System.Collections.Generic; using System.Threading; using UnityEngine; using UnityEngine.UI; public class Battle : MonoBehaviour { public static Battle instance; [SerializeField] public Board board; public Unit[][] units = new Unit[][]{ new Unit[]{null,null,null,null,null}, new Unit[]{null,null,null,null,null}, new Unit[]{null,null,null,null,null}, new Unit[]{null,null,null,null,null} }; private readonly int RowsCount = 4; private readonly int ColsCount = 5; private Cell currentCell; public bool CurrentPlayer { get=>currentPlayer; } private bool currentPlayer = true; private JSCompiler jsCompiler; public GameObject Swordsman; public GameObject Archer; private BattleData battleData; public Button endTurnButton; public Button SubmitButton; public Button DisAutoButton; public InputField playerCode; public Bot playerSample; private Queue<ActionData> ActionQueue = new Queue<ActionData>(); public Action OnWin; private bool isAutomatic; private int turnCount; private bool isStop; private Coroutine CurrentCoroutine; void Awake() { if (!instance) instance = this; } private void Start() { } public void Init(BattleData data) { LoadData(data); jsCompiler = FindObjectOfType<JSCompiler>(); jsCompiler.SetValue("Action", new Action<int, int, int, int>((x, y, targetX, targetY) => ActionQueue.Enqueue(new ActionData { x = x, y = y, targetX = targetX, targetY = targetY }))); jsCompiler.SetValue("GetUnits", new Func<Unit[][]>(() => units)); jsCompiler.SetValue("GetUnit", new Func<int,int,Unit>((y,x) => GetUnit(y,x))); jsCompiler.SetValue("EndTurn", new Action(()=>EndTurn())); jsCompiler.SetValue("numberOfRows", RowsCount); jsCompiler.SetValue("numberOfColumns", ColsCount); } public void LoadData(BattleData data) { if (CurrentCoroutine != null) { StopCoroutine(CurrentCoroutine); CurrentCoroutine = null; } battleData = data; for (int r = 0; r < RowsCount; r++) { for (int c = 0; c < ColsCount; c++) { var unitType = data.rows[r].units[c]; if (unitType == "Swordsman") { var unit = Instantiate(Swordsman, board[r, c].transform).GetComponent<Unit>(); units[r][c] = unit; unit.Owner = r > 1; unit.Init(); } if (unitType == "Archer") { var unit = Instantiate(Archer, board[r, c].transform).GetComponent<Unit>(); units[r][c] = unit; unit.Owner = r > 1; unit.Init(); } } } currentPlayer = true; endTurnButton.interactable = currentPlayer; RefreshUnits(); } public void ShowAvailableCells(int x, int y) { if (units[y][ x]) { if (x > 0) { if(units[y][ x - 1]) board[y, x - 1].SetAvailable(); else if(units[y][ x].IsCanMove) board[y, x - 1].SetCanMove(); } if (x < ColsCount-1) { if(units[y][x + 1]) board[y, x + 1].SetAvailable(); else if (units[y][x].IsCanMove) board[y, x + 1].SetCanMove(); } if (y > 0) { if(units[y - 1][x]) board[y - 1, x].SetAvailable(); else if (units[y][x].IsCanMove) board[y - 1, x].SetCanMove(); if (x > 0 && units[y - 1][x - 1]) board[y - 1, x - 1].SetAvailable(); if (x < ColsCount - 1 && units[y - 1][x + 1]) board[y - 1, x + 1].SetAvailable(); } if (y < RowsCount-1) { if(units[y + 1][x]) board[y + 1, x].SetAvailable(); else if (units[y][x].IsCanMove) board[y + 1, x].SetCanMove(); if (x > 0 && units[y + 1][x - 1]) board[y + 1, x - 1].SetAvailable(); if (x < ColsCount - 1 && units[y + 1][x + 1]) board[y + 1, x + 1].SetAvailable(); } if(units[y][x].Type == "Archer"){ for (int r = 0; r < RowsCount; r++) { for (int c = 0; c < ColsCount; c++) { var unit = units[r][c]; if (unit) { board[r,c].SetAvailable(); } } } } } } public void OnClickCell(Cell cell) { if (!currentCell && units[cell.y][ cell.x] && units[cell.y][ cell.x].Owner && units[cell.y][cell.x].isActive) { currentCell = cell; ShowAvailableCells(cell.x, cell.y); } else { if (cell.isAvailable) { if (!units[cell.y][ cell.x]) { MoveUnit(cell); ResetAviable(); currentCell = cell; ShowAvailableCells(cell.x, cell.y); } else { UnitAction(cell); ResetAviable(); currentCell = null; } } else { ResetAviable(); currentCell = null; } } } public void ResetBattle(BattleData data) { ActionQueue.Clear(); isStop = true; ClearBoard(); LoadData(data); turnCount = 0; SubmitButton.interactable = true; } public void ClearBoard() { for (int r = 0; r < RowsCount; r++) { for (int c = 0; c < ColsCount; c++) { var unit = units[r][c]; if (unit) { units[r][c] = null; Destroy(unit.gameObject); } } } ResetAviable(); currentCell = null; } private void MoveUnit(Cell cell) { var unit = units[currentCell.y][ currentCell.x]; units[currentCell.y][ currentCell.x] = null; units[cell.y][ cell.x] = unit; unit.Move(cell); } private void MoveUnit(Unit unit, Cell cell, int targetX, int targetY) { if (targetX >= 0 && targetX < ColsCount && targetY >= 0 && targetY < RowsCount) { units[cell.y][cell.x] = null; units[targetY][targetX] = unit; unit.Move(board[targetY,targetX]); } } public void UnitAction(Cell cell) { if (Mathf.Abs(cell.x - currentCell.x) < 2 && Mathf.Abs(cell.y - currentCell.y) < 2) units[currentCell.y][ currentCell.x].MeleeAtack(units[cell.y][ cell.x], currentCell, cell); else units[currentCell.y][currentCell.x].RangedAttack(units[cell.y][cell.x], currentCell, cell); } private void ResetAviable() { for (int r = 0; r < RowsCount; r++) { for (int c = 0; c < ColsCount; c++) { board[r, c].ResetCanMove(); } } } public void BotActions() { jsCompiler.ExecuteFunc(battleData.bot.code); CurrentCoroutine = StartCoroutine(InvokeBotActions()); } IEnumerator InvokeBotActions() { yield return new WaitForSeconds(0.5f); while (ActionQueue.Count > 0) { var actData = ActionQueue.Dequeue(); Action(actData.x, actData.y, actData.targetX, actData.targetY); yield return new WaitForSeconds(0.4f); } EndTurn(); } private void PlayerBotActions() { try { jsCompiler.ExecuteFunc(playerCode.text); } catch(Exception e) { jsCompiler.AddLog(e.ToString()); ActionQueue.Clear(); ResetBattle(battleData); return; } CurrentCoroutine = StartCoroutine(InvokeBotActions()); } public void OnClickSubmit() { SubmitButton.interactable = false; isStop = false; PlayerBotActions(); } public void EndTurn() { currentCell = null; if (isAutomatic && isStop) return; currentPlayer = !currentPlayer; endTurnButton.interactable = currentPlayer; ResetAviable(); RefreshUnits(); if (!currentPlayer) BotActions(); else if (isAutomatic) { turnCount++; if (turnCount > 50) ResetBattle(battleData); else PlayerBotActions(); } } public void RefreshUnits() { for (int r = 0; r < RowsCount; r++) { for (int c = 0; c < ColsCount; c++) { var unit = units[r][c]; if (unit) { if (unit.Owner == currentPlayer) { unit.Enable(); } else unit.Disable(); } } } } public void OnUnitDie(Unit unit, Cell cell) { units[cell.y][ cell.x] = null; Destroy(unit.gameObject); CheckEndBattle(); } public void Action(int x, int y, int targetX, int targetY) { var unit = GetUnit(y, x); if(unit && unit.Owner==currentPlayer && unit.isActive) { var target = GetUnit(targetY, targetX); if (target) { if (Mathf.Abs(x - targetX) < 2 && Mathf.Abs(y - targetY) < 2) unit.MeleeAtack(target, board[y, x], board[targetY, targetX]); else if (unit.Type == "Archer") unit.RangedAttack(target, board[y, x], board[targetY, targetX]); } else if(unit.IsCanMove && (Mathf.Abs(x - targetX)==1 && y == targetY) || (Mathf.Abs(y - targetY) == 1 && x == targetX)) { MoveUnit(unit, board[y,x], targetX, targetY); } } } private void CheckEndBattle() { var my = false; var enemy = false; for (int r = 0; r < RowsCount; r++) { for (int c = 0; c < ColsCount; c++) { var unit = units[r][c]; if (unit) { if (unit.Owner) { my = true; } else enemy = true; } } } if (my && !enemy) Win(); else if (!my) Lose(); } public void SetAutomatic() { isAutomatic = true; for (int r = 0; r < RowsCount; r++) { for (int c = 0; c < ColsCount; c++) { board[r, c].turnOff = true; } } endTurnButton.gameObject.SetActive(false); SubmitButton.gameObject.SetActive(true); DisAutoButton.gameObject.SetActive(true); } public void DisableAutomatic() { isAutomatic = false; for (int r = 0; r < RowsCount; r++) { for (int c = 0; c < ColsCount; c++) { board[r, c].turnOff = false; } } endTurnButton.gameObject.SetActive(true); endTurnButton.interactable = currentPlayer; SubmitButton.gameObject.SetActive(false); DisAutoButton.gameObject.SetActive(false); } public void Win() { OnWin.Invoke(); } public void Lose() { ResetBattle(battleData); } private Unit GetUnit(int y, int x) { if (x >= 0 && x < ColsCount && y >= 0 && y < RowsCount) return units[y][x]; else return null; } public void SetSampleCode() { playerCode.text = playerSample.code; } struct ActionData { public int x; public int y; public int targetX; public int targetY; } } [Serializable] public struct Row { public Cell[] cells; public Cell this[int i] { get { return cells[i]; } set { cells[i] = value; } } } [Serializable] public struct Board { public Row[] rows; public Cell this[int x, int y] { get { return rows[x][y]; } set { rows[x][y] = value; } } }
/* 作者: 盛世海 * 创建时间: 2012/7/19 10:36:31 * */ using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.ComponentModel; using MODEL.ViewModel; using Common; using Common.Attributes; using IBLLService; using ShengUI.Helper; using MODEL.DataTableModel; using MODEL.ViewPage; using Common.EfSearchModel.Model; namespace ShengUI.Logic.Admin { [AjaxRequestAttribute] [Description("车辆管理")] public class CarController : Controller { IMST_CAR_MANAGER carB = OperateContext.Current.BLLSession.IMST_CAR_MANAGER; IYX_weiUser_MANAGER userB = OperateContext.Current.BLLSession.IYX_weiUser_MANAGER; ISYS_USERLOGIN_MANAGER sys_UsurLogin = OperateContext.Current.BLLSession.ISYS_USERLOGIN_MANAGER; [DefaultPage] [ActionParent] [ActionDesc("车辆管理首页")] [Description("[车辆管理]车辆管理首页")] public ActionResult CarInfo() { ViewBag.Data = ""; ViewBag.UserName = ""; ViewBag.AddWhere = ""; var usernum = Request.QueryString["userNum"]; var username = Request.QueryString["userName"]; if (!string.IsNullOrEmpty(usernum)) { ViewBag.Data = @"'data': { '[Equal]UserId': '" + usernum + "'}"; ViewBag.UserName = userB.Get(u=>u.userNum==usernum).userRelname; ViewBag.AddWhere = "?userNum="+usernum; } // UserOperateLog.WriteOperateLog("[用户管理]浏览用户详细信息" + SysOperate.Load.ToMessage(true)); return View(); } [ActionDesc("获取车辆列表信息")] [Description("[车辆管理]获取车辆信息(主页必须)")] public ActionResult GetCarForGrid(QueryModel model) { DataTableRequest requestGrid = new DataTableRequest(HttpContext, model); return this.JsonFormat(carB.GetCarForGrid(requestGrid)); } [ViewPage] [ActionDesc("获取车辆信息")] [Description("[车辆管理]详细信息(add,Update,Detail必备)")] public ActionResult CarDetail(string car_cd) { VIEW_MST_CAR car = new VIEW_MST_CAR() { CAR_CD = "CAR" + Common.Tools.Get8Digits() ,AddTime=DateTime.Now}; var usernum = Request.QueryString["userNum"]; if (!string.IsNullOrEmpty(usernum)) { car.UserId = usernum; } var list = sys_UsurLogin.LoadListBy(su => su.LOGIN_ID == OperateContext.Current.UsrId).Select(su => su.SLSORG_CD); var memberlist= DataSelect.ToListViewModel(VIEW_YX_weiUser.ToListViewModel(userB.GetListBy(u => list.Contains(u.TREE_NODE_ID), u => u.userRelname))); ViewBag.MEMBERS = memberlist; ViewBag.ReturnUrl = Request["returnurl"]; ViewDetailPage page = new ViewDetailPage(HttpContext); ViewBag.IsView = page.IsView; //ViewBag.CurrentID = id; ViewBag.IsUpdate = "N"; ViewBag.TYPE = "Update"; var model = carB.Get(u => u.CAR_CD == car_cd); if (model == null) { ViewBag.TYPE = "Add"; ViewBag.IsUpdate = "Y"; return View(car); } if (memberlist.Select(m => m.Value).Contains(model.UserId)) ViewBag.IsUpdate = "Y"; return View(VIEW_MST_CAR.ToViewModel(model)); } [Description("[车辆管理]添加车辆信息")] [ActionDesc("添加车辆", "Y")] public ActionResult Add(VIEW_MST_CAR car) { bool status = false; if (!ModelState.IsValid) return this.JsonFormat(ModelState, status, "ERROR"); var currCar = VIEW_MST_CAR.ToEntity(car); var ReturnUrl = Request["returnurl"]; try { carB.Add(currCar); status = true; } catch (Exception e) { return this.JsonFormat(status, status, SysOperate.Add); } return this.JsonFormat(ReturnUrl, status, SysOperate.Update.ToMessage(status), status); } [Description("[车辆管理]更新车辆信息")] [ActionDesc("编辑", "Y")] public ActionResult Update(VIEW_MST_CAR car) { bool status = false; if (!ModelState.IsValid) return this.JsonFormat(ModelState, status, "ERROR"); var currCar = VIEW_MST_CAR.ToEntity(car); try { carB.Modify(currCar, "UserId", "CAR_NUM", "CAR_BRAND", "CAR_CATEGORY", "CAR_COLOR", "CAR_REMARK"); status = true; } catch (Exception e) { return this.JsonFormat(status, status, SysOperate.Update); } return this.JsonFormat("/Admin/Car/CarInfo", status, SysOperate.Update.ToMessage(status), status); } [ActionDesc("删除", "Y")] [Description("[车辆管理]软删除车辆")] public ActionResult Delete() { var ids = HttpContext.Request["Ids"].Split(',').ToList(); var data = false; try { MODEL.MST_CAR car=new MODEL.MST_CAR(){SYNCOPERATION="D"}; if (carB.ModifyBy(car, m => ids.Contains(m.CAR_CD), "SYNCOPERATION") > 0) { data = true; } return this.JsonFormat(data, data, SysOperate.Delete); } catch (Exception) { return this.JsonFormat(data, data, SysOperate.Delete); } } //[ActionDesc("永久删除", "Y")] //[Description("[微信用户管理]永久删除用户")] //public ActionResult RealDelete() //{ // ViewDetailPage page = new ViewDetailPage(HttpContext); // var model = new MODEL.FW_USER(); // model.USER_ID = page.CurrentID; // bool status = false; // try // { // UserInfoManager.Del(model); // status = true; // } // catch (Exception e) // { // return this.JsonFormat(status, status, SysOperate.Delete); // } // return this.JsonFormat(status, status, SysOperate.Delete); //} //[Description("角色选择的下拉框用户详细")] //public ActionResult GetRolesForSelect() //{ // EasyUISelectRequest requestSelect = new EasyUISelectRequest(HttpContext); // return this.JsonFormat(RoleManager.GetRolesForSelect(requestSelect)); //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace com.Sconit.Web.Models.SearchModels.MD { public class MrpExPlanItemRateSearchModel : SearchModelBase { public string Section { get; set; } public string Item { get; set; } public string SectionDesc { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CameraBazaar.Models.Enums { public enum Make { Canon, Nikon, Penta, Sony } }
using System; using System.Collections.Generic; namespace DataLightning.Core { public class GenericCalcUnit<TInput, TOutput> : CalcUnitBase<TInput, TOutput> { private readonly Func<IDictionary<object, TInput>, TOutput> _function; public GenericCalcUnit(Func<IDictionary<object, TInput>, TOutput> function, params ISubscribable<TInput>[] inputKeys) : base(inputKeys) { _function = function; } protected override TOutput Execute(IDictionary<object, TInput> args, object changedInput) => _function(args); } }
using System; using System.Collections; using UnityEngine; using System.Collections.Generic; [ExecuteInEditMode] public class ChangeRotate : MonoBehaviour { public Vector3 角度; public Transform 道具父物体; public Transform 导弹父物体; public enum MyEnum { 空, 无敌, 双倍, 冲刺, 磁铁, 护盾, 导弹 } public MyEnum 选择道具; public bool 开始调整角度; // Use this for initialization void Start () { } [ExecuteInEditMode] // Update is called once per frame void Update () { if (开始调整角度) { string name = null; switch (选择道具) { case MyEnum.空: Debug.Log("未选择道具"); break; case MyEnum.冲刺: name = "item-dash"; break; case MyEnum.双倍: name = "item-change"; break; case MyEnum.导弹: name = "Missile"; break; case MyEnum.护盾: name = "item-shield"; break; case MyEnum.无敌: name = "item-burst"; break; case MyEnum.磁铁: name = "item-magnet"; break; } List<Transform> list = FindObject(name, 选择道具); foreach (Transform item in list) { item.eulerAngles = 角度; } 开始调整角度 = false; } } List<Transform> FindObject(string name,MyEnum temp) { List<Transform> list = new List<Transform>(); Transform father = null; try { if (temp == MyEnum.导弹) { father = 导弹父物体; } else { father = 道具父物体; } } catch (Exception) { Debug.Log("没有找到道具父物体"); } if (father != null) { foreach (Transform item in father) { if (item.name.Contains(name)) { list.Add(item); } } } return list; } }
using FitnessStore.API.Core.Entities; using Microsoft.EntityFrameworkCore; namespace FitnessStore.API { public class FitnessStoreDbContext : DbContext { public FitnessStoreDbContext(DbContextOptions<FitnessStoreDbContext> options) : base(options) { } public DbSet<Usuario> Usuarios { get; set; } public DbSet<Refeicao> Refeicoes { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Usuario>() .HasMany(u => u.Refeicoes) .WithOne(r => r.Usuario) .HasForeignKey(r => r.CodigoUsuario) .OnDelete(DeleteBehavior.Restrict); modelBuilder.Entity<Refeicao>() .HasKey(r => r.CodigoRefeicao); base.OnModelCreating(modelBuilder); } } }
using System; using System.Collections.Generic; using System.Text; namespace AimaTeam.WebFormLightAPI.httpCore { /// <summary> /// 定义一个响应Josn数据选项枚举 /// </summary> public enum JsonAllowOption : byte { /// <summary> /// 默认,只允许POST /// </summary> Default = 0, /// <summary> /// 允许GET /// </summary> AllowGet = 1, } /// <summary> /// 定义一个允许http请求方法选项的枚举 /// </summary> public enum AllowMethodOption : int { All = 0, Get = 1, Post = 2, Head = 4, Trace = 16, Put = 32, Delete = 64, Options = 128, Connect = 256 } /// <summary> /// 定义一个MD5加密模式枚举 /// </summary> public enum MD5Mode : byte { /// <summary> /// 默认 16 为 md5 Hash /// </summary> Default = 0, /// <summary> /// 加强 32 位 md5 Hash /// </summary> Strongly = 1, } #region 文件上传相关 Enum 定义 /// <summary> /// 定义一个文件上传模式枚举(单文件上传/多文件上传) /// </summary> public enum FileUploadMode : byte { /// <summary> /// 允许多文件上传 /// </summary> Default = 0, /// <summary> /// 只允许单文件上传 /// </summary> Single = 1, } /// <summary> /// 定义一个文件上传类型校验模式枚举(校验只允许,校验不允许) /// </summary> public enum FileUploadTypeValidMode : byte { /// <summary> /// 方式为只允许 /// </summary> AllowType = 0, /// <summary> /// 方式为不允许 /// </summary> UnAllowType = 1, } /// <summary> /// 定义一个文件上传类型校验类型的类型枚举(大小,文件类型) /// </summary> public enum FileUploadTypeValidOption : byte { /// <summary> /// 文件大小 /// </summary> FileSize = 0, /// <summary> /// 文件类型 /// </summary> FileType = 1, } /// <summary> /// 定义一个如果保存文件存在与服务器上时的操作选项枚举 /// </summary> public enum FileUploadExistDoOption : byte { /// <summary> /// 抛出 FileUploadExistException /// </summary> ThrowEx = 0, /// <summary> /// 对新上传文件自动重命名 /// </summary> AutoNewName = 1, /// <summary> /// 备份老文件并上传新文件 /// </summary> BakAndUpload = 2, } #endregion }
using DevExpress.Mvvm.Native; using RomashkaBase.Model; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace RomashkaBase.ViewModel { public class CompaniesAndUsersViewModel : BasePropertyChanged { private ObservableCollection<Company> _companies; public ObservableCollection<Company> Companies { get => _companies; set { _companies = value; OnPropertyChanged(); } } public CompaniesAndUsersViewModel(ApplicationContext db) { Companies = db.Companies.ToObservableCollection(); } } }
using UnityEngine; using System.Collections; public struct GIMMIC_STATUS{ public int X,Y; public int startX,startY; public int trouble; public GameObject number; } public class Map_Input : MonoBehaviour { public static MAP_GIMMIC[,] mapdata; public static MAP_GIMMIC[,] start_mapdata; /// テキストデータのパス public static string filePath; /// 読み込んだテキストデータを格納するテキストアセット public static TextAsset stageTextAsset; /// ステージの文字列データ public static string stageData; /// 抽出した文字を格納する変数 public static int pattern; /// ステージの文字列データの添え字 public static int stageDataIndex; // 上2つのギミックの起動手数保管用変数 public static GIMMIC_STATUS[] appear; public static GIMMIC_STATUS[] disappear; void Start () { } void Update () { } /// テキストデータの読み込み。 /// テキストデータを読み込み、読み込んだテキストデータをステージデータに格納し、空白を削除する /// </remarks> public static void ReadTextData(){ // TextAssetとして、Resourcesフォルダからテキストデータをロードする stageTextAsset = Resources.Load(filePath) as TextAsset; // 文字列を代入 stageData = stageTextAsset.text; // 空白を置換で削除 stageData = stageData.Replace("\n", ""); // ','を置換で削除 stageData = stageData.Replace(",", ""); } // mapdata読み込み public static void Load(){ stageDataIndex = 0; MapAction.Map_X = MapAction.Map_Y = 8; MapAction.magnet_s_count = 0; MapAction.magnet_s_count = 0; MapAction.appear_count = 0; MapAction.disappear_count = 0; mapdata = new MAP_GIMMIC[MapAction.Map_Y, MapAction.Map_X]; start_mapdata = new MAP_GIMMIC[MapAction.Map_Y, MapAction.Map_X]; // 各ギミックの個数確認 for(int i=0;i<MapAction.Map_X*MapAction.Map_Y;i++){ pattern = stageData[stageDataIndex]; if(pattern == '6'){ MapAction.appear_count++; stageDataIndex++; } if(pattern == '7'){ MapAction.disappear_count++; stageDataIndex++; } // 次へ stageDataIndex++; } // ギミックの個数確定 // 上2つのギミックの起動手数保管用変数 appear = new GIMMIC_STATUS[MapAction.appear_count]; disappear = new GIMMIC_STATUS[MapAction.disappear_count]; stageDataIndex = 0; // 逆から格納するための添え字 int Acount = 0; int Dcount = 0; // 配列に値を格納 for (int Y=MapAction.Map_Y-1;Y>=0;Y--) { for(int X=0;X<MapAction.Map_X;X++) { // 文字の抽出 pattern = stageData[stageDataIndex]; switch(pattern) { case '0': mapdata[Y,X] = start_mapdata[Y,X] = MAP_GIMMIC.NONE; break; case '1': mapdata[Y,X] = start_mapdata[Y,X] = MAP_GIMMIC.BLOCK; break; case '2': // プレイヤーの座標を保存して空白にしておく Player.X = Player.StartX = X; Player.Y = Player.StartY = Y; mapdata[Y,X] = start_mapdata[Y,X] = MAP_GIMMIC.NONE; break; case '3': mapdata[Y,X] = start_mapdata[Y,X] = MAP_GIMMIC.GOAL; break; case '4': mapdata[Y,X] = start_mapdata[Y,X] = MAP_GIMMIC.MAGNET_S; MapAction.magnet_s_count++; break; case '5': mapdata[Y,X] = start_mapdata[Y,X] = MAP_GIMMIC.MAGNET_N; MapAction.magnet_n_count++; break; case '6': mapdata[Y,X] = start_mapdata[Y,X] = MAP_GIMMIC.APPEAR; stageDataIndex++; // 手数と座標の保管 appear[Acount].trouble = stageData[stageDataIndex]-48; appear[Acount].X = appear[Acount].startX = X; appear[Acount].Y = appear[Acount].startY = Y; Acount++; break; case '7': mapdata[Y,X] = start_mapdata[Y,X] = MAP_GIMMIC.DISAPPEAR; stageDataIndex++; // 手数と座標の保管 disappear[Dcount].trouble = stageData[stageDataIndex]-48; disappear[Dcount].X = disappear[Dcount].startX = X; disappear[Dcount].Y = disappear[Dcount].startY = Y; Dcount++; break; } // 次へ stageDataIndex++; } } // ギミックの数分座標配列の確保 MapAction.magnet_s_position = new Vector2[MapAction.magnet_s_count]; MapAction.magnet_n_position = new Vector2[MapAction.magnet_n_count]; } }
using curr.Controllers; using curr.Models; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; // The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 namespace curr { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { private WebsiteReader websiteReader; private ObservableCollection<Rate> PopularCurrencies; public MainPage() { this.InitializeComponent(); websiteReader = new WebsiteReader(); prepareBeginningWindow(); } private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e) { WebsiteReader.SelectedDate = (Date)e.AddedItems[0]; PopularCurrencies = WebsiteReader.GetCurrencries(WebsiteReader.SelectedDate); currency_grid.ItemsSource = PopularCurrencies; } private void prepareBeginningWindow() { var today = new Date { Day = DateTime.Today.Day, Month = DateTime.Today.Month, Year = DateTime.Today.Year }; try { PopularCurrencies = WebsiteReader.GetCurrencries(today); } catch (Exception e) { Helper.Message(e.Message); } List<DateTime> dateTimeList = WebsiteReader.DownloadAllCurrenciesWithDates(); var datetime = dateTimeList.Select(x => new Date { Day = x.Day, Month = x.Month, Year = x.Year }).ToList(); date_list_view.ItemsSource = datetime; } } }
using BaseLib.Media.Display; using BaseLib.Media.Video; using SharpDX; using SharpDX.Direct3D9; using System; using System.Diagnostics; namespace BaseLib.Display.WPF { public class RenderFrame : IRenderFrame, IDirectXFrame { private DirectX9Renderer owner; private Format dxfmt; private Texture systexture; private Surface syssurface; private DataRectangle lockrect; public Texture[] Textures { get; } public int Levels => this.Textures.Length; internal Surface[] rendertarget; public RenderFrame(DirectX9Renderer owner, int levels) { this.owner = owner; this.Textures = new Texture[levels]; this.rendertarget = new Surface[levels]; } ~RenderFrame() { Debug.Assert(false); //Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { lock (this.owner.renderframes) { Unlock(); this.systexture?.Dispose(); System.Array.ForEach(this.rendertarget, _rt => _rt?.Dispose()); System.Array.ForEach(this.Textures, _t => _t?.Dispose()); this.owner.renderframes.Remove(this); } } public long Time { get; set; } public int Width { get; private set; } public int Height { get; private set; } public long Duration { get; private set; } public VideoFormat PixelFormat { get; private set; } public IntPtr Data => this.lockrect.DataPointer; public int Stride => this.lockrect.Pitch; void IVideoFrame.Set(VideoFormat pixfmt) { switch (pixfmt) { case VideoFormat.ARGB: this.dxfmt = Format.A8R8G8B8; this.PixelFormat = pixfmt; break; case VideoFormat.RGBA: throw new NotImplementedException(); default: this.dxfmt = Format.X8R8G8B8; this.PixelFormat = VideoFormat.RGB; break; } } bool IVideoFrame.Set(Int64 time, int width, int height, Int64 duration) { this.Time = time; this.Duration = duration; if (this.rendertarget[0] == null && this.owner.device != null) { this.Width = width; this.Height = height; for (int nit = 0; nit < this.Textures.Length; nit++) { this.Textures[nit] = new Texture(this.owner.device, width, height, 1, Usage.RenderTarget, this.dxfmt, Pool.Default); this.rendertarget[nit] = this.Textures[nit].GetSurfaceLevel(0); } } return this.rendertarget != null; } public void Lock() { if (this.syssurface == null) { var rendertargetsurface = this.Textures[0].GetSurfaceLevel(0); if (this.systexture == null) { this.systexture = new Texture(this.owner.device, Width, Height, 1, Usage.None, this.dxfmt, Pool.SystemMemory); } this.syssurface = this.systexture.GetSurfaceLevel(0); this.owner.device.GetRenderTargetData(rendertargetsurface, this.syssurface); rendertargetsurface.Dispose(); this.lockrect = this.syssurface.LockRectangle(LockFlags.ReadOnly); } } public void Unlock() { this.syssurface?.UnlockRectangle(); this.syssurface?.Dispose(); this.syssurface = null; } public void Combine(IVideoFrame[] frames) { owner.Combine(frames, this); /* this.owner.StartRender(this, (Color?)null); try { var dstrec = new System.Drawing.Rectangle(0, 0, this.width, this.height); var effect = this.owner.effect3; var m = Matrix.Scaling(dstrec.Width, dstrec.Height, 1) * Matrix.Translation(dstrec.Left, dstrec.Top, 0); var worldViewProj = m * this.owner.CreateViewMatrix(this.width, this.height); // var texturematrix = Matrix.Scaling(dstrec.Width-1, dstrec.Height-1, 1); effect.SetValue("worldViewProj", worldViewProj); // effect.SetValue("texturematrix", texturematrix); effect.SetTexture("texture0", (fields[0] as IDirectXFrame).Texture); effect.SetTexture("texture1", (fields[1] as IDirectXFrame).Texture); effect.SetValue("vpHeight", this.height); this.owner.Paint( new System.Drawing.Rectangle(0, 0, this.width, this.height), effect, 0); } catch { } finally { this.owner.EndRender(this); }*/ } internal void OnLost() { throw new NotImplementedException(); } internal void OnReset() { throw new NotImplementedException(); } public void Deinterlace(IRenderFrame deinterlace, DeinterlaceModes mode) { owner.Deinterlace(this, deinterlace, mode); } public void CopyTo(IntPtr dataPointer, int pitch) { throw new NotImplementedException(); } } }
// Generates GlassMapper models using System; using System.Linq; using System.Collections.Generic; Log.Debug($"Emitting GlassMapper templates for {ConfigurationName}..."); Code.Append($@" #pragma warning disable 1591 #pragma warning disable 0108 //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by Leprechaun. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.CodeDom.Compiler; using System.Collections.Generic; using global::Glass.Mapper.Sc.Configuration.Attributes; using global::Glass.Mapper.Sc.Fields; using System.Diagnostics.CodeAnalysis; using global::Sitecore.Data; {RenderTemplates()} "); public string RenderTemplates() { var localCode = new System.Text.StringBuilder(); foreach (var template in Templates) { localCode.Append($@" namespace {template.RootNamespace} {{"); break; } foreach (var template in Templates) { localCode.AppendLine($@" /// <summary>Controls the appearance of the inheriting template in site navigation.</summary> [SitecoreType(TemplateId = {template.RootNamespace}.{template.CodeName}Constants.TemplateIdString)] [GeneratedCode(""Leprechaun"", ""{Version}"")] public partial interface I{template.CodeName} : {GetBaseInterfaces(template)} {{{RenderInterfaceFields(template)} }} [ExcludeFromCodeCoverage] [GeneratedCode(""Leprechaun"", ""{Version}"")] public struct {template.CodeName}Constants {{ public const string TemplateIdString = ""{template.Id}""; public static readonly ID TemplateId = new ID(TemplateIdString); public const string TemplateName = ""{template.Name}""; { RenderConstantFields(template) } }} [ExcludeFromCodeCoverage] [GeneratedCode(""Leprechaun"", ""{Version}"")] public partial class {template.CodeName} : GlassBase, I{template.CodeName} {{{ RenderClassFields(template) } }}"); } if (Templates.Any()) { localCode.Append($@" }}"); } return localCode.ToString(); } public string RenderClassFields(TemplateCodeGenerationMetadata template) { var localCode = new System.Text.StringBuilder(); foreach (var field in template.AllFields) { localCode.Append($@" /// <summary> /// Represents {field.Name} field /// <para>Path: {field.Path}</para> /// <para>ID: {field.Id}</para> /// </summary> [SitecoreField(FieldName = {template.CodeName}Constants.{field.CodeName}FieldName)] public virtual {GetFieldType(field)} {field.CodeName} {{ get; set; }} "); } return localCode.ToString().TrimEnd(); } public string GetBaseInterfaces(TemplateCodeGenerationMetadata template) { var bases = new System.Collections.Generic.List<string>(template.BaseTemplates.Count + 1); foreach (var baseTemplate in template.BaseTemplates) { bases.Add($"global::{baseTemplate.RootNamespace}.I{baseTemplate.CodeName}"); } if (bases.Count == 0) { // IGlassBase only needed when no other bases exist otherwise irrelevant by transitive inheritance bases.Add("IGlassBase"); } return string.Join(", ", bases); } public string RenderInterfaceFields(TemplateCodeGenerationMetadata template) { var localCode = new System.Text.StringBuilder(); foreach (var field in template.OwnFields) { localCode.AppendLine($@" /// <summary>{field.HelpText}</summary> [SitecoreField(FieldName = {template.RootNamespace}.{template.CodeName}Constants.{field.CodeName}FieldName)] {GetFieldType(field)} {field.CodeName} {{ get; set; }}"); } return localCode.ToString().TrimEnd(); } public string RenderConstantFields(TemplateCodeGenerationMetadata template) { var localCode = new System.Text.StringBuilder(); foreach (var field in template.AllFields) { localCode.AppendLine($@" public static readonly ID {field.CodeName}FieldId = new ID(""{field.Id}""); public const string {field.CodeName}FieldName = ""{field.CodeName}"";"); } return localCode.ToString().TrimEnd(); } public string GetFieldType(TemplateFieldCodeGenerationMetadata field) { switch (field.Type.ToLower()) { case "tristate": return "TriState"; case "checkbox": return "bool"; case "date": case "datetime": return "DateTime"; case "number": return "float"; case "integer": return "int"; case "treelist": return "IEnumerable<Guid>"; case "treelistex": case "treelist descriptive": case "checklist": case "multilist": return "IEnumerable<Guid>"; case "grouped droplink": case "droplink": case "lookup": case "droptree": case "reference": case "tree": return "Guid"; case "file": return "File"; case "image": return "ExtendedImage"; case "rich text": case "html": return "string"; case "general link": return "Link"; case "name value list": return "System.Collections.Specialized.NameValueCollection"; case "single-line text": case "multi-line text": case "frame": case "text": case "memo": case "droplist": case "grouped droplist": case "valuelookup": return "string"; default: return "string"; } }
using Alabo.Datas.Stores; using Alabo.Datas.UnitOfWorks; using Alabo.Domains.Dtos; using Alabo.Domains.Entities; using Alabo.Domains.Query; using Alabo.Domains.Services.Single; using Alabo.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace Alabo.Domains.Services.List { public abstract class GetListBaseAsync<TEntity, TKey> : SingleAsyncBase<TEntity, TKey>, IGetListAsync<TEntity, TKey> where TEntity : class, IAggregateRoot<TEntity, TKey> { /// <summary> /// 服务构造函数 /// </summary> /// <param name="unitOfWork">工作单元</param> /// <param name="store">仓储</param> protected GetListBaseAsync(IUnitOfWork unitOfWork, IStore<TEntity, TKey> store) : base(unitOfWork, store) { } public async Task<List<TDto>> GetAllAsync<TDto>() where TDto : IResponse, new() { var list = await GetListAsync(); return ToDto<TDto>(list).ToList(); } public async Task<IEnumerable<TEntity>> GetListAsync() { return await Store.GetListAsync(); } public async Task<IEnumerable<TEntity>> GetListAsync(Expression<Func<TEntity, bool>> predicate) { return await Store.GetListAsync(predicate); } public async Task<IEnumerable<TEntity>> GetListAsync(Dictionary<string, string> dictionary) { var predicate = LinqHelper.DictionaryToLinq<TEntity>(dictionary); return await GetListAsync(predicate); } public async Task<IEnumerable<TEntity>> GetListAsync(IExpressionQuery<TEntity> query) { // return await Store.GetList(query).ToList(); throw new NotImplementedException(); } public async Task<IEnumerable<TEntity>> GetListAsync(IEnumerable<TKey> ids) { return await GetListAsync(r => ids.Contains(r.Id)); } public async Task<List<TEntity>> GetListNoTrackingAsync(Expression<Func<TEntity, bool>> predicate = null) { throw new NotImplementedException(); } } }
using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.ProviderCommitments.Web.Models.Apprentice; using System.Threading.Tasks; using SFA.DAS.ProviderCommitments.Interfaces; using SFA.DAS.ProviderCommitments.Web.Services.Cache; namespace SFA.DAS.ProviderCommitments.Web.Mappers.Apprentice { public class EndDateRequestMapper : IMapper<StartDateViewModel, EndDateRequest> { private readonly ICacheStorageService _cacheStorage; public EndDateRequestMapper(ICacheStorageService cacheStorage) { _cacheStorage = cacheStorage; } public async Task<EndDateRequest> Map(StartDateViewModel source) { var cacheItem = await _cacheStorage.RetrieveFromCache<ChangeEmployerCacheItem>(source.CacheKey); cacheItem.StartDate = source.StartDate.Date.Value.ToString("MMyyyy"); await _cacheStorage.SaveToCache(cacheItem.Key, cacheItem,1); return new EndDateRequest { ApprenticeshipHashedId = source.ApprenticeshipHashedId, ProviderId = source.ProviderId, CacheKey = source.CacheKey }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio30 { class MatrizTriangular { static void Main(string[] args) { { Console.Write("Triangular superior (S) ou inferior (I)? "); Char Tipo = Convert.ToChar(Console.ReadLine()); Console.Write("Número de linhas da matriz? "); int N = Convert.ToInt16(Console.ReadLine()); int[,] A = new int[N, N]; if (Tipo == 'i' || Tipo == 'I') { for (int I = 0; I <= N - 1; I++) for (int J = 0; J <= I; J++) { Console.Write("a[{0},{1}] =", I, J); A[I, J] = Convert.ToInt16(Console.ReadLine()); if (I != J) A[J, I] = 0; } } else { for (int I = 0; I <= N - 1; I++) for (int J = N - 1; J >= I; J--) { Console.Write("a[{0},{1}]=", I, J); A[I, J] = Convert.ToInt16(Console.ReadLine()); if (I != J) A[J, I] = 0; } } for (int I = 0; I <= N - 1; I++) { for (int J = 0; J <= N - 1; J++) Console.Write("{0, 4}", A[I, J]); Console.WriteLine(); } } } } }
using Abhs.Model.Access; using Abhs.Model.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Abhs.Application.IService { public interface IPackageLessonService : IBaseService<SysPackageLesson> { void PackageLessonInit(); /// <summary> /// 获取所有课时 /// </summary> /// <returns></returns> List<SysPackageLesson> GetAllPackageLessonByCache(); /// <summary> /// 从缓存获取实体 /// </summary> /// <param name="id"></param> /// <returns></returns> SysPackageLesson GetModelByCache(int id); /// <summary> /// 获取课时 /// </summary> /// <param name="id"></param> /// <returns></returns> SysPackageLesson GetModel(int id); /// <summary> /// 获取课程下的课时,有缓存 /// </summary> /// <param name="packId"></param> /// <returns></returns> List<SysPackageLesson> GetModelListByPackId(int packId); /// <summary> /// 获取课程下的课时,包含未审核的,有缓存 /// </summary> /// <param name="packId"></param> /// <returns></returns> List<SysPackageLesson> GetListByPackId(int packId); /// <summary> /// 获取多个课时 /// </summary> /// <param name="packIds"></param> /// <returns></returns> List<SysPackageLesson> GetLessonByPackIds(List<int> packIds); } }
namespace Exp002_Sb_SagaCommon { using System; public interface ITripStarted { Guid CorrelationId { get; } //ILog Log { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace Sintaxis1 { class Lexico:Token,IDisposable { StreamReader archivo; StreamWriter bitacora; const int F = -1; const int E = -2; int linea, caracter; int[,] TRAND6V = { //WS,EF, L, D, ., E, +, -, =, :, ;, &, |, !, >, <, *, /, %, ", ', ?,La, {, },#10 { 0, F, 1, 2,29, 1,19,20, 8, 9,11,12,13,14,17,18,22,32,22,24,26,28,29,30,31, 0 },//Estado 0 { F, F, 1, 1, F, 1, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 1 { F, F, F, 2, 3, 5, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 2 { E, E, E, 4, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, F, F, E },//Estado 3 { F, F, F, 4, F, 5, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 4 { E, E, E, 7, E, E, 6, 6, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, F, F, F },//Estado 5 { E, E, E, 7, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, F, F, F },//Estado 6 { F, F, F, 7, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 7 { F, F, F, F, F, F, F, F,16, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 8 { F, F, F, F, F, F, F, F,10, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 9 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 10 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 11 { F, F, F, F, F, F, F, F, F, F, F,15, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 12 { F, F, F, F, F, F, F, F, F, F, F, F,15, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 13 { F, F, F, F, F, F, F, F,16, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 14 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 15 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 16 { F, F, F, F, F, F, F, F,16, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 17 { F, F, F, F, F, F, F, F,16, F, F, F, F, F,16, F, F, F, F, F, F, F, F, F, F, F },//Estado 18 { F, F, F, F, F, F,21, F,21, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 19 { F, F, F, F, F, F, F,21,21, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 20 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 21 { F, F, F, F, F, F, F, F,23, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 22 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 23 { 24, E,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,25,24,24,24, F, F,24 },//Estado 24 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 25 { 26, E,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,27,26,26, F, F,26 },//Estado 26 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 27 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 28 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 29 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 30 { F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F, F },//Estado 31 { F, F, F, F, F, F, F, F,23, F, F, F, F, F, F, F,34,33, F, F, F, F, F, F, F, F },//Estado 32 { 33, 0,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33,33, 0 },//Estado 33 { 34, E,34,34,34,34,34,34,34,34,34,34,34,34,34,34,35,34,34,34,34,34,34,34,34,34 },//Estado 34 { 34, E,34,34,34,34,34,34,34,34,34,34,34,34,34,34,35, 0,34,34,34,34,34,34,34,34 },//Estado 35 //WS,EF, L, D, ., E, +, -, =, :, ;, &, |, !, >, <, *, /, %, ", ', ?,La, {, },#10 }; public Lexico() { Console.WriteLine("Compilando el archivo Prueba.txt..."); Console.WriteLine("Inicia analisis lexico"); if (File.Exists("C:\\Archivos\\Prueba.txt")) { linea = caracter = 1; archivo = new StreamReader("C:\\Archivos\\Prueba.txt"); bitacora = new StreamWriter("C:\\Archivos\\Prueba.log"); bitacora.AutoFlush = true; bitacora.WriteLine("Archivo: Prueba.txt"); bitacora.WriteLine("Directorio: C:\\Archivos"); bitacora.WriteLine("Fecha: " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToString("HH:mm:ss")); } else { throw new Exception("El archivo Prueba.txt no existe"); } } public Lexico(string nombre) { Console.WriteLine("Compilando el archivo "+nombre); Console.WriteLine("Inicia analisis lexico"); if (File.Exists(nombre)) { linea = caracter = 1; archivo = new StreamReader(nombre); bitacora = new StreamWriter(Path.ChangeExtension(nombre,"log")); bitacora.AutoFlush = true; bitacora.WriteLine("Archivo: "+nombre); bitacora.WriteLine("Directorio: "); bitacora.WriteLine("Fecha: " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToString("HH:mm:ss")); } else { throw new Exception("El archivo "+nombre+" no existe"); } } //~Lexico() public void Dispose() { CerrarArchivos(); Console.WriteLine("Finaliza compilacion"); } private void CerrarArchivos() { archivo.Close(); bitacora.Close(); } protected void NextToken() { int estado = 0; char c; string palabra = ""; while (estado >= 0) { c = (char)archivo.Peek(); estado = TRAND6V[estado, Columna(c)]; Clasifica(estado); if (estado >= 0) { archivo.Read(); caracter++; if (c == 10) { linea++; caracter = 1; } if (estado > 0) palabra += c; else palabra = ""; } } setContenido(palabra); if (getClasificacion() == Clasificaciones.Identificador) { switch (getContenido()) { case "char": case "int": case "float": setClasificacion(Clasificaciones.TipoDato); break; case "private": case "protected": case "public": setClasificacion(Clasificaciones.Zona); break; case "if": case "else": case "switch": setClasificacion(Clasificaciones.Condicion); break; case "for": case "while": case "do": setClasificacion(Clasificaciones.Ciclo); break; } } if (estado == E) { string mensaje = "Error Lexico Linea " + linea + " Caracter " + caracter + " : " + (mensaje = Error(palabra)); bitacora.WriteLine(mensaje); throw new Exception(mensaje); } else if (palabra != "") { bitacora.WriteLine("Token = " + getContenido()); bitacora.WriteLine("Clasificacion = " + getClasificacion()); } } private int Columna(char t) { //WS,EF, L, D, ., E, +, -, =, :, ;, &, |, !, >, <, *, /, %, ", ', ?,La, {, },#10 if (FinArchivo()) return 1; if (t == 10) return 25; if (char.IsWhiteSpace(t)) return 0; if (char.ToLower(t) == 'e') return 5; if (char.IsLetter(t)) return 2; if (char.IsDigit(t)) return 3; if (t == '.') return 4; if (t == '+') return 6; if (t == '-') return 7; if (t == '=') return 8; if (t == ':') return 9; if (t == ';') return 10; if (t == '&') return 11; if (t == '|') return 12; if (t == '!') return 13; if (t == '>') return 14; if (t == '<') return 15; if (t == '*') return 16; if (t == '/') return 17; if (t == '%') return 18; if (t == '"') return 19; if (t == '\'') return 20; if (t == '?') return 21; if (t == '{') return 23; if (t == '}') return 24; return 22; //WS,EF, L, D, ., E, +, -, =, :, ;, &, |, !, >, <, *, /, %, ", ', ?,La, {, },#10 } private void Clasifica(int estado) { switch (estado) { case 1: setClasificacion(Clasificaciones.Identificador); break; case 2: setClasificacion(Clasificaciones.Numero); break; case 8: setClasificacion(Clasificaciones.Asignacion); break; case 9: case 12: case 13: case 29: setClasificacion(Clasificaciones.Caracter); break; case 10: setClasificacion(Clasificaciones.Inicializacion); break; case 11: setClasificacion(Clasificaciones.FinSentencia); break; case 14: case 15: setClasificacion(Clasificaciones.OperadorLogico); break; case 16: case 17: case 18: setClasificacion(Clasificaciones.OperadorRelacional); break; case 19: case 20: setClasificacion(Clasificaciones.OperadorTermino); break; case 21: setClasificacion(Clasificaciones.IncrementoTermino); break; case 22: case 32: setClasificacion(Clasificaciones.OperadorFactor); break; case 23: setClasificacion(Clasificaciones.IncrementoFactor); break; case 24: case 26: setClasificacion(Clasificaciones.Cadena); break; case 28: setClasificacion(Clasificaciones.Ternario); break; case 30: setClasificacion(Clasificaciones.InicioBloque); break; case 31: setClasificacion(Clasificaciones.FinBloque); break; } } protected string Error(string palabra) { string mensaje = ""; if (palabra.EndsWith(".")) mensaje = "Sintaxis del numero incorrecta, Falta digito"; if (palabra.EndsWith("E") || palabra.EndsWith("e") || palabra.EndsWith("+") || palabra.EndsWith("-")) mensaje = "Sintaxis del numero incorrecta, Falta parte exponencial"; if (palabra.StartsWith("\"") || palabra.StartsWith("'")) mensaje = "Sintaxis de la cadena incorrecta, Cerrar Cadena"; if (palabra.StartsWith("/")) mensaje = "Sintaxis incorrecta, Cerrar Comentario"; return mensaje; } public bool FinArchivo() { return archivo.EndOfStream; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IPTables.Net.Netfilter; namespace IPTables.Net.NfTables { public class NfTablesChainSet : NetfilterChainSet<NfTablesChain, NfTablesRule> { protected override NfTablesChain CreateChain(string tableName, string chainName, NetfilterSystem system) { return new NfTablesChain(tableName, chainName, system); } } }
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Net.Http; using System.Net.Http.Headers; using Newtonsoft.Json; using System.Threading.Tasks; using Kulula.com.Helpers; using Kulula.com.Models; namespace Kulula.com.Services { class FlightBookingService { private string rootUrl = "http://192.168.1.203:45455/"; // GET FlightBooking information public async Task<List<FlightBooking>> GetFlightBookings() { var httpClient = new HttpClient(); var json = await httpClient.GetStringAsync(rootUrl + "api/FlightBookings"); var flightBookings = JsonConvert.DeserializeObject<List<FlightBooking>>(json); return flightBookings; } // GET FlightBooking by ID public async Task<FlightBooking> GetFlightBooking(int id) { var httpClient = new HttpClient(); var json = await httpClient.GetStringAsync(rootUrl + "api/FlightBookings/" + id); var flightBooking = JsonConvert.DeserializeObject<FlightBooking>(json); Debug.WriteLine(flightBooking); return flightBooking; } // POST FlightBooking public async Task addflightBooking(FlightBooking flightBooking) { var httpClient = new HttpClient(); var json = JsonConvert.SerializeObject(flightBooking); StringContent stringContent = new StringContent(json); stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = await httpClient.PostAsync(rootUrl + "api/FlightBookings", stringContent); } // PUT FlightBooking public async Task UpdateflightBookings(int id, FlightBooking flightBooking) { var httpClient = new HttpClient(); var json = JsonConvert.SerializeObject(flightBooking); StringContent stringContent = new StringContent(json); stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); var result = await httpClient.PutAsync(rootUrl + "api/FlightBookings/" + id, stringContent); } // DELETE FlightBooking public async Task DeleteflightBooking(int id) { var httpClient = new HttpClient(); var response = await httpClient.DeleteAsync(rootUrl + "api/FlightBookings/" + id); } } }
// Print Out Obityary public partial class printObituary : PortalModuleBase { protected void Page_PreRender(object sender, EventArgs e) { try { //checks if there is a obituary id to use if (!string.IsNullOrEmpty(Request.QueryString["id"])) { string strObitID = DAL.safeSql(Request.QueryString["id"]);//holds the id of the obituary DataTable dtObituaryDetails = DAL.getRow("", "WHERE = " + strObitID);//holds the Obituary details //checks if there is any details for this obituary if (dtObituaryDetails != null && dtObituaryDetails.Rows.Count > 0) { int intIndexServiceID = 0;//holds the unquie id of the row string strLastFHID = "";//holds what is the last FHID DataTable dtObitImage = DAL.getRow("", "WHERE = " + strObitID + " Order by ");//gets all image for this obituary //sets the basis settings lblName.Text = dtObituaryDetails.Rows[0][""].ToString() + ", " + dtObituaryDetails.Rows[0][""].ToString() + " " + dtObituaryDetails.Rows[0][""].ToString(); //checks if there is a birth date if(!string.IsNullOrEmpty(dtObituaryDetails.Rows[0][""].ToString())) lblBirthDateAndPassingDate.Text += Convert.ToDateTime(dtObituaryDetails.Rows[0][""].ToString()).ToString("MMMM dd, yyyy"); //checks that there must be both a birth\death date for - to display if(!string.IsNullOrEmpty(dtObituaryDetails.Rows[0][""].ToString()) && !string.IsNullOrEmpty(dtObituaryDetails.Rows[0][""].ToString())) lblBirthDateAndPassingDate.Text += " - "; //checks if there is a death date or a is this a pre-plan obituarie if(!string.IsNullOrEmpty(dtObituaryDetails.Rows[0][""].ToString())) //sets the death year lblBirthDateAndPassingDate.Text += Convert.ToDateTime(dtObituaryDetails.Rows[0][""].ToString()).ToString("MMMM dd, yyyy"); //checks if there is any sevices if(dtObitImage.Rows.Count > 0) { //checks if the file in file system if so then display it if (File.Exists(Server.MapPath("~\\images\\User\\" + strObitID + "\\" + dtObitImage.Rows[0][""].ToString()))) { //sets this obituary image imgObituary.AlternateText = lblName.Text; imgObituary.ImageUrl = "/images/User/" + strObitID + "/" + dtObitImage.Rows[0][""].ToString(); //adds Image for display imgObituary.Visible = true; }//end of if }//end of if //checks if there is obituary text is being use if (!string.IsNullOrEmpty(dtObituaryDetails.Rows[0][""].ToString())) //gets the first half the obituary text litObituaryDetails.Text = Server.HtmlDecode(dtObituaryDetails.Rows[0][""].ToString()); }//end of if }//end of if else throw new Exception("Unable to find this Obituary"); }//end of try catch (Exception ex) { lblMainError.Text = ex.Message; panMainError.Visible = true; }//end of catch }//end of Page_PreRender() }//end of Module
using System.Collections; using Spring.RabbitQuickStart.Common.Data; namespace Spring.RabbitQuickStart.Server.Services.Stubs { public class CreditCheckServiceStub : ICreditCheckService { public bool CanExecute(TradeRequest tradeRequest, IList errors) { return true; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GoalShoot : MonoBehaviour { private Vector3 bestShoot = new Vector3(7f,16.5f,0); private Vector3 prevAcceleration; private bool isRunning,isDamageRunning; private bool isDamage; public Animation anim; public GyroInput gyro; public AudioSource audioSource; public AudioClip shoot,damage; // Use this for initialization void Start () { isDamage = false; } // Update is called once per frame void Update () { StartCoroutine ("Interval"); if (isDamage) { StartCoroutine ("Damage"); gyro.enabled = false; Debug.Log ("ダメージなう"); } } void OnTriggerEnter(Collider col){ if (!isDamage) { switch (col.gameObject.tag) { case "Ball": { if (heddingBall ()) { col.gameObject.layer = LayerMask.NameToLayer ("ToutchedBall"); if (this.gameObject.tag == "DummyCol") col.gameObject.GetComponent<Rigidbody> ().velocity = this.transform.forward * Random.Range (15, 25); else if (this.gameObject.tag == "BestHitCol") col.gameObject.GetComponent<Rigidbody> ().velocity = bestShoot; audioSource.PlayOneShot (shoot); col.gameObject.layer = LayerMask.NameToLayer ("ToutchedBall"); } break; } case "NotBall": { isDamage = true; anim.Play (); audioSource.PlayOneShot (damage); break; } default: break; } } } IEnumerator Interval(){ if (isRunning) yield break; isRunning = true; yield return new WaitForSeconds (0.25f); prevAcceleration = Input.acceleration; isRunning = false; } IEnumerator Damage(){ if (isDamageRunning) yield break; isDamageRunning = true; yield return new WaitForSeconds (1f); isDamage = false; isDamageRunning = false; gyro.enabled = true; } bool heddingBall(){ if (Input.acceleration.z < prevAcceleration.z && Mathf.Abs (Input.acceleration.z - prevAcceleration.z) > 0.3f) return true; else return false; } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; namespace PayRentAndUse_V3.Models { public class VehicleClass { public int Id { get; set; } [Required(ErrorMessage = "Please Vehicle Name")] [Display(Name = "Vehicle Name :")] [StringLength(maximumLength: 50, MinimumLength = 2, ErrorMessage = "Vehicle Name must be Max 50 and Min 2")] public string Name { get; set; } [Required(ErrorMessage = "Please Vehicle Manufactured Year")] [Display(Name = "Manufactured Year :")] public int YearManufactured { get; set; } } }
namespace Fingo.Auth.Domain.CustomData.ConfigurationClasses.Project { public class BooleanProjectConfiguration : ProjectConfiguration { public bool Default { get; set; } } }
using System; namespace CursoCsharp.TopicosAvancados { class Dynamic { public static void Executar() { dynamic meuObjeto = "Teste"; meuObjeto = 3; meuObjeto++; Console.WriteLine(meuObjeto); dynamic Aluno = new System.Dynamic.ExpandoObject(); Aluno.Nome = "Leonardo"; Aluno.Idade = 23; Aluno.Nota = 8.9; Console.WriteLine($"{Aluno.Nome} {Aluno.Idade} {Aluno.Nota}"); } } }
using System; using System.IO; using System.Windows.Controls; using System.Windows.Media.Imaging; namespace gView.Desktop.Wpf.Controls { public static class ToolBarFactory { static public ToolBar NewToolBar(bool hasGrip = true) { ToolBar toolbar = new ToolBar(); //toolbar.Height = 26; toolbar.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; toolbar.VerticalAlignment = System.Windows.VerticalAlignment.Top; toolbar.Background = new System.Windows.Media.SolidColorBrush( System.Windows.Media.Color.FromArgb(255, 188, 199, 216)); toolbar.BorderBrush = new System.Windows.Media.SolidColorBrush( System.Windows.Media.Color.FromArgb(255, 213, 220, 232)); toolbar.Margin = new System.Windows.Thickness(0, 0, 0, 0); toolbar.Padding = new System.Windows.Thickness(0, 0, 0, 0); if (hasGrip == false) { } return toolbar; } static public void AppendToolButton(ToolBar toolbar, Image image, string text = "", System.Windows.RoutedEventHandler click = null) { Button button = new Button(); AppendToolButtonProperties(button, image, text, click); if (button.Content == null) { return; } toolbar.Items.Add(button); } static public void AppendSeperator(ToolBar toolbar) { Separator sep = new Separator(); sep.Background = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 133, 145, 162)); toolbar.Items.Add(sep); } static public void AppendToolButtonProperties(Button button, Image image, string text, System.Windows.RoutedEventHandler click = null) { object content = image; if (!String.IsNullOrEmpty(text)) { content = new StackPanel(); ((StackPanel)content).Orientation = Orientation.Horizontal; if (image != null) { ((StackPanel)content).Children.Add(image); } var textBlock = new TextBlock(); textBlock.Text = text; textBlock.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 47, 21, 62)); ((StackPanel)content).Children.Add(textBlock); } else { button.Width = 24; } if (content != null) { button.Content = content; } if (click != null) { button.Click += click; } button.Height = 24; } } public static class ImageFactory { static public Image FromBitmap(System.Drawing.Image bm) { if (bm == null) { return null; } Image image = new Image(); MemoryStream ms = new MemoryStream(); bm.Save(ms, System.Drawing.Imaging.ImageFormat.Png); ms.Position = 0; BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.StreamSource = ms; bi.EndInit(); image.Source = bi; image.Width = bm.Width; image.Height = bm.Height; return image; } } }
using UnityEngine; public class PSplay : MonoBehaviour { [SerializeField] private ParticleSystem particleSystem; private void Start() { //Unparent the particles. transform.parent = null; //Play the particle system. particleSystem.Play(); //Once the particles have finished, destroy the gameobject they are on. Destroy(particleSystem.gameObject, particleSystem.main.duration); } }
using System; using System.Collections.Generic; using UnityEngine; public class TangentBasis : MonoBehaviour { /// <summary> /// Gets an array of tangent vectors for a mesh. /// </summary> /// <param name="mesh"></param> /// <returns></returns> public static Vector4[] GetMeshTangets(Mesh mesh, float hand) { var verts = mesh.vertices; var uvs = mesh.uv; var norms = mesh.normals; var length = mesh.triangles.Length; var tangents = new Vector4[length]; for (int i = 0; i < length; i+=3) { var tangent = new Vector3(); TangentBasis.Compute(verts[i], uvs[i], verts[i+1], uvs[i+1], verts[i+2], uvs[i+2], ref tangent); tangents[i] = AddHand(tangent, hand); tangents[i+1] = AddHand(tangent, hand); tangents[i+2] = AddHand(tangent, hand); } return tangents; } /// <summary> /// Adds the w component to the vector representing handedness of the tangent. /// </summary> /// <param name="tangent"></param> /// <param name="hand"></param> /// <returns></returns> static Vector4 AddHand(Vector3 tangent, float hand) { return new Vector4(tangent.x, tangent.y, tangent.z, hand); } /// <summary> /// Computes tangent, normal and basis for a triangle. /// </summary> /// <param name="P0">triangle vert 1</param> /// <param name="P1">triangle vert 2</param> /// <param name="P2">triangle vert 2</param> /// <param name="UV0">triangle uv 1</param> /// <param name="UV1">triagnle uv 2</param> /// <param name="UV2">triangle uv 3</param> /// <param name="normal">normal vector reference</param> /// <param name="tangent">tangent vector reference</param> /// <param name="binormal">binormal vector reference</param> static void Compute(Vector3 P0, Vector2 UV0, Vector3 P1, Vector2 UV1, Vector3 P2, Vector2 UV2, ref Vector3 normal, ref Vector3 tangent, ref Vector3 binormal) { Vector3 e0 = P1 - P0; Vector3 e1 = P2 - P0; normal = Vector3.Cross(e0, e1); Vector3 P = P1 - P0; Vector3 Q = P2 - P0; float s1 = UV1.x - UV0.x; float t1 = UV1.y - UV0.y; float s2 = UV2.x - UV0.x; float t2 = UV2.y - UV0.y; float tmp = 0.0f; if (Mathf.Abs(s1 * t2 - s2 * t1) <= 0.0001f) { tmp = 1.0f; } else { tmp = 1.0f / (s1 * t2 - s2 * t1); } tangent.x = (t2 * P.x - t1 * Q.x); tangent.y = (t2 * P.y - t1 * Q.y); tangent.z = (t2 * P.z - t1 * Q.z); tangent = tangent * tmp; binormal.x = (s1 * Q.x - s2 * P.x); binormal.y = (s1 * Q.y - s2 * P.y); binormal.z = (s1 * Q.z - s2 * P.z); binormal = binormal * tmp; normal.Normalize(); tangent.Normalize(); binormal.Normalize(); } /// <summary> /// Computes tangent and basis for a triangle. /// </summary> /// <param name="P0"></param> /// <param name="P1"></param> /// <param name="P2"></param> /// <param name="UV0"></param> /// <param name="UV1"></param> /// <param name="UV2"></param> /// <param name="tangent"></param> /// <param name="binormal"></param> static void Compute(Vector3 P0, Vector2 UV0, Vector3 P1, Vector2 UV1, Vector3 P2, Vector2 UV2, ref Vector3 tangent, ref Vector3 binormal) { Vector3 P = P1 - P0; Vector3 Q = P2 - P0; float s1 = UV1.x - UV0.x; float t1 = UV1.y - UV0.y; float s2 = UV2.x - UV0.x; float t2 = UV2.y - UV0.y; float tmp = 0.0f; if (Mathf.Abs(s1 * t2 - s2 * t1) <= 0.0001f) { tmp = 1.0f; } else { tmp = 1.0f / (s1 * t2 - s2 * t1); } tangent.x = (t2 * P.x - t1 * Q.x); tangent.y = (t2 * P.y - t1 * Q.y); tangent.z = (t2 * P.z - t1 * Q.z); tangent = tangent * tmp; binormal.x = (s1 * Q.x - s2 * P.x); binormal.y = (s1 * Q.y - s2 * P.y); binormal.z = (s1 * Q.z - s2 * P.z); binormal = binormal * tmp; tangent.Normalize(); binormal.Normalize(); } /// <summary> /// Computes tangent for a triangle. /// </summary> /// <param name="P0"></param> /// <param name="P1"></param> /// <param name="P2"></param> /// <param name="UV0"></param> /// <param name="UV1"></param> /// <param name="UV2"></param> /// <param name="tangent"></param> static void Compute(Vector3 P0, Vector2 UV0, Vector3 P1, Vector2 UV1, Vector3 P2, Vector2 UV2, ref Vector3 tangent) { Vector3 P = P1 - P0; Vector3 Q = P2 - P0; float s1 = UV1.x - UV0.x; float t1 = UV1.y - UV0.y; float s2 = UV2.x - UV0.x; float t2 = UV2.y - UV0.y; float tmp = 0.0f; if (Mathf.Abs(s1 * t2 - s2 * t1) <= 0.0001f) { tmp = 1.0f; } else { tmp = 1.0f / (s1 * t2 - s2 * t1); } tangent.x = (t2 * P.x - t1 * Q.x); tangent.y = (t2 * P.y - t1 * Q.y); tangent.z = (t2 * P.z - t1 * Q.z); tangent = tangent * tmp; tangent.Normalize(); } }
using System; using System.Linq; namespace Radioactive_Mutant_Vampire_Bunnies { class Program { static void Main(string[] args) { var dimensions = Console.ReadLine().Split().Select(int.Parse).ToArray(); var n = dimensions[0]; var m = dimensions[1]; var matrix = new char[n, m]; var playerRow = -1; var playerCol = -1; for (int row = 0; row < n; row++) { var input = Console.ReadLine().ToCharArray(); for (int col = 0; col < m; col++) { matrix[row, col] = input[col]; if (matrix[row, col] == 'P') { playerRow = row; playerCol = col; } } } var commands = Console.ReadLine().ToCharArray(); foreach (var command in commands) { if (command == 'U') { SpreadBunnies(matrix); PrintMatrix(matrix); if (CheckForLoseWithBunny(matrix)) { PrintMatrix(matrix); Console.WriteLine($"dead: {playerRow} {playerCol}"); return; } if (CheckWinUp(matrix, playerRow, playerCol)) { PrintMatrix(matrix); Console.WriteLine($"won: {playerRow} {playerCol}"); return; } if (CheckForLoseWithRunningUp(matrix, playerRow, playerCol)) { PrintMatrix(matrix); Console.WriteLine($"dead: {playerRow} {playerCol}"); return; } MoveUp(matrix, playerRow, playerCol); playerRow--; } else if (command == 'D') { SpreadBunnies(matrix); if (CheckForLoseWithBunny(matrix)) { PrintMatrix(matrix); Console.WriteLine($"dead: {playerRow} {playerCol}"); return; } if (CheckWinDown(matrix, playerRow, playerCol)) { PrintMatrix(matrix); Console.WriteLine($"won: {playerRow} {playerCol}"); return; } if (CheckForLoseWithRunningDown(matrix, playerRow, playerCol)) { PrintMatrix(matrix); Console.WriteLine($"dead: {playerRow} {playerCol}"); return; } MoveDown(matrix, playerRow, playerCol); playerRow++; } else if (command == 'L') { SpreadBunnies(matrix); PrintMatrix(matrix); if (CheckForLoseWithBunny(matrix)) { PrintMatrix(matrix); Console.WriteLine($"dead: {playerRow} {playerCol}"); return; } if (CheckWinLeft(matrix, playerRow, playerCol)) { PrintMatrix(matrix); Console.WriteLine($"won: {playerRow} {playerCol}"); return; } if (CheckForLoseWithRunningLeft(matrix, playerRow, playerCol)) { PrintMatrix(matrix); Console.WriteLine($"dead: {playerRow} {playerCol}"); return; } MoveLeft(matrix, playerRow, playerCol); playerCol--; } else if (command == 'R') { SpreadBunnies(matrix); if (CheckForLoseWithBunny(matrix)) { PrintMatrix(matrix); Console.WriteLine($"dead: {playerRow} {playerCol}"); return; } if (CheckWinRight(matrix, playerRow, playerCol)) { PrintMatrix(matrix); Console.WriteLine($"won: {playerRow} {playerCol}"); return; } if (CheckForLoseWithRunningRight(matrix, playerRow, playerCol)) { PrintMatrix(matrix); Console.WriteLine($"dead: {playerRow} {playerCol}"); return; } MoveRight(matrix, playerRow, playerCol); playerCol++; } } } private static void PrintMatrix(char[,] matrix) { for (int i = 0; i < matrix.GetLength(0); i++) { for (int j = 0; j < matrix.GetLength(1); j++) { Console.Write(matrix[i,j]); } Console.WriteLine(); } } private static void MoveRight(char[,] matrix, int playerRow, int playerCol) { matrix[playerRow, playerCol] = '.'; matrix[playerRow + 1, playerCol] = 'P'; } private static bool CheckForLoseWithRunningRight(char[,] matrix, int playerRow, int playerCol) { return matrix[playerRow, playerCol + 1] == 'B'; } private static bool CheckWinRight(char[,] matrix, int playerRow, int playerCol) { return playerCol + 1 < 0; } private static void MoveLeft(char[,] matrix, int playerRow, int playerCol) { matrix[playerRow, playerCol] = '.'; matrix[playerRow - 1, playerCol] = 'P'; } private static bool CheckForLoseWithRunningLeft(char[,] matrix, int playerRow, int playerCol) { return matrix[playerRow, playerCol - 1] == 'B'; } private static bool CheckWinLeft(char[,] matrix, int playerRow, int playerCol) { return playerCol - 1 < 0; } private static void MoveDown(char[,] matrix, int playerRow, int playerCol) { matrix[playerRow, playerCol] = '.'; matrix[playerRow + 1, playerCol] = 'P'; } private static bool CheckForLoseWithRunningDown(char[,] matrix, int playerRow, int playerCol) { return matrix[playerRow + 1, playerCol] == 'B'; } private static bool CheckWinDown(char[,] matrix, int playerRow, int playerCol) { return playerRow + 1 >= matrix.GetLength(0); } private static void MoveUp(char[,] matrix, int playerRow, int playerCol) { matrix[playerRow, playerCol] = '.'; matrix[playerRow - 1, playerCol] = 'P'; } private static bool CheckForLoseWithRunningUp(char[,] matrix, int playerRow, int playerCol) { return matrix[playerRow - 1, playerCol] == 'B'; } private static bool CheckWinUp(char[,] matrix, int playerRow, int playerCol) { return playerRow - 1 < 0; } private static bool CheckForLoseWithBunny(char[,] matrix) { foreach (var item in matrix) { if (item == 'P') { return false; } } return true; } private static void SpreadBunnies(char[,] matrix) { var matrixCopy = new char[matrix.GetLength(0),matrix.GetLength(1)]; for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { matrixCopy[row, col] = matrix[row, col]; } } for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { var element = matrix[row, col]; if (element == 'B') { if (row - 1 >= 0) { matrixCopy[row - 1, col] = 'B'; } if (row + 1 < matrix.GetLength(0)) { matrixCopy[row + 1, col] = 'B'; } if (col - 1 >= 0) { matrixCopy[row, col - 1] = 'B'; } if (col + 1 < matrix.GetLength(1)) { matrixCopy[row, col + 1] = 'B'; } } } } } } }
namespace QStore.Core { using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using QStore.Core.Interfaces; [DataContract] [Serializable] public class QMap<TKey, TValue> : ISequenceMap<TKey, TValue> { [DataMember(Order = 1)] protected internal QIndexedSet<TKey> IndexedSet; [DataMember(Order = 2)] public TValue[] Values { get; protected set; } public int Count { get { return this.IndexedSet.Count; } } public IComparer<TKey> Comparer { get { return this.IndexedSet.Comparer; } } public TValue this[IEnumerable<TKey> sequence] { get { int index = this.GetIndex(sequence); if (index < 0) { throw new KeyNotFoundException(); } return this.Values[index]; } set { int index = this.GetIndex(sequence); if (index < 0) { throw new KeyNotFoundException(); } this.Values[index] = value; } } public static QMap<TKey, TValue> Create(IEnumerable<IEnumerable<TKey>> keySequences, IComparer<TKey> comparer) { if (keySequences == null) { throw new ArgumentNullException("keySequences"); } if (comparer == null) { throw new ArgumentNullException("comparer"); } var indexedSet = QIndexedSet<TKey>.Create(keySequences, comparer); return new QMap<TKey, TValue> { IndexedSet = indexedSet, Values = new TValue[indexedSet.Count] }; } public bool Contains(IEnumerable<TKey> sequence) { return this.IndexedSet.Contains(sequence); } public IEnumerable<TKey[]> Enumerate() { return this.IndexedSet.Enumerate(); } public IEnumerable<TKey[]> EnumerateByPrefix(IEnumerable<TKey> prefix) { return this.IndexedSet.EnumerateByPrefix(prefix); } public IEnumerable<KeyValuePair<TKey[], int>> EnumerateByPrefixWithIndex(IEnumerable<TKey> prefix) { return this.IndexedSet.EnumerateByPrefixWithIndex(prefix); } public IEnumerable<KeyValuePair<TKey[], TValue>> EnumerateByPrefixWithValue(IEnumerable<TKey> prefix) { return this.EnumerateByPrefixWithIndex(prefix) .Select(p => new KeyValuePair<TKey[], TValue>(p.Key, this.Values[p.Value])); } public IEnumerable<KeyValuePair<TKey[], int>> EnumerateWithIndex() { return this.IndexedSet.EnumerateWithIndex(); } public IEnumerable<KeyValuePair<TKey[], TValue>> EnumerateWithValue() { return this.Enumerate().Select((key, i) => new KeyValuePair<TKey[], TValue>(key, this.Values[i])); } public TKey[] GetByIndex(int index) { return this.IndexedSet.GetByIndex(index); } public KeyValuePair<TKey[], TValue> GetByIndexWithValue(int index) { return new KeyValuePair<TKey[], TValue>(this.IndexedSet.GetByIndex(index), this.Values[index]); } public int GetIndex(IEnumerable<TKey> sequence) { return this.IndexedSet.GetIndex(sequence); } public TKey[] GetKeyByIndex(int index) { return this.IndexedSet.GetByIndex(index); } public void SetComparer(IComparer<TKey> comparer) { this.IndexedSet.SetComparer(comparer); } public bool TryGetValue(IEnumerable<TKey> key, out TValue value) { int index = this.GetIndex(key); if (index < 0) { value = default(TValue); return false; } value = this.Values[index]; return true; } } }
namespace NHibernate.DependencyInjection.Core { public class DefaultEntityInjector : IEntityInjector { public object[] GetConstructorParameters(System.Type type) { return null; } } }
using System; namespace _7_Static_Constructor { class SampleClass { public static int staticValue = 5; public int value = 1; static SampleClass() { Console.WriteLine("Static constructor is called."); } public SampleClass() { Console.WriteLine("Instance constructor is called."); } } class Program { static void Main(string[] args) { SampleClass obj1 = new SampleClass(); SampleClass obj2 = new SampleClass(); Console.WriteLine(SampleClass.staticValue); Console.WriteLine(obj1.value); } } }
using KeepTeamAutotests.Pages; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; using System; using System.Collections.Generic; using System.Drawing.Imaging; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace KeepTeamAutotests.AppLogic { public class AppManager { private string ImageStorage = "..\\img\\FireFox\\33.03\\"; public AppManager(ICapabilities capabilities, string baseUrl, string hubUrl) { Pages = new PageManager(capabilities, baseUrl, hubUrl); userHelper = new UserHelper(this); employeeHelper = new EmployeeHelper(this); timeoffHelper = new TimeOffHelper(this); imageHelper = new ImageHelper(this); screenHelper = new ScreenHelper(this); assetHelper = new AssetHelper(this); filterHelper = new FilterHelper(this); hiringHelper = new HiringHelper(this); emailHeper = new EmailHelper(this); kpiHelper = new KPIHelper(this); hintHelper = new HintHelper(this); commentHelper = new CommentHelper(this); } public UserHelper userHelper { get; set; } public CommentHelper commentHelper { get; set; } public EmployeeHelper employeeHelper {get; set; } public TimeOffHelper timeoffHelper {get; set; } public ImageHelper imageHelper{get; set;} public ScreenHelper screenHelper { get; set; } public AssetHelper assetHelper { get; set; } public FileHelper fileHelper { get; set; } public FilterHelper filterHelper { get; set; } public HiringHelper hiringHelper { get; set; } public EmailHelper emailHeper { get; set; } public KPIHelper kpiHelper { get; set; } public HintHelper hintHelper { get; set; } public PageManager Pages { get; set; } /* public void TakeScreenshot(string saveLocation) { ITakesScreenshot screenshotDriver = driver as ITakesScreenshot; Screenshot screenshot = screenshotDriver.GetScreenshot(); screenshot.SaveAsFile(saveLocation, ImageFormat.Png); } public void TakeScreenshot(IWebElement element, string saveLocation) { ITakesScreenshot screenshotDriver = driver as ITakesScreenshot; Screenshot screenshot = screenshotDriver.GetScreenshot(); screenshot.SaveAsFile(saveLocation, ImageFormat.Png); } */ public string getImageStorage() { return ImageStorage; } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Extensions; //using ProjectCompany.Person; //using ProjectCompany.Activity; using MySql.Data.EntityFrameworkCore.Extensions; using ProjectCompany.Models; namespace ProjectCompany { public class ApplicationContext : DbContext { public DbSet<Employee> employees {get; set;} public DbSet<Skill> skills { get; set; } public DbSet<Contribution> contributions { get; set; } public DbSet<Project> projects { get; set; } public DbSet<EmployeeSkill> employees_skills { get; set; } public ApplicationContext(DbContextOptions<ApplicationContext> options):base(options) {} protected override void OnModelCreating(ModelBuilder modelBuilder) { this.OnContributionAndProjectModelCreating(modelBuilder); this.OnEmployeeSkillCreating(modelBuilder); this.OnContributionSkillModelCreating(modelBuilder); modelBuilder.Entity<Skill>() .HasIndex(s => s.Title) .IsUnique(); } protected void OnContributionAndProjectModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Contribution>() .HasOne<Project>(c => c.Project) .WithMany(p => p.Contributions) .HasForeignKey(c => c.ProjectId); modelBuilder.Entity<Contribution>() .OwnsOne( c => c.DatePeriod, dp => { dp.Property(p => p.From).HasColumnName("from_date"); dp.Property(p => p.To).HasColumnName("to_date"); } ); modelBuilder.Entity<Project>() .OwnsOne( p => p.DatePeriod, dp => { dp.Property(p => p.From).HasColumnName("from_date"); dp.Property(p => p.To).HasColumnName("to_date"); } ); modelBuilder.Entity<Contribution>() .HasOne<Employee>(c => c.Employee) .WithMany(e => e.Contributions) .HasForeignKey(c => c.EmployeeId); } protected void OnEmployeeSkillCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<EmployeeSkill>() .HasKey(t => new { t.EmployeeId, t.SkillId}); modelBuilder.Entity<EmployeeSkill>() .HasOne(es => es.Employee) .WithMany(e => e.EmployeeSkills) .HasForeignKey(es => es.EmployeeId); modelBuilder.Entity<EmployeeSkill>() .HasOne(es => es.Skill) .WithMany(s => s.EmployeeSkills) .HasForeignKey(es => es.SkillId); } protected void OnContributionSkillModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<ContributionSkill>() .HasKey(t => new { t.ContributionId, t.SkillId}); modelBuilder.Entity<ContributionSkill>() .HasOne(cs => cs.Contribution) .WithMany(c => c.ContributionSkills) .HasForeignKey(es => es.ContributionId); modelBuilder.Entity<ContributionSkill>() .HasOne(es => es.Skill) .WithMany(s => s.ContributionSkills) .HasForeignKey(es => es.SkillId); } } }
namespace ForumSystem.Web.ViewModels.Comments { using Ganss.XSS; public class EditCommentViewModel { public string Content { get; set; } public string SanitizeContent => new HtmlSanitizer() .Sanitize(this.Content); } }
using UnityEngine; public class CharacterMoveRight : CharacterAbility { protected override void PlayAbility(bool keyDown) { animator.walkingRight = keyDown; if (!keyDown) return; animator.faceLeft = false; transform.position += sheet.speed * Time.deltaTime * Vector3.right; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using Kuromori.InfoIO; using System.Diagnostics; using Kuromori.DataStructure; namespace Kuromori { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class CreateEBEvent : ContentPage { // User User; public CreateEBEvent(/*User user*/) { InitializeComponent(); } public void OnImportClick(object sender, EventArgs args) { Task.Run(async () => { EBEvent ev = await HttpUtils.GetEBEventData(EventID.Text); Device.BeginInvokeOnMainThread(() => { Title.Text = ev.NameText; }); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Genesys.WebServicesClient.Resources { public abstract class InteractionResource { public string id; public string state; public IList<string> capabilities; public IDictionary<string, object> userData; public IList<object> participants; } }
using System; using Autofac; using Framework.Core.Common; using Tests.Data.Oberon; using Tests.Pages.ActionID; using Tests.Pages.Oberon.Contact; using Tests.Pages.Oberon.Contribution; using Tests.Pages.Oberon.FinancialBatchManager; using Tests.Pages.Oberon.Pledge; using Tests.Pages.Oberon.Search; using NUnit.Framework; namespace Tests.Projects.Oberon.Pledge { public class VerifyManualPayDownOfContributionToPledgeToRaise : BaseTest { private Driver Driver { get { return Scope.Resolve<Driver>(); }} private ActionIdLogIn LogIn { get { return Scope.Resolve<ActionIdLogIn>(); } } #region TestClass /// <summary> /// Requirements: Tenant w/ FBM /// Test: 6380-2B /// Scenario: Manual Pay Down Pledge to Raise, Verify Manual Association of Contribution to Pledge /// Steps: 1. Create a contact. 2. Create 2 pledges. 3. Create a contribution. 4. Verify Contribution is applied to the correct Pledge /// </summary> [Test] [Category("oberon"), Category("oberon_smoketest"), Category("oberon_pledge"), Category("oberon_PRODUCTION")] public void VerifyManualPayDownOfContributionToPledgeToRaiseTest() { LogIn.LogInTenant(); const int pledge1Amt = 104; const string p1Period = "Primary"; const int pledge2Amt = 204; const string p2Period = "Special Primary"; const int contribAmt = 54; const string contribperiod = "Primary"; const string cycle = "2011"; const string pledgetype = "To Raise"; const int amtRemaining = pledge1Amt - contribAmt; // Create contact var fname = FakeData.RandomLetterString(7); var lname = FakeData.RandomLetterString(10); var contact1 = Scope.Resolve<ContactCreate>(); var contactOne = new TestContact { ContactType = ContactType.Individual, FirstName = fname, LastName = lname }; var contactId = contact1.CreateContact(contactOne); // create pledge 1 var contactDetails = Scope.Resolve<ContactDetail>(); contactDetails.ClickAddPledgeButton(); var createPledge = Scope.Resolve<PledgeCreate>(); createPledge.SelectPledgeAmountType(1); createPledge.SetPledgeAmount(pledge1Amt); createPledge.SetPledgeType(pledgetype); createPledge.SetPeriod(p1Period); createPledge.SetCycle(cycle); createPledge.ClickSectionTitleCreateButton(); var pledgeDetail = Scope.Resolve<PledgeDetail>(); var pledge1Id = pledgeDetail.GetPledgeId(); // create pledge 2 pledgeDetail.ClickAddPledgeButton(); //createPledge = new PledgeCreate(Driver); createPledge.SelectPledgeAmountType(1); createPledge.SetPledgeAmount(pledge2Amt); createPledge.SetPledgeType(pledgetype); createPledge.SetPeriod(p2Period); Assert.IsTrue(createPledge.Cycle.GetAttribute("value") == cycle);// verify that cycle is sticky createPledge.ClickSectionTitleCreateButton(); //pledgeDetail = new PledgeDetail(Driver); var pledge2Id = pledgeDetail.GetPledgeId(); // nav back to contact and create a contribution pledgeDetail.FindAContactAndClick(fname + " " + lname); //contactDetails = new ContactDetail(Driver); contactDetails.ClickAddContributionButton(); var createContrib = Scope.Resolve<ContributionCreate>(); createContrib.SetAmount(contribAmt.ToString()); createContrib.Period.SendKeys(contribperiod); createContrib.SetCycle(cycle); // link the pledge to the contribution createContrib.ClickManualFindPledgeLink(); var findPledgeDialog = Scope.Resolve<PledgeRelatedRecordsModal>(); findPledgeDialog.ClickSearch(); findPledgeDialog.SelectPledgeById(pledge1Id); findPledgeDialog.ClickSubmit(); // finish creating the contribution createContrib = Scope.Resolve<ContributionCreate>(); createContrib.ClickContributionCreateButton(); // get contribution ID var contribDetails = Scope.Resolve<ContributionDetail>(); var contrib1Id = contribDetails.GetContributionId(); // navigate to pledge list page contribDetails.ClickPledgeCountLink(); // verify on Pledge List View, all info is correct and contrib has been applied to pledge // Watin test verified pledge info in the list grid. Doing it on the details page for now. var pledgeList = Scope.Resolve<PledgeList>(); Assert.IsTrue(pledgeList.VerifyPledgeInList(pledge1Id)); Assert.IsTrue(pledgeList.VerifyPledgeInList(pledge2Id)); //Verify pledge 1 on Pledge Detail Page pledgeList.ClickAmountLinkById(pledge1Id); pledgeDetail = Scope.Resolve<PledgeDetail>(); Assert.IsTrue(pledge1Amt.ToString("C") == pledgeDetail.Amount.Text); // format int as currency Assert.IsTrue("Amount Remaining: " + amtRemaining.ToString("C") == pledgeDetail.AmountRemaining.Text); Assert.IsTrue("Total Contributions: " + contribAmt.ToString("C") == pledgeDetail.TotalContributions.Text); Assert.IsTrue(pledgeDetail.FullfillmentStatus.Text == "Active"); Assert.IsTrue(pledgeDetail.PledgeType.Text == "To Raise"); //Verify pledge 2 on Pledge Detail Page pledgeDetail.ClickPledgeCountLink(); //pledgeList = new PledgeList(Driver); pledgeList.ClickAmountLinkById(pledge2Id); //pledgeDetail = new PledgeDetail(Driver); Assert.IsTrue(pledge2Amt.ToString("C") == pledgeDetail.Amount.Text); Assert.IsTrue("Amount Remaining: " + pledge2Amt.ToString("C") == pledgeDetail.AmountRemaining.Text); Assert.IsTrue("Total Contributions: $0.00" == pledgeDetail.TotalContributions.Text); Assert.IsTrue(pledgeDetail.FullfillmentStatus.Text == "Active"); Assert.IsTrue(pledgeDetail.PledgeType.Text == "To Raise"); #region Test Cleanup //// delete contrib //contribDetails = new ContributionDetail(_driver); //contribDetails.GoToPage(contrib1Id); //contribDetails.ClickContributionDeleteLink(); //// delete pledges //pledgeDetail = new PledgeDetail(_driver); //pledgeDetail.GoToPage(pledge1Id); //pledgeDetail.ClickPledgeDeleteLink(); //pledgeDetail.GoToPage(pledge2Id); //pledgeDetail.ClickPledgeDeleteLink(); //// delete contact //pledgeDetail.ClickContactNameLink(); //contactDetails = new ContactDetail(_driver); //contactDetails.ClickDeleteLink(); #endregion } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraManager : MonoBehaviour { public Transform player; //Public variable to store a reference to the player game object private Vector3 offset; //Private variable to store the offset distance between the player and camera public float smoothSpeed; public float cameraZ = -5; public float cameraYOffset = 2f; public float smoothTime = 0.3f; public float waitTime; public float waitTimer; public bool lerp; private Vector3 velocity = Vector3.zero; public float offsetY; // Place camera this much above player pivot point public bool isFree; // For cinematic restrictions // MAKE SURE ONLY ONE GAME MANAGER EXISTS (SINGLETON) public static CameraManager cameraManager = null; private void Awake() { if (cameraManager == null)//Check if instance already exists { cameraManager = this;//if not, set instance to this DontDestroyOnLoad(gameObject); //Sets this to not be destroyed when reloading scene } else if (cameraManager != this)//If instance already exists and it's not this: { Destroy(gameObject);//Then destroy this. This enforces our singleton pattern, meaning there can only ever be one instance of a GameManager. } // https://blogs.unity3d.com/2015/06/19/pixel-perfect-2d/ // Orthographic size = ((Vert Resolution)/(PPUScale * PPU)) * 0.5 GetComponent<Camera>().orthographicSize = Screen.height / 32 * 0.25f; // 320 / 64 = 5 //player = GameManager.gameManager.player.transform; // Get player reference from game manager if (player == null) player = GameObject.FindWithTag("Player").transform; // SET INITIAL POSITION transform.position = new Vector3(player.position.x, cameraYOffset, cameraZ); } private void Update() { if (player == null) player = GameObject.FindWithTag("Player").transform; } public IEnumerator ChangeFloor() { lerp = true; isFree = false; yield return new WaitForSeconds(waitTime); isFree = true; StopAllCoroutines(); yield return null; } void LateUpdate() { if (isFree) { if (lerp) { //Vector3 targetPos = player.position + offset; Vector3 targetPos = new Vector3(player.position.x, player.position.y + cameraYOffset, cameraZ); Vector3 smoothedPos = Vector3.Lerp(transform.position, targetPos, smoothSpeed); // Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance. transform.position = new Vector3(smoothedPos.x, smoothedPos.y, cameraZ); // Restrict camera movement with Mathf.Clamp(smoothedPos.y, -1.3f, 1f) if (Mathf.Abs(transform.position.y - targetPos.y) < 0.001f) // Close enough (Otherwise will smooth forever) { transform.position = targetPos; // Jump to final position lerp = false; // Return to normal camera behaviour } } else { Vector3 targetPos = new Vector3(player.position.x, transform.position.y, cameraZ); transform.position = targetPos; } } /* //print("Camerapos: "+ transform.position); // = Camerapos: (-8.6, 2.5, -1.0) if (isFree) { //Vector3 targetPos = player.position + offset; Vector3 targetPos = new Vector3 (player.position.x,cameraY,cameraZ); Vector3 smoothedPos = Vector3.Lerp(transform.position, targetPos, smoothSpeed); // Set the position of the camera's transform to be the same as the player's, but offset by the calculated offset distance. //transform.position = new Vector3(smoothedPos.x,smoothedPos.y +offsetY, cameraZ); // Rerstrict camera movement with Mathf.Clamp(smoothedPos.y, -1.3f, 1f) transform.position = Vector3.SmoothDamp(transform.position, targetPos, ref velocity, smoothTime); // Rerstrict camera movement with Mathf.Clamp(smoothedPos.y, -1.3f, 1f) } */ } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CommandInvoker : MonoBehaviour { public Queue<ICommand> commands = new Queue<ICommand>(); public Stack<ICommand> myStack = new Stack<ICommand>(); void Start() { } // Update is called once per frame void Update() { } public void AddCommand(ICommand command) { commands.Enqueue(command); } public void ProcessAll() { // while() // { // Process() // } } public void Process() { //commands.Enqueue(); } public void Undo() { if (commands != null) { } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Btf.Data.Model.Log; namespace Btf.Services.LogService { public interface ILogService { void StartLog(string requestUrl); void EndLog(int responseCode); void Log(string logMsg, LogTypes logType); void LogError(string errorMsg, string stackTrace); Task<int> GetLogRequestCount(); Task<int> GetLogRequestCount(string filter); Task<List<LogRequest>> GetLogRequest(int pageIndex, int pageSize); Task<List<LogRequest>> GetLogRequestAsync(int pageIndex, int pageSize, string filter); Task<int> GetLogMessagesCount(int logRequestId); Task<List<LogMsg>> GetLogMessages(int logRequestId); } }
using Moq; using NumberConverter.API.Controllers; using NumberConverter.Services; using NUnit.Framework; namespace NumberConverter.Tests { [TestFixture] public class ConverterControllerTests { private ConverterController _converterController; private Mock<IConverterService> _converterService; [SetUp] public void Setup() { _converterService = new Mock<IConverterService>(); _converterController = new ConverterController(_converterService.Object); } [Test] public void GetWords_ReturnsWordsString() { const string WORDS = "FIVE HUNDRED DOLLARS"; const decimal NUMBER = 500; _converterService .Setup(x => x.NumberToWords(NUMBER)) .Returns(WORDS); var result = _converterController.Get(NUMBER); Assert.AreEqual(WORDS, result); _converterService.Verify(x => x.NumberToWords(It.IsAny<decimal>()), Times.Once); } } }
using Microsoft.AspNetCore.Mvc; using MongoDB.api.Data.Collections; using MongoDB.api.Model; using MongoDB.Driver; namespace MongoDB.api.Controllers { [ApiController] [Route("[controller]")] public class InfectadoController : ControllerBase { Data.MongoContext _mongoDB; IMongoCollection<Infectado> _infectadosCollection; public InfectadoController(Data.MongoContext mongoDB) { _mongoDB = mongoDB; _infectadosCollection = _mongoDB.DB.GetCollection<Infectado>(typeof(Infectado).Name.ToLower()); } /// <summary> /// Este serviço permite inserir uma pessoa infectada pelo vírus COVID-19 /// de acordo com seu sexo e localização. /// </summary> [HttpPost] [Route("insere")] public ActionResult SalvarInfectado([FromBody] InfectadoViewModel dto) { var infectado = new Infectado(dto.cpf, dto.Idade, dto.Sexo, dto.Latitude, dto.Longitude); _infectadosCollection.InsertOne(infectado); return StatusCode(201, "Infectado inserido com sucesso"); } /// <summary> /// Este serviço lista os dados registrados de todos os infectados. /// </summary> [HttpGet] [Route("lista")] public ActionResult ObterInfectados() { var infectados = _infectadosCollection.Find(Builders<Infectado>.Filter.Empty).ToList(); return Ok(infectados); } /// <summary> /// Este serviço busca um infectado resgitrado, pelo CPF, e lista seus dados. /// </summary> [HttpGet("{CPF}")] public ActionResult ObterInfectado(long CPF) { if(!FoundInfect(CPF)){ return NotFound("Infectado não encontrado na base de dados"); } var infectados = _infectadosCollection.Find(Builders<Infectado>.Filter.Where(_ => _.cpf == CPF)).ToList(); return Ok(infectados); } /// <summary> /// Este serviço atualiza os dados de um infectado regitrado, pelo CPF. /// </summary> [HttpPut] [Route("atualiza")] public ActionResult AtualizarInfectado([FromBody] InfectadoViewModel dto) { if(!FoundInfect(dto.cpf)){ return NotFound("Infectado não encontrado na base de dados"); } var infectado = new Infectado(dto.cpf, dto.Idade, dto.Sexo, dto.Latitude, dto.Longitude); _infectadosCollection.ReplaceOne(Builders<Infectado>.Filter.Where(_ => _.cpf == dto.cpf), infectado); return Ok("Atualizado com sucesso!"); } /// <summary> /// Este serviço deleta os dados de um CPF registrado como infectado. /// </summary> [HttpDelete("{CPF}")] public ActionResult DeletarInfectado(long CPF) { if(!FoundInfect(CPF)){ return NotFound("Infectado não encontrado na base de dados"); } _infectadosCollection.DeleteOne(Builders<Infectado>.Filter.Where(_ => _.cpf == CPF)); return Ok("Deletado com sucesso!"); } private bool FoundInfect(long CPF){ var infectados = _infectadosCollection.Find(Builders<Infectado>.Filter.Where(_ => _.cpf == CPF)).ToList(); if(infectados == null){ return false; } return true; } } }
using UnityEngine; using Random = UnityEngine.Random; public class ProtectBroke : MonoBehaviour { private Color _color; private Vector3[] _direction; private GameObject _particle_GameObject; // Use this for initialization void Start () { GameObject protect_Broke_Mobel = (GameObject)StaticParameter.LoadObject("Other", "ProtectParticle"); _particle_GameObject = Instantiate(protect_Broke_Mobel); _particle_GameObject.transform.position = HumanManager.Nature.Human_Mesh.bounds.center; _color = Color.white*0.3f; _direction = new Vector3[transform.childCount]; for (int i = 0; i < transform.childCount; i++) { transform.GetChild(i).GetComponent<MeshFilter>().mesh.RecalculateNormals(); _direction[i] = transform.GetChild(i).GetComponent<MeshFilter>().mesh.normals[0] * Random.Range(0.3f, 0.8f); } } // Update is called once per frame void Update () { _color -= Color.white * 0.01f; for (int i = 0; i < transform.childCount; i++) { transform.GetChild(i).Translate(_direction[i]); transform.GetChild(i).GetComponent<Renderer>().material.SetColor("_TintColor", _color); } if (_color.a < 0) { Destroy(gameObject); Destroy(_particle_GameObject); StaticParameter.ClearReference(ref _particle_GameObject); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using TweetSharp; namespace LwTwitterClient { /// <summary> /// Логика взаимодействия для AuthenticationWindow.xaml /// </summary> public partial class AuthenticationWindow : Window { TwitterService service; OAuthRequestToken requestToken; public AuthenticationWindow() { InitializeComponent(); } public AuthenticationWindow(TwitterService service, OAuthRequestToken requestToken) { InitializeComponent(); this.service = service; this.requestToken = requestToken; } private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { OAuthAccessToken access = service.GetAccessToken(requestToken, TokenInput.Text); service.AuthenticateWith(access.Token, access.TokenSecret); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TinhLuongINFO { public class Credential { private string groupID; private string rightID; public string GroupID { get { return groupID; } set { groupID = value; } } public string RightID { get { return rightID; } set { rightID = value; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class FloorUI : MonoBehaviour { #region Singleton to change the camera view public static FloorUI instance = null; public int floor; private void Awake() { if (instance == null) { instance = this; } else if (instance != this) { Destroy(gameObject); } } #endregion [SerializeField] public GameObject[] floorTxt; public int indexer = 0; public void firstFloor() { floorTxt[0].SetActive(true); floorTxt[1].SetActive(false); floorTxt[2].SetActive(false); floor = 1; } public void secondFloor() { floorTxt[0].SetActive(false); floorTxt[1].SetActive(true); floorTxt[2].SetActive(false); floor = 2; } public void thirdFloor() { floorTxt[0].SetActive(false); floorTxt[1].SetActive(false); floorTxt[2].SetActive(true); floor = 3; } public void clickNext() { if (indexer >= 3) { indexer = default; floorsystem.instance.changecamera(indexer); } else { indexer++; floorsystem.instance.changecamera(); } } public void clickPrev() { if (indexer == 0) { indexer = 2; floorsystem.instance.changecamera(indexer); } else { indexer--; floorsystem.instance.changecamera(); } } void Update() { switch (indexer) { case 1: { secondFloor(); } break; case 2: { thirdFloor(); } break; default: { firstFloor(); } break; } } }
using System.Configuration; namespace ServiceHost { /// <summary> /// Configuration section for self-hosted WCF services. /// </summary> public class ServicesConfigurationSection : ConfigurationSection { #region Constructors /// <summary> /// Creates a new instance of ServicesConfigurationSection. /// </summary> public ServicesConfigurationSection() { } #endregion #region Public Properties [ConfigurationProperty("services", IsDefaultCollection = false)] [ConfigurationCollection(typeof(ServiceElementCollection), AddItemName = "add", ClearItemsName = "clear", RemoveItemName = "remove")] public ServiceElementCollection Services { get { ServiceElementCollection servicesCollection = (ServiceElementCollection)base["services"]; return servicesCollection; } } #endregion } }
using System; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Server; using OnlineClinic.Core.Services; public class CustomAuthStateProvider : ServerAuthenticationStateProvider, IHostEnvironmentAuthenticationStateProvider { private readonly IUserService _userService; public CustomAuthStateProvider(IUserService userService) { _userService = userService; } public bool Authenticate(string username, string password, bool AdminUser = false) { var isValid = _userService.Authenticate(username, password, AdminUser); if(isValid) { var identity = new ClaimsIdentity(new[] { new Claim("Username", username), new Claim("Role", AdminUser? "Administrator" : "Doctor"), new Claim(ClaimTypes.Role, AdminUser? "Administrator" : "Doctor"), new Claim(ClaimTypes.NameIdentifier, AdminUser? "Administrator" : username) }, "Web", username, AdminUser? "Administrator" : "Doctor"); var authenticationState = new AuthenticationState(new ClaimsPrincipal(identity)); SetAuthenticationState(Task.FromResult<AuthenticationState>(authenticationState)); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); return true; } return false; } public void Logout() { var authenticationState = new AuthenticationState(new ClaimsPrincipal()); SetAuthenticationState(Task.FromResult<AuthenticationState>(authenticationState)); NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Notas.Dominio.Entities { public class Naturezas { public int NaturezasId { get; set; } public int Codigo { get; set; } public string Descricao { get; set; } public string Doi { get; set; } public string Censec { get; set; } public int Cep { get; set; } public string Tipo { get; set; } } }
using System; /*Write a program that compares two char arrays lexicographically (letter by letter).*/ class Program { static void Main() { Console.Write("length = "); int length = int.Parse(Console.ReadLine()); char[] arr1 = new char[length]; char[] arr2 = new char[length]; for (int i = 0; i < length; i++) { Console.Write("arr1[{0}] = ", i); arr1[i] = char.Parse(Console.ReadLine()); } for (int i = 0; i < length; i++) { Console.Write("arr2[{0}] = ", i); arr2[i] = char.Parse(Console.ReadLine()); } for (int i = 0; i < length; i++) if (arr1[i] > arr2[i]) Console.WriteLine("{0} > {1}", arr1[i], arr2[i]); else if (arr1[i] == arr2[i]) Console.WriteLine("{0} = {1}", arr1[i], arr2[i]); else Console.WriteLine("{0} < {1}", arr1[i], arr2[i]); } }
 /* ****************************************************************************** * @file : Program.cs * @Copyright: ViewTool * @Revision : ver 1.0 * @Date : 2015/02/13 10:44 * @brief : Program demo ****************************************************************************** * @attention * * Copyright 2009-2015, ViewTool * http://www.viewtool.com/ * All Rights Reserved * ****************************************************************************** */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using Ginkgo; namespace ControlGPIO_Test { class Program { static void Main(string[] args) { int ret; // Scan connected device ret = ControlGPIO.VGI_ScanDevice(1); if (ret <= 0) { Console.WriteLine("No device connect!"); return; } // Open device ret = ControlGPIO.VGI_OpenDevice(ControlGPIO.VGI_USBGPIO, 0, 0); if (ret != ControlGPIO.ERROR.SUCCESS) { Console.WriteLine("Open device error!"); return; } // Set GPIO_7 and GPIO_8 to output ret = ControlGPIO.VGI_SetOutput(ControlGPIO.VGI_USBGPIO, 0, ControlGPIO.GPIO_MASK.VGI_GPIO_PIN7 | ControlGPIO.GPIO_MASK.VGI_GPIO_PIN8); if (ret != ControlGPIO.ERROR.SUCCESS) { Console.WriteLine("Set pin output error!"); return; } // Set GPIO_7 and GPIO_8 to high level ret = ControlGPIO.VGI_SetOutput(ControlGPIO.VGI_USBGPIO, 0, ControlGPIO.GPIO_MASK.VGI_GPIO_PIN7 | ControlGPIO.GPIO_MASK.VGI_GPIO_PIN8); if (ret != ControlGPIO.ERROR.SUCCESS) { Console.WriteLine("Set pin high error!"); return; } // Set GPIO_7 and GPIO_8 to low level ret = ControlGPIO.VGI_ResetPins(ControlGPIO.VGI_USBGPIO, 0, ControlGPIO.GPIO_MASK.VGI_GPIO_PIN7 | ControlGPIO.GPIO_MASK.VGI_GPIO_PIN8); if (ret != ControlGPIO.ERROR.SUCCESS) { Console.WriteLine("Set pin low error!"); return; } // Set GPIO_4 and GPIO_5 to input ret = ControlGPIO.VGI_SetInput(ControlGPIO.VGI_USBGPIO, 0, ControlGPIO.GPIO_MASK.VGI_GPIO_PIN4 | ControlGPIO.GPIO_MASK.VGI_GPIO_PIN5); if (ret != ControlGPIO.ERROR.SUCCESS) { Console.WriteLine("Set pin input error!"); return; } // Get GPIO_4 and GPIO_5 value UInt16 pin_value = 0; ret = ControlGPIO.VGI_ReadDatas(ControlGPIO.VGI_USBGPIO, 0, ControlGPIO.GPIO_MASK.VGI_GPIO_PIN4 | ControlGPIO.GPIO_MASK.VGI_GPIO_PIN5, ref pin_value); if (ret != ControlGPIO.ERROR.SUCCESS) { Console.WriteLine("Get pin data error!"); return; } else { if ((pin_value & ControlGPIO.GPIO_MASK.VGI_GPIO_PIN4) != 0) { Console.WriteLine("GPIO_4 is high-level!"); } else { Console.WriteLine("GPIO_4 is low-level!"); } if ((pin_value & ControlGPIO.GPIO_MASK.VGI_GPIO_PIN5) != 0) { Console.WriteLine("GPIO_5 is high-level!"); } else { Console.WriteLine("GPIO_5 is low-level!"); } } // Set GPIO_4 and GPIO_5 to OD(Bi-directional, need pull-up resistor) ret = ControlGPIO.VGI_SetOpenDrain(ControlGPIO.VGI_USBGPIO, 0, ControlGPIO.GPIO_MASK.VGI_GPIO_PIN4 | ControlGPIO.GPIO_MASK.VGI_GPIO_PIN5); if (ret != ControlGPIO.ERROR.SUCCESS) { Console.WriteLine("Set pin input error!"); return; } // Set GPIO_4 and GPIO_5 to high level ret = ControlGPIO.VGI_SetOutput(ControlGPIO.VGI_USBGPIO, 0, ControlGPIO.GPIO_MASK.VGI_GPIO_PIN4 | ControlGPIO.GPIO_MASK.VGI_GPIO_PIN5); if (ret != ControlGPIO.ERROR.SUCCESS) { Console.WriteLine("Set pin high error!"); return; } // Set GPIO_4 and GPIO_5 to low level ret = ControlGPIO.VGI_ResetPins(ControlGPIO.VGI_USBGPIO, 0, ControlGPIO.GPIO_MASK.VGI_GPIO_PIN4 | ControlGPIO.GPIO_MASK.VGI_GPIO_PIN5); if (ret != ControlGPIO.ERROR.SUCCESS) { Console.WriteLine("Set pin high error!"); return; } // Get GPIO_4 and GPIO_5 value ret = ControlGPIO.VGI_ReadDatas(ControlGPIO.VGI_USBGPIO, 0, ControlGPIO.GPIO_MASK.VGI_GPIO_PIN4 | ControlGPIO.GPIO_MASK.VGI_GPIO_PIN5, ref pin_value); if (ret != ControlGPIO.ERROR.SUCCESS) { Console.WriteLine("Get pin data error!"); return; } else { if ((pin_value & ControlGPIO.GPIO_MASK.VGI_GPIO_PIN4) != 0) { Console.WriteLine("GPIO_4 is high-level!"); } else { Console.WriteLine("GPIO_4 is low-level!"); } if ((pin_value & ControlGPIO.GPIO_MASK.VGI_GPIO_PIN5) != 0) { Console.WriteLine("GPIO_5 is high-level!"); } else { Console.WriteLine("GPIO_5 is low-level!"); } } // Close device ret = ControlGPIO.VGI_CloseDevice(ControlGPIO.VGI_USBGPIO, 0); if (ret != ControlGPIO.ERROR.SUCCESS) { Console.WriteLine("Close device error!"); return; } } } }
using System; using System.Threading; using System.Threading.Tasks; using Ardalis.ApiEndpoints; using AutoMapper; using BlazorShared.Models.Schedule; using FrontDesk.Core.Aggregates; using Microsoft.AspNetCore.Mvc; using PluralsightDdd.SharedKernel.Interfaces; using Swashbuckle.AspNetCore.Annotations; namespace FrontDesk.Api.ScheduleEndpoints { public class Create : BaseAsyncEndpoint .WithRequest<CreateScheduleRequest> .WithResponse<CreateScheduleResponse> { private readonly IRepository _repository; private readonly IMapper _mapper; public Create(IRepository repository, IMapper mapper) { _repository = repository; _mapper = mapper; } [HttpPost("api/schedules")] [SwaggerOperation( Summary = "Creates a new Schedule", Description = "Creates a new Schedule", OperationId = "schedules.create", Tags = new[] { "ScheduleEndpoints" }) ] public override async Task<ActionResult<CreateScheduleResponse>> HandleAsync(CreateScheduleRequest request, CancellationToken cancellationToken) { var response = new CreateScheduleResponse(request.CorrelationId()); var toAdd = _mapper.Map<Schedule>(request); toAdd = await _repository.AddAsync<Schedule, Guid>(toAdd); var dto = _mapper.Map<ScheduleDto>(toAdd); response.Schedule = dto; return Ok(response); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Data.Entity; using BudgetApp.Domain.Abstract; using BudgetApp.Domain.Concrete; using BudgetApp.Domain.Entities; using BudgetApp.WebUI.ViewModels; using BudgetApp.Domain.DAL; namespace BudgetApp.WebUI.Controllers { public class CreditCardController : Controller { public ICardEntries CardList; public IResponsiblePartyEntries PartyList; public ICreditEntries CreditEntryList; public IPaymentPlanEntries PaymentPlanEntries; public UnitofWork unitOfWork; // Constant strings for CreditEntry field names private const string PURCHASEDATE = "entry-date"; private const string SCHEDULEDDATE = "scheduledate"; private const string DESCRIPTION = "entry-description"; private const string PURCHASEAMOUNT = "entry-amount"; private const string PAYAMOUNT = "amount-paid"; private const string CARD = "card-spinner"; public CreditCardController(ICardEntries Cards, IResponsiblePartyEntries Parties, ICreditEntries CreditEntries, IPaymentPlanEntries PaymentPlanEntries) { this.CardList = Cards; this.PartyList = Parties; this.CreditEntryList = CreditEntries; this.PaymentPlanEntries = PaymentPlanEntries; unitOfWork = new UnitofWork(); } public ActionResult List() { Dictionary<int, string> testDictionary = new Dictionary<int, string>(); testDictionary.Add(1, "brandon"); ViewBag.Cards = (from card in CardList.CreditCards.ToArray() select new SelectListItem { Text = card.Card, Value = card.Card }).ToArray(); ViewBag.Parties = (from party in PartyList.Parties.ToArray() orderby party.PartyName select new SelectListItem { Text = party.PartyName, Value = party.PartyName }).ToList(); ViewBag.PaymentPlans = AggregatePaymentPlans(); return View("CreditView", CreditEntryList.CreditEntries.Include(c=>c.Card).Include(c=>c.ResponsibleParty)); } /** * Action method for updating PaymentPlan Partial View * */ public ActionResult UpdatePaymentPlans() { PaymentPlanViewModel plans = AggregatePaymentPlans(); return PartialView("AggregatePaymentPlans", plans); } /** * Action method for updating PaymentPlanViewModel * */ public PaymentPlanViewModel AggregatePaymentPlans() { // Create ViewModel object and set the Parties property PaymentPlanViewModel PaymentPlans = new PaymentPlanViewModel(); PaymentPlans.Parties = PartyList.Parties.ToList(); // Sort PaymentPlanEntries by ascending date // Also eagerly load the PaymentPlanEntries and PaymentPlanCharges IQueryable<PaymentPlanEntry> payments = PaymentPlanEntries.PaymentPlanEntries .OrderBy(p => p.PaymentDate) .Include(x => x.Charges) .Include(p => p.ResponsibleParty); // Cycle through PaymentPlanEntries to populate PaymentPlanViewModel foreach (PaymentPlanEntry entry in payments) { IDictionary<string, decimal> AmtPerParty = new Dictionary<string, decimal>(); IEnumerable<PartyEntry> parties = entry.Charges .Select(c => c.CreditEntry.ResponsibleParty); if (PaymentPlans.plans.ContainsKey(entry.PaymentDate)) { var Amt = PaymentPlans.plans[entry.PaymentDate]; //Calculate PaymentPlanTotal from linked Charges var total = entry.Charges.Sum(t => t.CreditEntry.AmountPaid); Amt[entry.ResponsibleParty.PartyName] = total; //entry.PaymentTotal; } else { foreach (string party in parties.Select(p=>p.PartyName)) { var total = entry.Charges .Where(c => c.CreditEntry.ResponsibleParty.PartyName == party) .Sum(t => t.CreditEntry.AmountPaid); AmtPerParty[party] = total; } PaymentPlans.plans.Add(entry.PaymentDate, AmtPerParty); } } return PaymentPlans; } public ActionResult Edit(int? EntryID) { CreditEntry Entry; // If EntryID is null, we are adding if (EntryID == null) { Entry = new CreditEntry(); ViewBag.Action = true; } else { Entry = (CreditEntry)CreditEntryList.CreditEntries .Where(m => m.CreditEntryId == EntryID) .First(); ViewBag.Action = false; } ViewBag.Cards = CardList.CreditCards; return View(Entry); } [HttpPost] public ActionResult Edit(CreditEntry Entry, bool add) { //string card = unitOfWork.CardRepo.CreditCards.Where(c => c.Card == Request.Params.Get("Card")); string card = Request.Params.Get("Card"); CardEntry cardEntry = unitOfWork.CardRepo.CreditCards .Where(c => c.Card == card) .FirstOrDefault(); Entry.Card = cardEntry; string party = Request.Params.Get("ResponsibleParty"); PartyEntry partyEntry = unitOfWork.PartyRepo.Parties .Where(p => p.PartyName == party) .FirstOrDefault(); Entry.ResponsibleParty = partyEntry; ModelState.SetModelValue("Card", new ValueProviderResult(cardEntry, card, System.Globalization.CultureInfo.InvariantCulture)); if (ModelState.IsValid) { Entry.AmountRemaining = Entry.PurchaseTotal - Entry.AmountPaid; if (add) unitOfWork.CreditRepo.Add(Entry); else unitOfWork.CreditRepo.Edit(Entry); unitOfWork.Save(); return RedirectToAction("List"); } else { return View(); } } public ActionResult Delete(CreditEntry Entry) { unitOfWork.CreditRepo.Delete(Entry); unitOfWork.Save(); return RedirectToAction("List"); } /** * Update a chosen Credit Entry field * * id id of the credit entry to be modified * value updated value */ public string UpdateField(string id, string value) { int EntryId = Convert.ToInt32(id.Substring(id.LastIndexOf('-')+1)); id = id.Substring(0, id.LastIndexOf('-')); CreditEntry nakedEntry = (CreditEntry)unitOfWork.CreditRepo.CreditEntries .Where(c => c.CreditEntryId == EntryId) .Include( c => c.Card) .Include( c => c.ResponsibleParty) .First(); CreditEntryWrapper wrappedEntry = new CreditEntryWrapper(nakedEntry, unitOfWork, CardList.CreditCards, PartyList.Parties); wrappedEntry.UpdateField(id, value); return value; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Obstacle : MonoBehaviour { public void Disjoint() { Rigidbody rb = GetComponent<Rigidbody>(); rb.isKinematic = false;//Physic enable GetComponent<Collider>().enabled = false; Vector3 forcePositon = transform.parent.position; float distance = forcePositon.x - GetComponent<MeshRenderer>().bounds.center.x; Vector3 dir = (distance < 0 ? Vector3.right : Vector3.left) + Vector3.up * 1.5f; float force = Random.Range(20, 35); float torque = Random.Range(110, 180); rb.AddForceAtPosition(dir.normalized * force, forcePositon, ForceMode.Impulse); rb.AddTorque(Vector3.left * torque); rb.velocity = Vector3.down; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace uri { class house { protected double area; protected door Door=new door(); public house(double area) { this.area = area; } public double Area { get { return this.area; } set { this.area = value; } } public door d1 { get { return this.Door; } set { this.Door = value; } } public void showdata() { Console.WriteLine("I am a house, my area is"+Area+" m2"); } } class door { private string color; public string Color { get { return this.color; } set { this.color = value; } } public void showdata() { Console.WriteLine("I am a door, my color is " + color); } } class SmallApartment : house { public SmallApartment(double area) : base(area) { } } class person { private string name; private house hname; public person(string name, house hname) { this.name = name; this.hname = hname; } public string Name { get { return this.name; } set { this.name = value; } } public house Hname { get { return this.hname; } set { this.hname = value; } } public void showdata() { Console.WriteLine("Owner Name:"+name); hname.showdata(); hname.d1.showdata(); } } class Program { static void Main(string[] args) { SmallApartment s = new SmallApartment(50); s.d1.Color = "brown"; person p = new person("Anik",s); p.showdata(); Console.ReadKey(); } } }
using Cs_Gerencial.Aplicacao.ServicosApp; using Cs_Gerencial.Dominio.Entities; using Cs_Gerencial.Dominio.Interfaces.Repositorios; using Cs_Gerencial.Dominio.Interfaces.Servicos; using Cs_Gerencial.Dominio.Servicos; using Moq; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Cs_Gerecial.Testes.ServicosTestes { public class TesteServicoSeries { [Fact] public void ServicoSeries_ConsultarPorIdCompraSelo_True() { //Arrange var repositorio = new Mock<IRepositorioSeries>(); var listaSeries = new List<Series>(); var serie = new Series(); for (int i = 0; i < 100; i++) { serie = new Series() { SerieId = i, IdCompra = i, }; if (i == 50) { serie.Inicial = 10000; serie.Final = 10020; serie.Letra = "ABCD"; serie.Quantidade = 20; } listaSeries.Add(serie); } repositorio.Setup(p => p.ConsultarPorIdCompraSelo(50)).Returns(listaSeries.Where(p => p.IdCompra == 50)); var servicoSeries = new ServicoSeries(repositorio.Object); //Act var retorno = servicoSeries.ConsultarPorIdCompraSelo(50); //Assert Assert.True(retorno.FirstOrDefault().Quantidade == 20); } } }
namespace Sentry.Internal.JsonConverters; /// <summary> /// A converter that removes dangerous classes from being serialized, /// and, also formats some classes like Exception and Type. /// </summary> internal class SentryJsonConverter : JsonConverter<object?> { public override bool CanConvert(Type typeToConvert) => typeof(Type).IsAssignableFrom(typeToConvert) || typeToConvert.FullName?.StartsWith("System.Reflection") == true; public override object? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => default; public override void Write(Utf8JsonWriter writer, object? value, JsonSerializerOptions options) { if (value is Type type && type.FullName != null) { writer.WriteStringValue(type.FullName); } else { writer.WriteNullValue(); } } }
using System; namespace DocumentsApproval.Commands { public abstract class BaseCommand { public Guid StreamId { get; set; } } }
using UnityEngine; using System.Collections; using System; public class CarJump : MonoBehaviour { public float jumpForce; public Rigidbody2D frontWheel, rearWheel; public string jumpButton, flipButton, horizontalAxis; public bool facingRight = true; // For determining which way the car is currently facing. private Rigidbody2D rigidBody; private LayerMask layerMask; private int jumpState; private float torqueDir; // to detect whether torque is being applied private float distanceToGround; // int groundLayer = 18; // Debug.Log(LayerMask.NameToLayer("Ground")); private float timeUpsideDown = 0f; // Use this for initialization void Start() { rigidBody = GetComponent<Rigidbody2D>(); layerMask = LayerMask.GetMask(new string[] { "Ground" }); jumpState = 0; distanceToGround = 1.0f; // idealmente iríamos buscar isto tipo collider.bounds.extents.y; mas parece que não há para 2d // Flip(); } public bool wheelsGrounded() // mudar para wheels -> istouching ou parecido { /* CircleCollider2D rearWheelCollider = rearWheel.GetComponentInChildren<CircleCollider2D>(); CircleCollider2D frontWheelCollider = frontWheel.GetComponentInChildren<CircleCollider2D>(); if (rearWheelCollider.IsTouchingLayers(groundLayer)) print("rear wheel touching Ground layer"); if (frontWheelCollider.IsTouchingLayers(groundLayer)) print("front wheel touching Ground layer"); print("rear wheel collider: " + rearWheelCollider.ToString()); print("front wheel collider: " + frontWheelCollider.ToString()); return rearWheelCollider.IsTouchingLayers(groundLayer) && rearWheelCollider.IsTouchingLayers(groundLayer); */ RaycastHit2D rayHitsFront = Physics2D.Raycast(frontWheel.position, -Vector2.up, distanceToGround + 0.1f, layerMask); RaycastHit2D rayHitsRear = Physics2D.Raycast(rearWheel.position, -Vector2.up, distanceToGround + 0.1f, layerMask); return (rayHitsFront.collider != null) && (rayHitsRear.collider != null); } void OnCollisionStay2D(Collision2D col) { print(col.gameObject.name); print(col.gameObject.tag); if (col.gameObject.tag == "Ground") { timeUpsideDown += Time.deltaTime; print("timeUpsideDown: " + timeUpsideDown); if (timeUpsideDown > 2) { jumpFlip(); timeUpsideDown = 0f; } } } public bool carUpsideDownGrounded() // mudar para wheels -> istouching ou parecido { RaycastHit2D rayHitsTop = Physics2D.Raycast(rigidBody.position, -Vector2.up, distanceToGround + 0.5f, layerMask); return rayHitsTop.collider != null; } // Update is called once per frame void FixedUpdate() { if (wheelsGrounded()) jumpState = 0; torqueDir = Input.GetAxis(horizontalAxis); if (!facingRight) torqueDir *= -1; if (jumpState < 2) { if (Input.GetKeyDown(jumpButton)) { if (carUpsideDownGrounded()) jumpFlip(); if (torqueDir > 0) jumpFront(); else if (torqueDir < 0) jumpBack(); else jumpCenter(); } } if (Input.GetKeyDown(flipButton)) Flip(); } private void Flip() { // Switch the way the car is labelled as facing. facingRight = !facingRight; if (facingRight) print("Car is now facing right"); if (!facingRight) print("Car is now facing left"); // Multiply the player's x local scale by -1. /* Vector3 theScale = transform.localScale; theScale.x *= -1; transform.localScale = theScale; */ Vector3 theScale = transform.localScale; // mudar para carro completo (incl. rodas) theScale.x *= -1.0f; transform.localScale = theScale; print(theScale); } private void jumpCenter() { rigidBody.AddForce(transform.up * jumpForce, ForceMode2D.Impulse); jumpState++; } private void jumpBack() { frontWheel.AddForce(transform.up * jumpForce, ForceMode2D.Impulse); rigidBody.AddForce(-transform.right * jumpForce * 0.2f, ForceMode2D.Impulse); jumpState++; } private void jumpFront() { rearWheel.AddForce(transform.up * jumpForce, ForceMode2D.Impulse); rigidBody.AddForce(transform.right * jumpForce * 0.2f, ForceMode2D.Impulse); jumpState++; } private void jumpFlip() { rigidBody.AddForce(-1.0f * transform.up * jumpForce, ForceMode2D.Impulse); } }
using System; class Diamand { static void Main() { int n = int.Parse(Console.ReadLine()); int rowCount = (n + 1) / 2 * 2 - 1; for (int row = 0; row < rowCount; row++) { int countOuterDash = Math.Abs((n - 1) / 2 - row); string outerDash = new string('-', countOuterDash); Console.Write(outerDash + "*"); if (row == 0 || row == rowCount - 1) { if (n % 2 == 0) { Console.Write("*"); } } else { int countInnerDash = n - 2 * countOuterDash - 2; string innerDash = new string('-', countInnerDash); Console.Write(innerDash + "*"); } Console.Write(outerDash); Console.WriteLine(); } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EntityFrameworkCodeFirstApp_JustConsoleApp_ { public class Category { public int CategoryId { get; set; } public string Name { get; set; } public string Description { get; set; } } public class MoviesContext:DbContext { public DbSet<Category> Categories { get; set; } public MoviesContext():base("MoviesConStr") { } } class Program { static void Main(string[] args) { MoviesContext db = new MoviesContext(); var category = new Category() { Description = "Desc 1", Name = "Category 1" }; db.Categories.Add(category); db.SaveChanges(); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Data.SqlClient; namespace AdoExam.Seller { /// <summary> /// Interaction logic for GoodList.xaml /// </summary> public partial class GoodList : Window { bool sell; public GoodList(bool sell) { InitializeComponent(); this.sell = sell; FullCreate(); } public void FullCreate() { DataSet ds = new DataSet(); SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Good", App.conStr); adapter.Fill(ds); dgGoods.ItemsSource = ds.Tables[0].DefaultView; } private void CheckBox_Checked(object sender, RoutedEventArgs e) { DataSet ds = new DataSet(); SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Good WHERE Quantity<10", App.conStr); adapter.Fill(ds); dgGoods.ItemsSource = ds.Tables[0].DefaultView; } private void CheckBox_Unchecked(object sender, RoutedEventArgs e) { FullCreate(); } private void dgGoods_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (sell) { } } } }
using Owin; using Visualisr.Infrastructure.Mapping; namespace Visualisr { public class Startup { public void Configuration(IAppBuilder app) { app.UseNancy(); app.UseAutoMapper(); } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Models.Login.Models { public class UserApplication { [Key] public int UserApplicationId { get; set; } [ForeignKey("Application")] public int ApplicationId { get; set; } public virtual Application Application { get; set; } public string UserId { get; set; } public string RefereeId { get; set; } [ForeignKey("UserReferral")] public Guid ReferralId { get; set; } public virtual UserReferral UserReferral{ get; set; } } }
using System; namespace OnDemand.ObjectModel.Models { public class PaymentHistory { public DateTime PayAt { get; set; } public decimal Amount { get; set; } public string Description { get; set; } } }
using Framework.Core.Common; using OpenQA.Selenium; namespace Tests.Pages.Drupal.Forms { public class EventForm : FormBase { #region Elements public new IWebElement ContributionOtherAmountElement { get { return _driver.FindElement(By.Id("edit-additionalcontributionvalue")); } } #endregion public EventForm(Driver driver) : base(driver) { } #region Methods public void EnterOtherContributionAmount() { ContributionOtherAmountElement.Click(); ContributionOtherAmountElement.SendKeys(ContributionOtherAmount); } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using momo.Handles; using Swashbuckle.AspNetCore.Swagger; using Microsoft.Extensions.Caching.Redis; using Microsoft.IdentityModel.Tokens; using momo.Middleware; using AutoMapper; namespace momo { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } //这就是一个容器,所有注册的依赖都注入到这里面 // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // 注册CORS服务 services.AddCors(options => { options.AddPolicy("any", builder => { builder.AllowAnyOrigin() //允许任何来源的主机访问 .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials();//指定处理cookie }); }); #region 授权服务 string issuer = Configuration["Jwt:Issuer"]; string audience = Configuration["Jwt:Audience"]; string expire = Configuration["Jwt:ExpireMinutes"]; TimeSpan expiration = TimeSpan.FromMinutes(Convert.ToDouble(expire)); SecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecurityKey"])); services.AddAuthorization(options => { //1、Definition authorization policy, 一旦标识了Permission,将挂起请求,直到认证授权通过 options.AddPolicy("Permission", policy => policy.Requirements.Add(new PolicyRequirement())); }).AddAuthentication(s => { //2、Authentication s.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; s.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; s.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(s => { //3、Use Jwt bearer s.TokenValidationParameters = new TokenValidationParameters { ValidIssuer = issuer, ValidAudience = audience, IssuerSigningKey = key, ClockSkew = expiration, ValidateLifetime = true }; s.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { //Token expired if (context.Exception.GetType() == typeof(SecurityTokenExpiredException)) { context.Response.Headers.Add("Token-Expired", "true"); } return Task.CompletedTask; } }; }); //DI handler process function services.AddSingleton<IAuthorizationHandler, PolicyHandler>(); #endregion services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddJsonFormatters(); services.AddSwaggerGen(s => { //Generate api description doc var provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>(); //swagger界面概要 foreach (var description in provider.ApiVersionDescriptions) { s.SwaggerDoc(description.GroupName, new Info { Contact = new Contact { Name = "zc", Email = "172610800@qq.com", Url = "https://yuiter.com" }, Description = "A front-background project build by ASP.NET Core 2.2 and Vue", Title = "momo", Version = description.ApiVersion.ToString(), License = new License { Name = "MIT", Url = "https://mit-license.org/" } }); } //Show the api version in url address s.DocInclusionPredicate((version, apiDescription) => { if (!version.Equals(apiDescription.GroupName)) return false; var values = apiDescription.RelativePath .Split('/') .Select(v => v.Replace("v{version}", apiDescription.GroupName)); apiDescription.RelativePath = string.Join("/", values); return true; }); //接口说明配置 //Add comments description var basePath = Path.GetDirectoryName(AppContext.BaseDirectory);//get application located directory var apiPath = Path.Combine(basePath, "momo.xml"); //var dtoPath = Path.Combine(basePath, "Grapefruit.Application.xml"); s.IncludeXmlComments(apiPath, true); //s.IncludeXmlComments(dtoPath, true); //Add Jwt Authorize to http header //配置 Swagger 从而使 Swagger 可以支持我们的权限验证方式。 s.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization",//Jwt default param name In = "header",//Jwt store address Type = "apiKey"//Security scheme type }); //Add authentication type s.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } } }); }); services.AddApiVersioning(o => { o.ReportApiVersions = true; //return versions in a response header o.DefaultApiVersion = new ApiVersion(1, 0);//default version select o.AssumeDefaultVersionWhenUnspecified = true; //if not specifying an api version,show the default version }) //添加api版本服务浏览 .AddVersionedApiExplorer(option => { option.GroupNameFormat = "'v'VVVV";//api group name option.AssumeDefaultVersionWhenUnspecified = true;//whether provide a service API version }); //采用反射的方式,批量的将程序集内的接口与其实现类进行注入。 string assemblies = Configuration["Assembly:FunctionAssembly"]; if (!string.IsNullOrEmpty(assemblies)) { foreach (var item in assemblies.Split('|')) { Assembly assembly = Assembly.Load(item); foreach (var implement in assembly.GetTypes()) { Type[] interfaceType = implement.GetInterfaces(); foreach (var service in interfaceType) { services.AddTransient(service, implement); } } } } //在停用 token 的代码中,我们使用了 Redis 去保存停用的 token 信息,因此,我们需要配置我们的 Redis 连接。 services.AddDistributedRedisCache(r => { r.Configuration = Configuration["Redis:ConnectionString"]; }); services.AddAutoMapper(); //DI Sql Data services.AddTransient<IDataRepository, DataRepository>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiVersionDescriptionProvider provider) { //record interface call time; app.UsePerformanceLog(); //Enable Authentication app.UseAuthentication(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } // 启用CORS服务,必须放在mvc前面 app.UseCors("any"); app.UseHttpsRedirection(); app.UseMvc(); //Load Sql Data app.UseDapper(); //使用Swagger app.UseSwagger(); app.UseSwaggerUI(s => { //版本控制 // s.SwaggerEndpoint("/swagger/v1/swagger.json", "momo API V1.0"); foreach (var description in provider.ApiVersionDescriptions.Reverse()) { s.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", $"momo API {description.GroupName.ToUpperInvariant()}"); } }); } } }
namespace FlippoIO { public struct Tile { public readonly bool occupied; public readonly bool white; public Tile(bool occupied, bool white) { this.occupied = occupied; this.white = white; } public override string ToString() => (occupied ? (white ? Settings.WhiteChar : Settings.BlackChar) : Settings.EmptyChar).ToString(); } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DefaultCartDataEnricher.cs" company="Jeroen Stemerdink"> // Copyright © 2019 Jeroen Stemerdink. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace EPi.Libraries.Logging.Serilog.Enrichers.Commerce { using System; using System.Linq; using EPiServer.Commerce.Order; using EPiServer.ServiceLocation; using Mediachase.Commerce.Customers; using Mediachase.Commerce.Orders; using Newtonsoft.Json; using global::Serilog.Core; using global::Serilog.Events; /// <summary> /// Class DefaultCartDataEnricher. /// </summary> /// <seealso cref="ILogEventEnricher" /> public class DefaultCartDataEnricher : ILogEventEnricher { /// <summary> /// The current cart property name /// </summary> public const string CurrentCartPropertyName = "CurrentCart"; /// <summary> /// Enrich the log event. /// </summary> /// <param name="logEvent">The log event to enrich.</param> /// <param name="propertyFactory">Factory for creating new properties to add to the event.</param> public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory) { if (logEvent == null) { return; } IOrderRepository orderRepository; CustomerContext customerContext = CustomerContext.Current; if (customerContext == null || customerContext.CurrentContactId == Guid.Empty) { return; } try { orderRepository = ServiceLocator.Current.GetInstance<IOrderRepository>(); } catch (ActivationException) { return; } ICart cart = orderRepository.Load<ICart>( customerId: customerContext.CurrentContactId, name: Cart.DefaultName).FirstOrDefault(); string serializedCart = string.Empty; if (cart != null && cart.GetAllLineItems().Any()) { try { serializedCart = JsonConvert.SerializeObject( value: cart, formatting: Formatting.Indented, settings: new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore }); } catch { } } if (!string.IsNullOrWhiteSpace(serializedCart)) { logEvent.AddPropertyIfAbsent( new LogEventProperty( name: CurrentCartPropertyName, value: new ScalarValue(serializedCart))); } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using GisSharpBlog.NetTopologySuite.Geometries; using NUnit.Framework; using SharpMap.Rendering; namespace SharpMap.Tests.Rendering { [TestFixture] public class MapHelperTest { [Test] public void ImageToWorld() { var map = new Map(new Size(400, 300)) {Zoom = 50}; var coordinate = MapHelper.ImageToWorld(map, 15, 15); Assert.AreEqual(1.875, coordinate.X); Assert.AreEqual(1.875, coordinate.Y); } [Test] public void GetEnvelope() { var envelope = MapHelper.GetEnvelope(new Coordinate(5, 5), 7, 6); Assert.AreEqual(5, envelope.Centre.X); Assert.AreEqual(5, envelope.Centre.Y); Assert.AreEqual(7, envelope.Width); Assert.AreEqual(6, envelope.Height); } [Test] public void GetEnvelopeForImage() { var map = new Map(new Size(400, 300)) { Zoom = 50 }; var envelope = MapHelper.GetEnvelopeForImage(map, new Coordinate(5, 5), 16, 16); Assert.AreEqual(5, envelope.Centre.X); Assert.AreEqual(5, envelope.Centre.Y); Assert.AreEqual(2, envelope.Width); Assert.AreEqual(2, envelope.Height); } } }
using PopulationFitness.Models; using PopulationFitness.Models.Genes.Cache; using PopulationFitness.Output; using System; using System.Collections.Generic; namespace PopulationFitness { public class Commands { public const string Seed = "-s"; public const string TuningFile = "-t"; public const string EpochsFile = "-e"; public const string Id = "-i"; public const string RandomSeed = "random"; /** * Defines the path of the tuning file read from arguments. */ public static string TuningFilePath = ""; /** * Defines the path of the epochs file read from arguments. */ public static string EpochsFilePath = ""; /** * Defines the command line for any child processes */ public static string ChildCommandLine = ""; /** * Defines the cache type for genes */ public static CacheType CacheType = CacheType.Default; /** * Reads tuning and epochs from the process arguments * * @param config * @param tuning * @param epochs * @param args */ public static void ConfigureTuningAndEpochsFromInputFiles(Config config, Tuning tuning, Epochs epochs, string[] args) { int parallelCount = 1; if (args.Length < 2) { ShowHelp(); } if (args.Length % 2 == 1) { ShowHelp(); } for (int i = 0; i < args.Length - 1; i += 2) { string argument = args[i].ToLower(); string value = args[i + 1]; try { if (argument.StartsWith(Seed)) { long seed = getSeed(value); RepeatableRandom.SetSeed(seed); continue; } if (argument.StartsWith(TuningFile)) { TuningFilePath = value; TuningReader.Read(tuning, TuningFilePath); config.SizeOfEachGene = tuning.SizeOfGenes; config.NumberOfGenes = tuning.NumberOfGenes; config.GenesFactory.FitnessFunction =tuning.Function; config.MutationsPerGene = tuning.MutationsPerGene; parallelCount = tuning.ParallelRuns; continue; } if (argument.StartsWith(EpochsFile)) { EpochsFilePath = value; List<Epoch> read = EpochsReader.ReadEpochs(config, EpochsFilePath); epochs.AddAll(read); continue; } if (argument.StartsWith(Id)) { config.Id = tuning.Id = value; continue; } } catch (Exception e) { Console.Write(e); } ShowHelp(); } tuning.ParallelRuns = parallelCount; } private static long getSeed(string arg) { // Will set the seed from the current time if 'random' is chosen if (arg.ToLower().StartsWith(RandomSeed)) { return DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; } return Int64.Parse(arg); } private static void ShowHelp() { Console.WriteLine("Commands:"); Console.WriteLine(" -s [seed number]| [random to set a seed from the current time]"); Console.WriteLine(" -t [csv file containing tuning]"); Console.WriteLine(" -e [csv file containing epochs]"); Console.WriteLine(" -i [simulation id - used to generate the name of the output files"); Environment.Exit(0); } } }
using System; using System.Data.Entity; using System.Linq; using System.Windows.Forms; using Taggart.Data; namespace Taggart { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { using (var ctx = new TrackLibraryContext()) { var libraries = ctx.Libraries.ToList(); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LuckyMasale.DAL { /// <summary> /// Interface for the <see cref="DataSourceFactory"/> class. /// </summary> public interface IDataSourceFactory { /// <summary> /// Creates a new data source. /// </summary> /// <returns>The data source.</returns> IDataSource CreateDataSource(); } /// <summary> /// Contains all logic for creating new data sources. /// </summary> public class DataSourceFactory : IDataSourceFactory { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DataSourceFactory"/> class. /// </summary> public DataSourceFactory() { } #endregion #region Public Methods /// <summary> /// Creates a new data source. /// </summary> /// <returns>The data source.</returns> public IDataSource CreateDataSource() { return new DataSource(); } #endregion } }
using System; using System.Xml; namespace gView.Framework.system { static public class MapServerConfig { static private string _defaultOutputPath = String.Empty, _defaultOutputUrl = String.Empty, _defaultTileCachePath = String.Empty, _defaultOnlineResource = String.Empty; static private int _removeInterval = 20; static private bool _loaded = false; static private ServerConfig[] _servers = new ServerConfig[0]; static public void Load() { _loaded = true; try { _servers = new ServerConfig[0]; XmlDocument doc = new XmlDocument(); doc.Load(SystemVariables.CommonApplicationData + @"/mapServer/MapServerConfig.xml"); XmlNode globalsNode = doc.SelectSingleNode("mapserver/globals"); _defaultOutputUrl = GetAttributeValue(globalsNode, "outputurl", "http://localhost/output"); _defaultOutputPath = GetAttributeValue(globalsNode, "outputpath", @"C:\output"); _defaultTileCachePath = GetAttributeValue(globalsNode, "tilecachepath", @"C:\output\tiles"); _defaultOnlineResource = GetAttributeValue(globalsNode, "onlineresource", "http://localhost:{port}"); _removeInterval = int.Parse(GetAttributeValue(globalsNode, "removeinterval", "20")); foreach (XmlNode serverNode in doc.SelectNodes("mapserver/servers/server[@port]")) { ServerConfig serverConfig = new ServerConfig(); serverConfig.Port = int.Parse(serverNode.Attributes["port"].Value); serverConfig.OutputUrl = GetAttributeValue(serverNode, "outputurl", _defaultOutputUrl); serverConfig.OutputPath = GetAttributeValue(serverNode, "outputpath", _defaultOutputPath); serverConfig.TileCachePath = GetAttributeValue(serverNode, "tilecachpath", _defaultTileCachePath); serverConfig.OnlineResource = GetAttributeValue(serverNode, "onlineresource", _defaultOnlineResource.Replace("{port}", serverConfig.Port.ToString())); foreach (XmlNode instanceNode in serverNode.SelectNodes("instances/instance[@port]")) { ServerConfig.InstanceConfig instanceConfig = new ServerConfig.InstanceConfig(); instanceConfig.Port = int.Parse(instanceNode.Attributes["port"].Value); instanceConfig.MaxThreads = int.Parse(GetAttributeValue(instanceNode, "threads", "4")); instanceConfig.MaxQueueLength = int.Parse(GetAttributeValue(instanceNode, "queuelength", "100")); Array.Resize<ServerConfig.InstanceConfig>(ref serverConfig.Instances, serverConfig.Instances.Length + 1); serverConfig.Instances[serverConfig.Instances.Length - 1] = instanceConfig; } Array.Resize<ServerConfig>(ref _servers, _servers.Length + 1); _servers[_servers.Length - 1] = serverConfig; } } catch (Exception ex) { string msg = ex.Message; _loaded = false; } } static private string GetAttributeValue(XmlNode node, string attrName, string defValue) { if (node == null || node.Attributes[attrName] == null) { return defValue; } return node.Attributes[attrName].Value; } static public string DefaultOutputPath { get { if (!_loaded) { Load(); } return _defaultOutputPath; } set { _defaultOutputPath = value; } } static public string DefaultOutputUrl { get { if (!_loaded) { Load(); } return _defaultOutputUrl; } set { _defaultOutputUrl = value; } } static public int RemoveInterval { get { if (!_loaded) { Load(); } return _removeInterval; } set { _removeInterval = value; } } static public string DefaultTileCachePath { get { if (!_loaded) { Load(); } return _defaultTileCachePath; } set { _defaultTileCachePath = value; } } static public string DefaultOnlineResource { get { if (!_loaded) { Load(); } return _defaultOnlineResource; } set { _defaultOnlineResource = value; } } static public void Commit() { if (!_loaded) { Load(); } } public class ServerConfig { public int Port = 8001; public string OutputPath = String.Empty; public string OutputUrl = String.Empty; public string OnlineResource = String.Empty; public string TileCachePath = String.Empty; public InstanceConfig[] Instances = new InstanceConfig[0]; public class InstanceConfig { public int Port = 8011; public int MaxThreads = 5; public int MaxQueueLength = 100; } } static public int ServerCount { get { if (!_loaded) { Load(); } return _servers.Length; } } static public ServerConfig Server(int serverNumber) { if (!_loaded) { Load(); } if (serverNumber < 0 || serverNumber >= ServerCount) { return null; } return _servers[serverNumber]; } static public ServerConfig ServerByPort(int port) { if (!_loaded) { Load(); } for (int i = 0; i < _servers.Length; i++) { if (_servers[i].Port == port) { return _servers[i]; } } return null; } static public ServerConfig ServerByInstancePort(int port) { if (!_loaded) { Load(); } for (int s = 0; s < _servers.Length; s++) { for (int i = 0; i < _servers[s].Instances.Length; i++) { if (_servers[s].Instances[i].Port == port) { return _servers[s]; } } } return null; } static public ServerConfig.InstanceConfig InstanceByInstancePort(int port) { if (!_loaded) { Load(); } for (int s = 0; s < _servers.Length; s++) { for (int i = 0; i < _servers[s].Instances.Length; i++) { if (_servers[s].Instances[i].Port == port) { return _servers[s].Instances[i]; } } } return null; } } }
using FluentMigrator; namespace Profiling2.Migrations { [Migration(201306251237)] public class MoveUnitHierarchyOrganizationAudit : Migration { public override void Down() { Delete.Column("OrganizationID").FromTable("PRF_Unit_AUD"); } public override void Up() { Create.Column("OrganizationID").OnTable("PRF_Unit_AUD").AsInt32().Nullable(); } } }
using SuiviCompresseur.GestionCompresseur.Domain.Models; using System; using System.Collections.Generic; using System.Text; namespace SuiviCompresseur.GestionCompresseur.Application.Interfaces { public interface ICompresseurService { IEnumerable<FournisseurDup> GetFournisseursDup(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GUI.Models; namespace GUI.Repositories { public interface IAsyncIrpRepository { /// <summary> /// Returns all IRPs. /// </summary> Task<IEnumerable<Irp>> GetAsync(); /// <summary> /// Returns all IRPs matching a field matching the given pattern. /// </summary> Task<IEnumerable<Irp>> GetAsync(string pattern); Task<bool> Insert(Irp irp); Task<bool> Clear(); Task<bool> Delete(int id); int Count(); } }
/*********************************************************************** * Module: Ingredient.cs * Author: Dragana Carapic * Purpose: Definition of the Class Manager.Ingredient ***********************************************************************/ using System; namespace Model.Manager { public class Ingredient { public string Name { get; set; } public bool Alergen { get; set; } public Ingredient() { this.Alergen = false; } public Ingredient(string name, bool alergen) { this.Name = name; this.Alergen = alergen; } public Ingredient(Ingredient ingredient) { this.Name = ingredient.Name; this.Alergen = ingredient.Alergen; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace myBOOK.data { public class Books { [Key] [Column(Order = 1)] public string BookName { get; set; } [Key] [Column(Order = 2)] public string Author { get; set; } public Genres Genre { get; set; } public string Description { get; set; } public string LoadingLink { get; set; } public enum Genres { Fiction, Comedy, Drama, Horror, RomanceNovel, Satire, Tragedy, Tragicomedy, Fantasy, ChildrenLiterature, Mystery, ScienceFiction, PictureBook, Western, ShortStory, Biography, Essay, Memoir, NonFiction, Action, SelfHelp, History, Poetry } //public static implicit operator Books(Books v) //{ //throw new NotImplementedException(); //} } }
using Anywhere2Go.DataAccess.Entity; using Anywhere2Go.DataAccess.MySqlEntity; using System; using System.Collections.Generic; namespace Claimdi.Web.TH.Models { //public class ReportViewModel //{ // public string RepTaskId { get; set; } // public string RepTaskProcessId { get; set; } // public string RepInsurerId { get; set; } // public string RepTaskTypeId { get; set; } // public string RepDepartmentId { get; set; } // public string RepStartDate { get; set; } // public string RepEndDate { get; set; } // public string RepTaskDisplay { get; set; } // public List<TaskReport> TaskReportData { get; set; } // public List<TaskInspectionReport> TaskInspectionReportData { get; set; } // public List<InsPaymentReport> InsPaymentReportData { get; set; } // public List<InsCountTaskReport> InsCountTaskReportData { get; set; } // public string RepProvinceCode { get; set; } // public string RepAmphurCode { get; set; } // public string RepDistrictCode { get; set; } // public string RepCarRegis { get; set; } // public string RepComId { get; set; } // public string RepAssignAccId { get; set; } // // public List<SurveyorReport> SurveyorReportData { get; set; } //} //public class ReportSearchModel //{ // public string RepTaskDisplay { get; set; } // public string RepProcessId { get; set; } // public string RepInsurerId { get; set; } // public string RepTaskTypeId { get; set; } // public string RepDepartmentId { get; set; } // public string RepStartDate { get; set; } // public string RepEndDate { get; set; } // public List<TaskReport> TaskReportData { get; set; } // public string RepProvinceCode { get; set; } // public string RepAmphurCode { get; set; } // public string RepDistrictCode { get; set; } // public string RepCarRegis { get; set; } // public string RepComId { get; set; } // public string RepEmployeeId { get; set; } //} //public class ReportTsoftSearchModel //{ // public int TRAdvertiseID { get; set; } // public int ClaimType { get; set; } // public int InsurerID { get; set; } // public string SurvJobNo { get; set; } // public string RefClaimNo { get; set; } // public string PrbNumber { get; set; } // public string AccPolicyNo { get; set; } // public string AssuredName { get; set; } // public string TxtCallPlace { get; set; } // public string TxtCallCause { get; set; } // public string TxtCallName { get; set; } // public string PolicyType { get; set; } // public int AdvertiseStatus { get; set; } // public int TypeJob { get; set; } // public List<TRAdvertise> TaskReportData { get; set; } // public string StartDate { get; set; } // public string EndDate { get; set; } //} }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Reflection; abstract public class State<T> { private T owner; /// <summary> /// Call upward to get the base GameObject or other necessary parent properties or functions /// </summary> public T Owner { get { return owner; } private set { owner = value; } } [Tooltip("Is the state initialized")] private bool initialized; /// <summary> /// Setup for the state equivalent to constructor /// </summary> /// <param name="owner">setting parent variable</param> virtual public void Configure(T owner) { Owner = owner; initialized = true; } /// <summary> /// Startup for the state to run smooth. /// Assign any used null variables here. /// </summary> abstract public void OnEnter(); /// <summary> /// Actions and checks that happen every frame. /// </summary> abstract public void Process(); /// <summary> /// Cleanup to safely transition states. /// </summary> abstract public void OnExit(); /// <summary> /// Used for the background process. /// </summary> abstract public void GlobalProcess(); /// <summary> /// Through reflection, send the message to the first active state that can take the method (nested state machines). /// </summary> /// <param name="call">Function being called</param> /// <param name="args">arguments for the function to use</param> public void messageCalls(string call, params object[] args) { Type t = GetType(); if(t != null) { MethodInfo mi = t.GetMethod(call); if (mi != null) { mi.Invoke(this, args); } else { StateMachine<T> sm = t.GetMember("stateMachine") as StateMachine<T>; if (sm != null) { sm.messageReciever(call, args); } } } } public bool canRun() { return initialized; } } /// <summary> /// NAME ALL VARIABLES "stateMachine" /// Value is used to find nested state machines. /// Finite State Machines are used to run specific sections of code at a time. /// </summary> /// <typeparam name="T">The class that is running the state machine</typeparam> public class StateMachine<T> { private T owner; /// <summary> /// Call upward to get the base GameObject or other necessary parent properties or functions /// </summary> public T Owner { get { return owner; } private set { owner = value; } } [Tooltip("Active state running")] private State<T> currentState; [Tooltip("Previous state, shouldn't be used extensively")] private State<T> previousState; [Tooltip("Background state to run throughout the program.")] private State<T> globalState; private bool pause; /// <summary> /// pause the current state, useful for menus /// </summary> public bool Pause { get { return pause; } set { pause = value; } } private string state; /// <summary> /// String for the active state, /// Shouldn't be used extensively /// </summary> public string State { get { return state; } set { state = value; } } /// <summary> /// preventing "missing" components /// </summary> public void Awake() { currentState = null; previousState = null; globalState = null; } /// <summary> /// Initial setup for the state machine /// </summary> /// <param name="owner">reference to the parent class</param> /// <param name="InitialState">starting state that is used</param> public void Configure(T owner, State<T> InitialState) { this.owner = owner; ChangeState(InitialState); } /// <summary> /// Main actions in the state machine /// </summary> public void Update() { if (globalState != null) globalState.Process(); if (currentState != null && !pause) currentState.Process(); } /// <summary> /// Exits previous global state and enters a new one /// </summary> /// <param name="newGlobalState">new global state for the state machine</param> public void ChangeGlobalState(State<T> newGlobalState) { if (globalState != null) globalState.OnExit(); globalState = newGlobalState; if (globalState != null) { if (!globalState.canRun()) { globalState.Configure(owner); } globalState.OnEnter(); } } /// <summary> /// Stores current state as previous, exits old state, enters new state /// </summary> /// <param name="NewState">new state that the state machine runs</param> public void ChangeState(State<T> NewState) { previousState = currentState; if (currentState != null) currentState.OnExit(); currentState = NewState; if (currentState != null) { if(!currentState.canRun()) { currentState.Configure(owner); } currentState.OnEnter(); } } /// <summary> /// Changes state to the previous state /// rare use case /// </summary> public void RevertToPreviousState() { if (previousState != null) ChangeState(previousState); } /// <summary> /// calling internal state functions /// </summary> /// <param name="call">function that will be called</param> /// <param name="args">arguments for the function</param> public void messageReciever(string call, params object[] args) { messageReciever(call, false, args); } /// <summary> /// calling internal state functions /// </summary> /// <param name="call">function that will be called</param> /// <param name="globalState">sends to the global state</param> /// <param name="args">arguments for the function</param> public void messageReciever(string call, bool globalState, params object[] args) { if (globalState) { this.globalState.messageCalls(call, args); } else { currentState.messageCalls(call, args); } } public bool isInCurrentState(State<T> state) { return currentState.Equals(state); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace Commun { public enum TypePaquet { Material, DirtyMaterial, Commande } [Serializable()] // Pour que la classe soit sérialisable public class Paquet //Une superclasse pour les paquets { public TypePaquet Type { get; protected set; } public Paquet(TypePaquet Type) { this.Type = Type; } //Méthode statique pour l'envoi et la réception public static void Send(Paquet paquet, NetworkStream stream) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(stream, paquet); stream.Flush(); } public static Paquet Receive(NetworkStream stream) { Paquet p = null; BinaryFormatter bf = new BinaryFormatter(); p = (Paquet)bf.Deserialize(stream); return p; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SolutionsAssemblyConsoleTest.Interfaces { interface IShowResults { void ShowResults(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DelftTools.Functions; using DelftTools.Hydro.Structures; using NUnit.Framework; using ValidationAspects; namespace DelftTools.DataObjects.Tests.HydroNetwork.Structures { [TestFixture] public class PumpTest { [Test] public void DefaultPump() { Pump pump = new Pump("testPump"); Assert.IsTrue(pump.Validate().IsValid); } [Test] public void Clone() { var pump = new Pump("Kees") {LongName = "Long"}; var clone = (Pump) pump.Clone(); Assert.AreEqual(clone.LongName, pump.LongName); } [Test] public void CopyFrom() { var targetPump = new Pump(); var sourcePump = new Pump { Name = "target", Capacity = 42.0, StartDelivery = 1, StopDelivery = 0, StartSuction = 4.0, StopSuction = 3.0, DirectionIsPositive = false, ControlDirection = PumpControlDirection.DeliverySideControl, ReductionTable = FunctionHelper.Get1DFunction<double, double>("reduction", "differrence", "factor") }; targetPump.CopyFrom(sourcePump); Assert.AreEqual(sourcePump.Attributes, targetPump.Attributes); Assert.AreEqual(sourcePump.Capacity, targetPump.Capacity); Assert.AreEqual(sourcePump.StopDelivery, targetPump.StopDelivery); Assert.AreEqual(sourcePump.StartDelivery, targetPump.StartDelivery); Assert.AreEqual(sourcePump.StartSuction, targetPump.StartSuction); Assert.AreEqual(sourcePump.StopSuction, targetPump.StopSuction); Assert.AreEqual(sourcePump.ControlDirection, targetPump.ControlDirection); Assert.AreEqual(sourcePump.OffsetY, targetPump.OffsetY); Assert.AreEqual(sourcePump.DirectionIsPositive, targetPump.DirectionIsPositive); for (int i = 0; i < sourcePump.ReductionTable.Components[0].Values.Count; i++) { Assert.AreEqual(sourcePump.ReductionTable.Components[0].Values[i], targetPump.ReductionTable.Components[0].Values[i]); } Assert.AreNotEqual(sourcePump.Name, targetPump.Name); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CameraInterface.Cameras { public class HuaweiCamera : ICamera { public bool _isActive; public HuaweiCamera() { } public bool isActive { get { { return _isActive; }; } set { { _isActive = value; } } } public ActionResult Activate() { if (!_isActive) { _isActive = true; return new ActionResult("Camera Huawei has been activated", _isActive); } else { return new ActionResult(" Error Camera Huawei has been already active", _isActive); } } public ActionResult DeActivate() { if (_isActive) { _isActive = false; return new ActionResult("Camera Huawei has been Deactivated", _isActive); } else { return new ActionResult(" Error Camera Huawei has been already Deactived", _isActive); } } public ActionResult ChargeCamera() { return new ActionResult(" Camera was completly Charged!", true); } public ActionResult SetCamera() { if (_isActive) { return new ActionResult(" Ok all Camera's Huawei settings has been applied ",_isActive); } else { return new ActionResult(" Error was not possible set camera Huawei because was already Deactive ", _isActive); } } public ImagePhoto TakeSnap() { if (_isActive) { return new ImagePhoto(@"C:\myImagesHuawei\myImage", DateTime.Now, ".jpg",true); } else { return new ImagePhoto("noActiveHuaweiCamera", DateTime.Now, "noActive",true); } } } }
using System; using iSukces.Code.Interfaces; namespace EqualityGeneratorSample { [Auto.EqualityGeneratorAttribute(null, CachedGetHashCodeImplementation = GetHashCodeImplementationKind.Custom)] public partial class ClassWithCustomGetHashCode { public ClassWithCustomGetHashCode(string firstName, string lastName, DateTime birthDate, DateTime? otherDate) { FirstName = firstName; LastName = lastName; BirthDate = birthDate; OtherDate = otherDate; // _cachedHashCode = CalculateHashCode(); } public override int GetHashCode() { // make this code manually unchecked { var hashCode = StringComparer.Ordinal.GetHashCode(FirstName ?? string.Empty); hashCode = (hashCode * 397) ^ StringComparer.Ordinal.GetHashCode(LastName ?? string.Empty); hashCode = (hashCode * 397) ^ BirthDate.GetHashCode(); hashCode = (hashCode * 397) ^ OtherDate?.GetHashCode() ?? 0; return hashCode; } } public string FirstName { get; } public string LastName { get; } public DateTime BirthDate { get; } public DateTime? OtherDate { get; } } }