text
stringlengths
13
6.01M
//============================================================================== // Copyright (c) 2012-2020 Fiats Inc. All rights reserved. // https://www.fiats.asia/ // using System; using System.Collections.Generic; namespace Financial.Extensions.Trading { public class Market<TPrice, TSize> : IMarket<TPrice, TSize> { public string MarketSymbol { get; private set; } public TPrice MarketPrice { get; private set; } public DateTime LastUpdatedTime { get; private set; } List<IOrder<TPrice, TSize>> _activeOrders = new List<IOrder<TPrice, TSize>>(); List<IOrder<TPrice, TSize>> _closedOrders = new List<IOrder<TPrice, TSize>>(); public bool HasActiveOrder => _activeOrders.Count > 0; public event Action<IOrder<TPrice, TSize>> OrderChanged; public virtual void UpdatePrice(DateTime time, TPrice price) { LastUpdatedTime = time; MarketPrice = price; var activeOrders = new List<IOrder<TPrice, TSize>>(); foreach (var order in _activeOrders) { if (!order.TryExecute(LastUpdatedTime, MarketPrice)) { continue; } if (order.IsClosed) { _closedOrders.Add(order); } else { activeOrders.Add(order); } OrderChanged?.Invoke(order); } _activeOrders = activeOrders; } public bool PlaceOrder(IOrder<TPrice, TSize> order) { order.Open(LastUpdatedTime); if (!order.TryExecute(LastUpdatedTime, MarketPrice)) { _activeOrders.Add(order); return true; } if (order.IsClosed) { _closedOrders.Add(order); } else { _activeOrders.Add(order); } OrderChanged?.Invoke(order); return true; } public bool PlaceOrder(IOrder<TPrice, TSize> order, TimeInForce tif) { throw new NotSupportedException(); } OrderFactory<TPrice, TSize> _orderFactory = new OrderFactory<TPrice, TSize>(); public IOrderFactory<TPrice, TSize> GetOrderFactory() => _orderFactory; public Market() { } public Market(string marketSymbol) { MarketSymbol = marketSymbol; } } }
using PePo.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using UnityEngine; using UnityEngine.Networking; using UnityEngine.SceneManagement; using UnityEngine.UI; using CI.HttpClient; public class MainPageController : MonoBehaviour { public Transform MarketPage; public Transform MyBookPage; public Transform NotificationPage; public Transform MyBookSelectPage; public GameObject BookItem; public GameObject MyBookItem; public GameObject NotificationItem; public InputField SearchField; public Image BookDetail_BookPicture; public Text BookDetail_BookName; public Text BookDetail_BookDescription; public Image BookDetail_ProfilePicture; public Text BookDetail_ProfileName; public Image MyProfile; public Text MyName; public Text MyUsername; public Text MyBookNumber; public Image confirmation_offerPicture; public Image confirmation_mePicture; public Image confirmation_userPicture; public Text confirmation_OfferBookName; public Text confirmation_OfferBookDescription; public Text confirmation_OfferName; public Text confirmation_MeBookName; public Text confirmation_MeBookDescription; public Image AddNew_Photo; public Text AddNew_BookName; public Text AddNew_Description; public Image Receipt_otherBook; public Image Receipt_userBook; public Text Receipt_otherBookName; public Text Receipt_userBookName; public Text Receipt_otherTele; public Text Receipt_userTele; public Text Receipt_otherName; public Text Receipt_userName; public Text TextButtonSelectBook; public Sprite ProfilePicture; public Sprite PhotoPicture; private byte[] imageUpload; private MainPage_UIManager UIManager; private float timeToCloseApp = 0; private int currentBookID; private int currentUserID; private int numberOfTransaction; private string _path; private void Awake() { UIManager = GameObject.Find("MainPage_UIManager").GetComponent<MainPage_UIManager>(); LoadBook(); StartCoroutine(LoadNotificationAPI(request => { print(request.downloadHandler.text); var notis = JsonUtility.FromJson<Notifications>(request.downloadHandler.text); if (notis != null) { foreach (var noti in notis.list) { var item = Instantiate(NotificationItem); item.transform.SetParent(NotificationPage, false); var TemList = new List<Transform>(); for (int i = 0; i < 2; i++) { TemList.Add(item.transform.GetChild(i)); } foreach (var listObj in TemList) { switch (listObj.name) { case "Image:BookPhoto": StartCoroutine(LoadBookPicture(noti.image, action => { var texture = DownloadHandlerTexture.GetContent(action); listObj.GetComponent<Image>().sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); })); break; case "Text:Detail": listObj.GetComponent<Text>().text = $"{noti.username}"; break; } } item.GetComponent<Button>().onClick.AddListener(() => OnClick_NotificationItem(int.Parse(noti.book_id))); } } })); MyName.text = PlayerPrefs.GetString("name"); MyUsername.text = PlayerPrefs.GetString("username"); } private void LoadBook() { StartCoroutine(LoadMarketAPI(request => { print(request.downloadHandler.text); var books = JsonUtility.FromJson<Books>(request.downloadHandler.text); if (books != null) { if (books.list.Count > 6) { var x = books.list.Count - 5; x /= 2; MarketPage.GetComponent<RectTransform>().sizeDelta = new Vector2(MarketPage.GetComponent<RectTransform>().sizeDelta.x, 3560 + 1200 * x); } foreach (var book in books.list) { var item = Instantiate(BookItem); item.transform.SetParent(MarketPage, false); var TemList = new List<Transform>(); for (int i = 0; i < 3; i++) { TemList.Add(item.transform.GetChild(i)); } foreach (var listObj in TemList) { switch (listObj.name) { case "Image:BookPhoto": StartCoroutine(LoadBookPicture(book.image, action => { var texture = DownloadHandlerTexture.GetContent(action); listObj.GetComponent<Image>().sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); })); break; case "Text:Title": listObj.GetComponent<Text>().text = $"{book.book_name}"; break; case "Text:Detail": listObj.GetComponent<Text>().text = book.description; break; } } item.GetComponent<Button>().onClick.AddListener(() => OnClick_BookItem(int.Parse(book.book_id))); } } })); StartCoroutine(LoadMyBookAPI(request => { var books = JsonUtility.FromJson<Books>(request.downloadHandler.text); if (books != null) { MyBookNumber.text = books.list.Count.ToString(); ; if (books.list.Count > 4) { var x = books.list.Count - 3; x /= 2; MyBookSelectPage.GetComponent<RectTransform>().sizeDelta = new Vector2(MyBookSelectPage.GetComponent<RectTransform>().sizeDelta.x, 2326.8f + 1200 * x); } foreach (var book in books.list) { var itemX = Instantiate(MyBookItem); itemX.transform.SetParent(MyBookSelectPage, false); var TemListX = new List<Transform>(); for (int i = 0; i < 2; i++) { TemListX.Add(itemX.transform.GetChild(i)); } foreach (var listObj in TemListX) { switch (listObj.name) { case "Image:BookPhoto": StartCoroutine(LoadBookPicture(book.image, action => { var texture = DownloadHandlerTexture.GetContent(action); listObj.GetComponent<Image>().sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); })); break; case "Text:Detail": listObj.GetComponent<Text>().text = book.book_name; break; } } itemX.GetComponent<Button>().onClick.AddListener(() => OnClick_MyBookItem(int.Parse(book.book_id))); var item = Instantiate(BookItem); item.transform.SetParent(MyBookPage, false); var TemList = new List<Transform>(); for (int i = 0; i < 3; i++) { TemList.Add(item.transform.GetChild(i)); } foreach (var listObj in TemList) { switch (listObj.name) { case "Image:BookPhoto": StartCoroutine(LoadBookPicture(book.image, action => { var texture = DownloadHandlerTexture.GetContent(action); listObj.GetComponent<Image>().sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); })); break; case "Text:Title": listObj.GetComponent<Text>().text = $"{book.book_name}"; break; case "Text:Detail": listObj.GetComponent<Text>().text = book.description; break; } } item.GetComponent<Button>().onClick.AddListener(() => OnClick_MyBookSelfItem(int.Parse(book.book_id))); } } else { MyBookNumber.text = "0"; } })); } private void Update() { if (timeToCloseApp > (Time.time - 1.2f)) { if (Input.GetKeyDown(KeyCode.Escape)) { Application.Quit(); } } else { if (Input.GetKeyDown(KeyCode.Escape)) { timeToCloseApp = Time.time; AndroidNativeFunctions.ShowToast("double tab to exit app . . .", true); } } } public void OnClick_NotificationItem(int i) { AndroidNativeFunctions.ShowProgressDialog("Loading . . ."); StartCoroutine(SeeOfferAPI(i.ToString(), action => { print(action.downloadHandler.text); var con = JsonUtility.FromJson<confirmation>(action.downloadHandler.text); numberOfTransaction = int.Parse(con.me.number); confirmation_OfferBookName.text = con.offer.book_name; confirmation_OfferBookDescription.text = con.offer.description; confirmation_OfferName.text = con.offer.name; confirmation_MeBookDescription.text = con.me.description; confirmation_MeBookName.text = con.me.book_name; StartCoroutine(LoadBookPicture(con.offer.image, pic => { var texture = DownloadHandlerTexture.GetContent(pic); confirmation_offerPicture.sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); StartCoroutine(LoadBookPicture(con.offer.user_image, pic2 => { var texture1 = DownloadHandlerTexture.GetContent(pic2); confirmation_userPicture.sprite = Sprite.Create(texture1, new Rect(0.0f, 0.0f, texture1.width, texture1.height), new Vector2(0.5f, 0.5f), 100.0f); StartCoroutine(LoadBookPicture(con.me.image, pic3 => { var texture2 = DownloadHandlerTexture.GetContent(pic3); confirmation_mePicture.sprite = Sprite.Create(texture2, new Rect(0.0f, 0.0f, texture2.width, texture2.height), new Vector2(0.5f, 0.5f), 100.0f); UIManager.ShowConfirmation(); AndroidNativeFunctions.HideProgressDialog(); })); })); })); })); } public void OnClick_BookItem(int bookId) { AndroidNativeFunctions.ShowProgressDialog("Loading . . ."); currentBookID = bookId; TextButtonSelectBook.text = "Select Your book to make offer"; StartCoroutine(LoadBookDetail(bookId, action1 => { print(action1.downloadHandler.text); var bookDetail = JsonUtility.FromJson<BookData>(action1.downloadHandler.text); StartCoroutine(LoadBookPicture(bookDetail.image, action3 => { var texture = DownloadHandlerTexture.GetContent(action3); BookDetail_BookPicture.sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); })); BookDetail_BookName.text = bookDetail.book_name; BookDetail_BookDescription.text = bookDetail.description; currentUserID = int.Parse(bookDetail.user_creator); StartCoroutine(LoadUserProfile(currentUserID, action2 => { var userProfile = JsonUtility.FromJson<UserProfile>(action2.downloadHandler.text); StartCoroutine(LoadBookPicture(userProfile.image, action3 => { var texture = DownloadHandlerTexture.GetContent(action3); BookDetail_ProfilePicture.sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); AndroidNativeFunctions.HideProgressDialog(); UIManager.ShowBookDetail(); })); BookDetail_ProfileName.text = userProfile.name; })); })); } public void OnClick_MyBookItem(int bookId) { var OfferData = new offerData(){ book_deal = currentBookID.ToString(), book_offer = bookId.ToString(), user_deal = currentUserID.ToString() }; AndroidNativeFunctions.ShowProgressDialog("Loading . . ."); StartCoroutine(SentOfferAPI(OfferData, action => { var TemList = new List<Transform>(); int x = MarketPage.childCount; for (int i = 0; i < x; i++) { TemList.Add(MarketPage.GetChild(i)); } for (int i = 0; i < x; i++) { Destroy(TemList[i].gameObject); } TemList.Clear(); x = MyBookPage.childCount; for (int i = 0; i < x; i++) { TemList.Add(MyBookPage.GetChild(i)); } for (int i = 0; i < x; i++) { Destroy(TemList[i].gameObject); } TemList.Clear(); x = MyBookSelectPage.childCount; for (int i = 0; i < x; i++) { TemList.Add(MyBookSelectPage.GetChild(i)); } for (int i = 0; i < x; i++) { Destroy(TemList[i].gameObject); } LoadBook(); UIManager.ShowDialog(); AndroidNativeFunctions.HideProgressDialog(); })); } public void OnClick_MyBookSelfItem(int bookId) { TextButtonSelectBook.text = "Delete this book"; AndroidNativeFunctions.ShowProgressDialog("Loading . . ."); currentBookID = bookId; StartCoroutine(LoadBookDetail(bookId, action1 => { var bookDetail = JsonUtility.FromJson<BookData>(action1.downloadHandler.text); StartCoroutine(LoadBookPicture(bookDetail.image, action3 => { var texture = DownloadHandlerTexture.GetContent(action3); BookDetail_BookPicture.sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); })); BookDetail_BookName.text = bookDetail.book_name; BookDetail_BookDescription.text = bookDetail.description; StartCoroutine(LoadUserProfile(int.Parse(bookDetail.user_creator), action2 => { print(action2.downloadHandler.text); var userProfile = JsonUtility.FromJson<UserProfile>(action2.downloadHandler.text); StartCoroutine(LoadBookPicture(userProfile.image, action3 => { var texture = DownloadHandlerTexture.GetContent(action3); BookDetail_ProfilePicture.sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); AndroidNativeFunctions.HideProgressDialog(); UIManager.ShowBookDetail(); })); BookDetail_ProfileName.text = userProfile.name; })); })); } public void OnClick_SelectBook() { if (TextButtonSelectBook.text.Equals("Delete this book")) { AndroidNativeFunctions.ShowAlert("This action will delete your book information and orther people can't acess it", "Remove book from SwapBook", "Sure", "Cancel", "", action => { if (action == DialogInterface.Positive) { StartCoroutine(DeleteBookAPI(currentBookID.ToString(), callback => { var TemList = new List<Transform>(); int x = MarketPage.childCount; for (int i = 0; i < x; i++) { TemList.Add(MyBookPage.GetChild(i)); } for (int i = 0; i < x; i++) { Destroy(TemList[i].gameObject); } TemList.Clear(); x = MyBookSelectPage.childCount; for (int i = 0; i < x; i++) { TemList.Add(MyBookSelectPage.GetChild(i)); } for (int i = 0; i < x; i++) { Destroy(TemList[i].gameObject); } LoadBook(); UIManager.HideBookDetail(); })); } }); return; } if (int.Parse(MyBookNumber.text) > 0) { UIManager.OnClick_Offer(); } else { AndroidNativeFunctions.ShowToast("Your don't have any book to swap !"); } } public void OnClick_ChangePassword() { // StartCoroutine(); } public void OnClick_AddNew() { StartCoroutine(AddBookAPI(()=> { UIManager.HideAddNew(); AddNew_Photo.sprite = PhotoPicture; })); } public void OnClick_AddPicture() { NativeGallery.Permission permission = NativeGallery.GetImageFromGallery( ( path ) => { if( path != null ) { _path = path; AddNew_BookName.text = _path; Texture2D texture = NativeGallery.LoadImageAtPath( path, 1024 ); texture.Apply(); if( texture == null ) { Debug.Log( "Couldn't load texture from " + path ); return; } imageUpload = texture.EncodeToPNG(); AddNew_Photo.sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); } }, "Select a PNG image"); } public void AcceptOffer() { StartCoroutine(AcceptOfferAPI(numberOfTransaction.ToString(), action => { print(action.downloadHandler.text); var r = JsonUtility.FromJson<Receipt>(action.downloadHandler.text); Receipt_otherBookName.text = r.other_book.book_name; Receipt_otherName.text = r.other_user.name; Receipt_otherTele.text = r.other_user.telephone; Receipt_userBookName.text = r.book_me.book_name; Receipt_userName.text = r.user_me.name; Receipt_userTele.text = r.user_me.telephone; StartCoroutine(LoadBookPicture(r.other_book.image, pic => { var texture = DownloadHandlerTexture.GetContent(pic); Receipt_otherBook.sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); StartCoroutine(LoadBookPicture(r.book_me.image, pic2 => { texture = DownloadHandlerTexture.GetContent(pic2); Receipt_userBook.sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); UIManager.ShowReceipt(); UIManager.HideConfirmation(); })); })); })); } public void DisclaimOffer() { StartCoroutine(DisclaimOfferAPI(numberOfTransaction.ToString(), action=> { UIManager.HideConfirmation(); })); } public void OnClick_Search() { var TemList = new List<Transform>(); int x = MarketPage.childCount; for (int i = 0; i < x; i++) { TemList.Add(MarketPage.GetChild(i)); } for (int i = 0; i < x; i++) { Destroy(TemList[i].gameObject); } StartCoroutine(SearchAPI(SearchField.text, request => { print(request.downloadHandler.text); var books = JsonUtility.FromJson<Books>(request.downloadHandler.text); if (books != null) { if (books.list.Count > 6) { var y = books.list.Count - 5; y /= 2; MarketPage.GetComponent<RectTransform>().sizeDelta = new Vector2(MarketPage.GetComponent<RectTransform>().sizeDelta.x, 3560 + 1200 * y); } foreach (var book in books.list) { var item = Instantiate(BookItem); item.transform.SetParent(MarketPage, false); var TempList = new List<Transform>(); for (int i = 0; i < 3; i++) { TempList.Add(item.transform.GetChild(i)); } foreach (var listObj in TempList) { switch (listObj.name) { case "Image:BookPhoto": StartCoroutine(LoadBookPicture(book.image, action => { var texture = DownloadHandlerTexture.GetContent(action); listObj.GetComponent<Image>().sprite = Sprite.Create(texture, new Rect(0.0f, 0.0f, texture.width, texture.height), new Vector2(0.5f, 0.5f), 100.0f); })); break; case "Text:Title": listObj.GetComponent<Text>().text = $"{book.book_name}"; break; case "Text:Detail": listObj.GetComponent<Text>().text = book.description; break; } } item.GetComponent<Button>().onClick.AddListener(() => OnClick_BookItem(int.Parse(book.book_id))); } } })); } public void OnClick_Logout() { PlayerPrefs.DeleteAll(); OneSignal.ClearOneSignalNotifications(); SceneManager.LoadScene("Initialization"); } private IEnumerator AcceptOfferAPI(string number, Action<UnityWebRequest> callBack) { var request = new UnityWebRequest($"{Config.URL()}/transaction/accept", "POST"); var bodyRaw = new UTF8Encoding().GetBytes($"{{\"number\":\"{number}\"}}"); request.uploadHandler = new UploadHandlerRaw(bodyRaw); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("x-auth", PlayerPrefs.GetString("token")); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); callBack(request); } private IEnumerator DisclaimOfferAPI(string number, Action<UnityWebRequest> callBack) { var request = new UnityWebRequest($"{Config.URL()}/transaction/decline", "POST"); var bodyRaw = new UTF8Encoding().GetBytes($"{{\"number\":\"{number}\"}}"); request.uploadHandler = new UploadHandlerRaw(bodyRaw); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("x-auth", PlayerPrefs.GetString("token")); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); callBack(request); } private IEnumerator SearchAPI(string query, Action<UnityWebRequest> callBack) { var request = new UnityWebRequest($"{Config.URL()}/search", "POST"); var bodyRaw = new UTF8Encoding().GetBytes($"{{\"query\":\"{query}\"}}"); request.uploadHandler = new UploadHandlerRaw(bodyRaw); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("x-auth", PlayerPrefs.GetString("token")); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); callBack(request); } private IEnumerator DeleteBookAPI(string bookId, Action<UnityWebRequest> callBack) { var request = new UnityWebRequest($"{Config.URL()}/books/{bookId}", "DELETE"); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("x-auth", PlayerPrefs.GetString("token")); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); callBack(request); } private IEnumerator SeeOfferAPI(string bookId, Action<UnityWebRequest> callBack) { var request = new UnityWebRequest($"{Config.URL()}/transaction/confirmation", "POST"); var bodyRaw = new UTF8Encoding().GetBytes($"{{\"book_offer\":\"{bookId}\"}}"); request.uploadHandler = new UploadHandlerRaw(bodyRaw); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("x-auth", PlayerPrefs.GetString("token")); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); callBack(request); } private IEnumerator AddBookAPI(Action callBack) { var client = new HttpClient(); client.Headers.Add("x-auth", PlayerPrefs.GetString("token")); client.Headers.Add("book_name", AddNew_BookName.text); client.Headers.Add("description", AddNew_Description.text); var multipartFormDataContent = new MultipartFormDataContent(); multipartFormDataContent.Add(new ByteArrayContent(imageUpload, "application/octet-stream"), "bookImage", "image.png"); client.Post(new Uri($"{Config.URL()}/books/upload"), multipartFormDataContent, HttpCompletionOption.AllResponseContent, r => { }, (u) => { }); yield return new WaitForEndOfFrame(); callBack(); } private IEnumerator SentOfferAPI(offerData data, Action<UnityWebRequest> callBack) { var request = new UnityWebRequest($"{Config.URL()}/offer", "POST"); var bodyRaw = new UTF8Encoding().GetBytes(JsonUtility.ToJson(data)); request.uploadHandler = new UploadHandlerRaw(bodyRaw); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("x-auth", PlayerPrefs.GetString("token")); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); callBack(request); } private IEnumerator LoadMarketAPI(Action<UnityWebRequest> callBack) { var request = new UnityWebRequest($"{Config.URL()}/books", "GET"); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("x-auth", PlayerPrefs.GetString("token")); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); callBack(request); } private IEnumerator LoadMyBookAPI(Action<UnityWebRequest> callBack) { var request = new UnityWebRequest($"{Config.URL()}/books/me", "GET"); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("x-auth", PlayerPrefs.GetString("token")); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); callBack(request); } private IEnumerator LoadNotificationAPI(Action<UnityWebRequest> callBack) { var request = new UnityWebRequest($"{Config.URL()}/transaction/offer", "GET"); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("x-auth", PlayerPrefs.GetString("token")); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); callBack(request); } private IEnumerator LoadBookPicture(string pictureName, Action<UnityWebRequest> action) { UnityWebRequest www = UnityWebRequestTexture.GetTexture($"{Config.HostName}/{pictureName}"); yield return www.SendWebRequest(); action(www); } private IEnumerator LoadBookDetail(int bookId, Action<UnityWebRequest> action) { var request = new UnityWebRequest($"{Config.URL()}/books/{bookId}", "GET"); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); action(request); } private IEnumerator LoadUserProfile(int UserId, Action<UnityWebRequest> action) { var request = new UnityWebRequest($"{Config.URL()}/users/{UserId}", "GET"); request.downloadHandler = new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); action(request); } }
// ---------------------------------------------------------------------------------- // Microsoft Developer & Platform Evangelism // // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. // ---------------------------------------------------------------------------------- // The example companies, organizations, products, domain names, // e-mail addresses, logos, people, places, and events depicted // herein are fictitious. No association with any real company, // organization, product, domain name, email address, logo, person, // places, or events is intended or should be inferred. // ---------------------------------------------------------------------------------- namespace Microsoft.Web.MobileCapableViewEngine { using System.Collections.Specialized; using System.Globalization; using System.Linq; using System.Web; using System.Web.Mvc; /// <summary> /// Represents a view engine for rendering a Web Forms page in MVC with support for discover views for mobile devices. /// </summary> public class MobileCapableWebFormViewEngine : WebFormViewEngine { private StringDictionary deviceFolders; /// <summary> /// Initializes a new instance of the MobileCapableWebFormViewEngine class. /// </summary> public MobileCapableWebFormViewEngine() { this.deviceFolders = new StringDictionary { { "MSIE Mobile", "WindowsMobile" }, { "Mozilla", "iPhone" } }; } /// <summary> /// Get the "browser/folder" mapping dictionary. /// </summary> public StringDictionary DeviceFolders { get { return this.deviceFolders; } } /// <summary> /// Finds the view. /// </summary> /// <param name="controllerContext">The controller context.</param> /// <param name="viewName">Name of the view.</param> /// <param name="masterName">Name of the master.</param> /// <param name="useCache">if set to true [use cache].</param> /// <returns>The page view.</returns> public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) { ViewEngineResult result = null; HttpRequestBase request = controllerContext.HttpContext.Request; if (request.Browser.IsMobileDevice) { string mobileViewName = string.Empty; mobileViewName = GetMobileViewName(string.Concat("Mobile/", this.RetrieveDeviceFolderName(request.Browser.Browser)), viewName); result = this.ResolveView(controllerContext, mobileViewName, masterName, useCache); if (result == null || result.View == null) { mobileViewName = GetMobileViewName("Mobile", viewName); result = this.ResolveView(controllerContext, mobileViewName, masterName, useCache); } } if (result == null || result.View == null) { result = this.ResolveView(controllerContext, viewName, masterName, useCache); } return result; } private static string GetMobileViewName(string folderName, string viewName) { string[] viewParts = viewName.Split('/'); return string.Format("{0}/{1}/{2}", string.Join("/", viewParts.Take(viewParts.Length-1)), folderName, viewParts.Skip(viewParts.Length-1).First()); } protected virtual ViewEngineResult ResolveView(ControllerContext controllerContext, string viewName, string masterName, bool useCache) { return base.FindView(controllerContext, viewName, masterName, useCache); } /// <summary> /// Get the device folder associated with the name of the browser. /// </summary> /// <param name="browser">Name of the browser.</param> /// <returns>The associated folder name.</returns> private string RetrieveDeviceFolderName(string browser) { if (this.deviceFolders.ContainsKey(browser)) { return this.deviceFolders[browser.Trim()]; } else { return "unknown"; } } } }
using System; using System.Collections.Generic; using System.Text; namespace DesignPatterns.Bridge.Example1 { public class PlayView { public static void Run() { var artist = new Artist() { Bio = "Bio", Image = "image", Name = "Artist's name", Url = "http://aaa" }; View view = new LongForm(new ArtistResource(artist)); Client client = new Client(); client.ClientCode(view); } } }
namespace Fingo.Auth.Domain.Policies.Tests.Factories.Actions.Implementation { public class GetPoliciesFromProjectTest { } }
using System; using System.Globalization; using System.Runtime.InteropServices; using FontStashSharp; namespace Jypeli { /// <summary> /// Väri. /// </summary> [Save] public struct Color { /// <summary> /// Punainen värikomponentti välillä 0-255 /// </summary> [Save] public byte RedComponent; /// <summary> /// Vihreä värikomponentti välillä 0-255 /// </summary> [Save] public byte GreenComponent; /// <summary> /// Sininen värikomponentti välillä 0-255 /// </summary> [Save] public byte BlueComponent; /// <summary> /// Läpinäkymättömyys välillä 0-255 /// </summary> [Save] public byte AlphaComponent; /// <summary> /// Uusi väri /// </summary> /// <param name="red">Punainen värikomponentti välillä 0-255</param> /// <param name="green">Vihreä värikomponentti välillä 0-255</param> /// <param name="blue">Sininen värikomponentti välillä 0-255</param> public Color(byte red, byte green, byte blue) : this(red, green, blue, byte.MaxValue) { } /// <summary> /// Uusi väri /// </summary> /// <param name="red">Punainen värikomponentti välillä 0-255</param> /// <param name="green">Vihreä värikomponentti välillä 0-255</param> /// <param name="blue">Sininen värikomponentti välillä 0-255</param> /// <param name="alpha">Läpinäkymättömyys välillä 0-255</param> public Color(byte red, byte green, byte blue, byte alpha) { RedComponent = red; GreenComponent = green; BlueComponent = blue; AlphaComponent = alpha; } /// <summary> /// Uusi väri /// </summary> /// <param name="red">Punainen värikomponentti välillä 0-255</param> /// <param name="green">Vihreä värikomponentti välillä 0-255</param> /// <param name="blue">Sininen värikomponentti välillä 0-255</param> /// <param name="alpha">Läpinäkymättömyys välillä 0-255</param> public Color(int red, int green, int blue, int alpha) : this((byte)red, (byte)green, (byte)blue, (byte)alpha) { } /// <summary> /// Uusi väri /// </summary> /// <param name="red">Punainen värikomponentti välillä 0-255</param> /// <param name="green">Vihreä värikomponentti välillä 0-255</param> /// <param name="blue">Sininen värikomponentti välillä 0-255</param> public Color(int red, int green, int blue) : this((byte)red, (byte)green, (byte)blue, byte.MaxValue) { } /// <summary> /// Uusi väri aiemman pohjalta uudella läpinäkyvyydellä /// </summary> /// <param name="rgb">Väri</param> /// <param name="alpha">Läpinäkymättömyys välillä 0-255</param> public Color(Color rgb, byte alpha) : this(rgb.RedComponent, rgb.GreenComponent, rgb.BlueComponent, alpha) { } /// <summary> /// Uusi väri /// </summary> /// <param name="red">Punainen värikomponentti välillä 0-1.0</param> /// <param name="green">Vihreä värikomponentti välillä 0-1.0</param> /// <param name="blue">Sininen värikomponentti välillä 0-1.0</param> public Color(double red, double green, double blue) : this(red, green, blue, 1.0) { } /// <summary> /// Uusi väri /// </summary> /// <param name="red">Punainen värikomponentti välillä 0-1.0</param> /// <param name="green">Vihreä värikomponentti välillä 0-1.0</param> /// <param name="blue">Sininen värikomponentti välillä 0-1.0</param> /// <param name="alpha">Läpinäkymättömyys välillä 0-1.0</param> public Color(double red, double green, double blue, double alpha) : this((int)(red * 255), (int)(green * 255), (int)(blue * 255), (int)(alpha * 255)) { } /// <summary> /// Pakkaa kolme kokonaislukua väriä vastaavaksi kokonaisluvuksi /// </summary> /// <param name="r">värin punainen osuus (0-255)</param> /// <param name="g">värin vihreä osuus (0-255)</param> /// <param name="b">värin sininen osuus (0-255)</param> /// <param name="a">alpha-arvo (0-255)</param> /// <returns></returns> public static uint PackRGB(byte r, byte g, byte b, byte a = 255) { return (uint)((a << 24) | (r << 16) | (g << 8) | b); } /// <summary> /// Pakkaa kolme kokonaislukua väriä vastaavaksi kokonaisluvuksi /// </summary> /// <param name="r">värin punainen osuus (0-255)</param> /// <param name="g">värin vihreä osuus (0-255)</param> /// <param name="b">värin sininen osuus (0-255)</param> /// <param name="a">alpha-arvo (0-255)</param> /// <returns></returns> public static uint PackRGB(int r, int g, int b, int a = 255) { return (uint)((a << 24) | (r << 16) | (g << 8) | b); } /// <summary> /// Palauttaa heksakoodia vastaavan värin. /// </summary> /// <param name="hexString">Heksakoodi</param> /// <returns></returns> public static Color FromHexCode(string hexString) { if (hexString.StartsWith("#")) hexString = hexString.Substring(1); uint hex = uint.Parse(hexString, NumberStyles.HexNumber, CultureInfo.InvariantCulture); Color color = Color.White; if (hexString.Length == 8) { color.AlphaComponent = (byte)(hex >> 24); color.RedComponent = (byte)(hex >> 16); color.GreenComponent = (byte)(hex >> 8); color.BlueComponent = (byte)(hex); } else if (hexString.Length == 6) { color.RedComponent = (byte)(hex >> 16); color.GreenComponent = (byte)(hex >> 8); color.BlueComponent = (byte)(hex); } else { throw new InvalidOperationException("Invald hex representation of an ARGB or RGB color value."); } return color; } /// <summary> /// Antaa värin Paint.net -ohjelman paletista. /// </summary> /// <param name="row">Rivi (0-1)</param> /// <param name="col">Sarake (0-15)</param> /// <returns>Väri</returns> public static Color FromPaintDotNet(int row, int col) { if (row < 0 || row > 1 || col < 0 || col > 15) throw new ArgumentException("Row must be between 0 and 1 and column between 0 and 15."); Color[,] colors = { { Color.Black, Color.DarkGray, Color.Red, Color.Orange, Color.Gold, Color.YellowGreen, Color.Harlequin, Color.BrightGreen, Color.SpringGreen, Color.Cyan, Color.Azure, Color.PaintDotNetBlue, Color.HanPurple, Color.Violet, Color.PaintDotNetMagenta, Color.Rose }, { Color.White, Color.Gray, Color.DarkRed, Color.Brown, Color.Olive, Color.BrownGreen, Color.ForestGreen, Color.DarkForestGreen, Color.DarkJungleGreen, Color.DarkCyan, Color.DarkAzure, Color.DarkBlue, Color.MidnightBlue,Color.DarkViolet, Color.Purple, Color.BloodRed } }; return colors[row, col]; } /// <summary> /// Ottaa kokonaisluvusta alpha-arvon /// </summary> /// <param name="c">luku josta otetaan</param> /// <returns>Alpha-arvo</returns> public static byte GetAlpha(uint c) { return (byte)((c >> 24) & 0xff); } /// <summary> /// Ottaa kokonaisluvusta alpha-arvon /// </summary> /// <param name="c">luku josta otetaan</param> /// <returns>Alpha-arvo</returns> public static byte GetAlpha(int c) { return (byte)((c >> 24) & 0xff); } /// <summary> /// Ottaa kokonaisluvusta punaisen värin /// </summary> /// <param name="c">luku josta otetaan</param> /// <returns>punaisen osuus</returns> public static byte GetRed(uint c) { return (byte)((c >> 16) & 0xff); } /// <summary> /// Ottaa kokonaisluvusta vihreän värin /// </summary> /// <param name="c">luku josta otetaan</param> /// <returns>vihreän osuus</returns> public static byte GetGreen(uint c) { return (byte)((c >> 8) & 0xff); } /// <summary> /// Ottaa kokonaisluvusta sinisen värin /// </summary> /// <param name="c">luku josta otetaan</param> /// <returns>sinisen osuus</returns> public static byte GetBlue(uint c) { return (byte)((c >> 0) & 0xff); } /// <summary> /// Tekee kokonaisluvusta värin /// </summary> /// <param name="c">ARGB-arvon sisältävä kokonaisluku</param> /// <returns></returns> public static Color IntToColor(int c) { return new Color((byte)((c >> 16) & 0xff), (byte)((c >> 8) & 0xff), (byte)((c) & 0xff), (byte)((c >> 24) & 0xff)); } /// <summary> /// Tekee kokonaisluvusta värin /// </summary> /// <param name="c">ARGB-arvon sisältävä kokonaisluku</param> /// <returns></returns> public static Color UIntToColor(uint c) { return new Color((byte)((c >> 16) & 0xff), (byte)((c >> 8) & 0xff), (byte)((c) & 0xff), (byte)((c >> 24) & 0xff)); } /// <summary> /// Laskee kahden värin (euklidisen) etäisyyden RGB-väriavaruudessa. /// Värikomponentit ovat välillä 0-255 joten suurin mahdollinen etäisyys /// (musta ja valkoinen) on noin 441,68. /// </summary> /// <returns>Etäisyys</returns> public static double Distance(Color a, Color b) { double rd = Math.Pow(a.RedComponent - b.RedComponent, 2); double gd = Math.Pow(a.GreenComponent - b.GreenComponent, 2); double bd = Math.Pow(a.BlueComponent - b.BlueComponent, 2); return Math.Sqrt(rd + gd + bd); } /// <summary> /// Muuttaa värin ARGB-kokonaisluvuksi /// </summary> /// <returns></returns> public int ToInt() { return (AlphaComponent << 24) + (RedComponent << 16) + (GreenComponent << 8) + BlueComponent; } /// <summary> /// Muuttaa värin RGB-kokonaisluvuksi /// </summary> /// <returns></returns> public int ToIntRGB() { return (RedComponent << 16) + (GreenComponent << 8) + BlueComponent; } /// <summary> /// Muuttaa värin ARGB-kokonaisluvuksi /// </summary> /// <returns></returns> public uint ToUInt() { return (uint)ToInt(); } /// <summary> /// Palautetaan väri heksamerkkijonona /// </summary> /// <returns></returns> public override string ToString() { return ToString(true); } /// <summary> /// Palautetaan väri heksamerkkijonona. /// </summary> /// <param name="alpha">Otetaanko läpinäkyvyys mukaan (8 merkin heksakoodi)</param> /// <returns></returns> public string ToString(bool alpha) { if (alpha) return ToInt().ToString("X8"); return ToIntRGB().ToString("X6"); } /// <summary> /// Väri System.Drawing.Color tyyppinä /// </summary> /// <returns></returns> public System.Drawing.Color ToSystemDrawing() { return System.Drawing.Color.FromArgb(AlphaComponent, RedComponent, GreenComponent, BlueComponent); } internal FSColor ToFSColor() { return new FSColor(RedComponent, GreenComponent, BlueComponent, AlphaComponent); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member public static bool operator ==(Color c1, Color c2) { return c1.RedComponent == c2.RedComponent && c1.GreenComponent == c2.GreenComponent && c1.BlueComponent == c2.BlueComponent && c1.AlphaComponent == c2.AlphaComponent; } public static bool operator ==(Color c1, uint i2) { return c1.ToUInt() == i2; } public static bool operator !=(Color c1, uint i2) { return c1.ToUInt() != i2; } public static bool operator ==(Color c1, int i2) { return c1.ToUInt() == (uint)i2; } public static bool operator !=(Color c1, int i2) { return c1.ToUInt() != (uint)i2; } public override int GetHashCode() { return ToInt(); } public override bool Equals(Object c2) { if (c2 is Color) return this == (Color)c2; if (c2 is uint) return this == (uint)c2; if (c2 is int) return this == (uint)c2; return false; } public static bool operator !=(Color c1, Color c2) { return !(c1 == c2); } /// <summary> /// Lineaarinen interpolaatio värien välillä /// </summary> /// <param name="value1"></param> /// <param name="value2"></param> /// <param name="amount"></param> /// <returns></returns> public static Color Lerp(Color value1, Color value2, double amount) { float x = (float)MathHelper.Clamp(amount, 0, 1); return new Color( (byte)MathHelper.Lerp(value1.RedComponent, value2.RedComponent, x), (byte)MathHelper.Lerp(value1.GreenComponent, value2.GreenComponent, x), (byte)MathHelper.Lerp(value1.BlueComponent, value2.BlueComponent, x), (byte)MathHelper.Lerp(value1.AlphaComponent, value2.AlphaComponent, x)); } internal System.Numerics.Vector4 ToNumerics() { return new System.Numerics.Vector4(RedComponent / 255f, GreenComponent / 255f, BlueComponent / 255f, AlphaComponent / 255f); } /// <summary> /// Antaa tummemman värin. Vähentaa jokaista kolmea osaväriä arvon <c>howMuch</c> /// verran. /// </summary> /// <param name="c">Alkuperäinen väri.</param> /// <param name="howMuch">Kuinka paljon tummempi (positiivinen luku).</param> /// <returns>Tummempi väri.</returns> public static Color Darker(Color c, int howMuch) { int r = (int)c.RedComponent - howMuch; int g = (int)c.GreenComponent - howMuch; int b = (int)c.BlueComponent - howMuch; if (r < 0) r = 0; if (g < 0) g = 0; if (b < 0) b = 0; return new Color((byte)r, (byte)g, (byte)b, c.AlphaComponent); } /// <summary> /// Antaa kirkkaamman värin. Kasvattaa jokaista kolmea osaväriä arvon <c>howMuch</c> /// verran. /// </summary> /// <param name="c">Alkuperäinen väri.</param> /// <param name="howMuch">Kuinka paljon vaaleampi.</param> /// <returns>Vaaleampi väri.</returns> public static Color Lighter(Color c, int howMuch) { int r = (int)c.RedComponent + howMuch; int g = (int)c.GreenComponent + howMuch; int b = (int)c.BlueComponent + howMuch; if (r > byte.MaxValue) r = byte.MaxValue; if (g > byte.MaxValue) g = byte.MaxValue; if (b > byte.MaxValue) b = byte.MaxValue; return new Color((byte)r, (byte)g, (byte)b, c.AlphaComponent); } /// <summary> /// Sekoittaa kahta tai useampaa väriä. /// </summary> /// <param name="colors">Värit parametreina.</param> /// <returns>Sekoitettu väri</returns> public static Color Mix(params Color[] colors) { if (colors.Length == 0) throw new ArgumentException("Color.Average needs at least one argument"); double[] sums = new double[4]; for (int i = 0; i < colors.Length; i++) { sums[0] += colors[i].RedComponent / 255.0; sums[1] += colors[i].GreenComponent / 255.0; sums[2] += colors[i].BlueComponent / 255.0; sums[3] += colors[i].AlphaComponent / 255.0; } return new Color( sums[0] / colors.Length, sums[1] / colors.Length, sums[2] / colors.Length, sums[3] / colors.Length ); } /// <summary> /// Tuhkanharmaa. /// </summary> public static readonly Color AshGray = new Color(178, 190, 181, 255); /// <summary> /// Vedensininen. /// </summary> public static readonly Color Aqua = new Color(0, 255, 255, 255); /// <summary> /// Akvamariini. /// </summary> public static readonly Color Aquamarine = new Color(127, 255, 212, 255); /// <summary> /// Asuurinsininen. /// </summary> public static readonly Color Azure = new Color(0, 148, 255, 255); /// <summary> /// Beessi. /// </summary> public static readonly Color Beige = new Color(245, 245, 220, 255); /// <summary> /// Musta. /// </summary> public static readonly Color Black = new Color(0, 0, 0, 255); /// <summary> /// Verenpunainen. /// </summary> public static readonly Color BloodRed = new Color(127, 0, 55, 255); /// <summary> /// Sininen. /// </summary> public static readonly Color Blue = new Color(0, 0, 255, 255); /// <summary> /// Siniharmaa. /// </summary> public static readonly Color BlueGray = new Color(102, 153, 204, 255); /// <summary> /// Kirkkaan vihreä. /// </summary> public static readonly Color BrightGreen = new Color(0, 255, 33, 255); /// <summary> /// Ruskea. /// </summary> public static readonly Color Brown = new Color(127, 51, 0, 255); /// <summary> /// Ruskeanvihreä. /// </summary> public static readonly Color BrownGreen = new Color(91, 127, 0, 255); /// <summary> /// Karmiininpunainen. /// </summary> public static readonly Color Crimson = new Color(220, 20, 60, 255); /// <summary> /// Syaani. /// </summary> public static readonly Color Cyan = new Color(0, 255, 255, 255); /// <summary> /// Hiilenmusta. /// </summary> public static readonly Color Charcoal = new Color(54, 69, 79, 255); /// <summary> /// Tumma asuuri. /// </summary> public static readonly Color DarkAzure = new Color(0, 74, 127, 255); /// <summary> /// Tumma ruskea. /// </summary> public static readonly Color DarkBrown = new Color(92, 64, 51, 255); /// <summary> /// Tumma sininen. /// </summary> public static readonly Color DarkBlue = new Color(0, 19, 127, 255); /// <summary> /// Tumma syaani. /// </summary> public static readonly Color DarkCyan = new Color(0, 127, 127, 255); /// <summary> /// Tumma metsänvihreä. /// </summary> public static readonly Color DarkForestGreen = new Color(0, 127, 14); /// <summary> /// Tumma harmaa. /// </summary> public static readonly Color DarkGray = new Color(64, 64, 64, 255); /// <summary> /// Tumma vihreä. /// </summary> public static readonly Color DarkGreen = new Color(0, 100, 0, 255); /// <summary> /// Tumma viidakonvihreä. /// </summary> public static readonly Color DarkJungleGreen = new Color(0, 127, 70, 255); /// <summary> /// Tumma oranssi / ruskea. /// </summary> public static readonly Color DarkOrange = Color.Brown; /// <summary> /// Tumma punainen. /// </summary> public static readonly Color DarkRed = new Color(127, 0, 0, 255); /// <summary> /// Tumma turkoosi. /// </summary> public static readonly Color DarkTurquoise = new Color(0, 206, 209, 255); /// <summary> /// Tumma violetti. /// </summary> public static readonly Color DarkViolet = new Color(87, 0, 127, 255); /// <summary> /// Tumma keltainen (oliivi). /// </summary> public static readonly Color DarkYellow = Color.Olive; /// <summary> /// Tumma keltavihreä (ruskeanvihreä). /// </summary> public static readonly Color DarkYellowGreen = Color.BrownGreen; /// <summary> /// Smaragdinvihreä. /// </summary> public static readonly Color Emerald = new Color(80, 200, 120, 255); /// <summary> /// Metsänvihreä. /// </summary> public static readonly Color ForestGreen = new Color(38, 127, 0); /// <summary> /// Fuksia (pinkki) /// </summary> public static readonly Color Fuchsia = new Color(255, 0, 255, 255); /// <summary> /// Kulta. /// </summary> public static readonly Color Gold = new Color(255, 216, 0, 255); /// <summary> /// Harmaa. /// </summary> public static readonly Color Gray = new Color(128, 128, 128, 255); /// <summary> /// Vihreä. /// </summary> public static readonly Color Green = new Color(0, 128, 0, 255); /// <summary> /// Keltavihreä. /// </summary> public static readonly Color GreenYellow = new Color(173, 255, 47, 255); /// <summary> /// Sinipurppurainen väri Han-dynastian ajoilta. /// </summary> public static readonly Color HanPurple = new Color(72, 0, 255, 255); /// <summary> /// Harlekiini (hieman keltaisella sävytetty kirkas vihreä). /// </summary> public static readonly Color Harlequin = new Color(76, 255, 0, 255); /// <summary> /// Pinkki. /// </summary> public static readonly Color HotPink = new Color(255, 105, 180, 255); /// <summary> /// Norsunluu. /// </summary> public static readonly Color Ivory = new Color(255, 255, 240, 255); /// <summary> /// Viidakonvihreä. /// </summary> public static readonly Color JungleGreen = new Color(41, 171, 135, 255); /// <summary> /// Laventeli. /// </summary> public static readonly Color Lavender = new Color(220, 208, 255, 255); /// <summary> /// Vaalea sininen. /// </summary> public static readonly Color LightBlue = new Color(173, 216, 230, 255); /// <summary> /// Vaalea syaani. /// </summary> public static readonly Color LightCyan = new Color(224, 255, 255, 255); /// <summary> /// Vaalea harmaa. /// </summary> public static readonly Color LightGray = new Color(211, 211, 211, 255); /// <summary> /// Vaalea vihreä. /// </summary> public static readonly Color LightGreen = new Color(144, 238, 144, 255); /// <summary> /// Vaalea vaaleanpunainen. /// </summary> public static readonly Color LightPink = new Color(255, 182, 193, 255); /// <summary> /// Vaalea keltainen. /// </summary> public static readonly Color LightYellow = new Color(255, 255, 224, 255); /// <summary> /// Limetti. /// </summary> public static readonly Color Lime = new Color(0, 255, 0, 255); /// <summary> /// Limetinvihreä. /// </summary> public static readonly Color LimeGreen = new Color(50, 205, 50, 255); /// <summary> /// Magenta (pinkki) /// </summary> public static readonly Color Magenta = new Color(255, 0, 255, 255); /// <summary> /// Viininpunainen. /// </summary> public static readonly Color Maroon = new Color(128, 0, 0, 255); /// <summary> /// Tummahko sininen. /// </summary> public static readonly Color MediumBlue = new Color(0, 0, 205, 255); /// <summary> /// Tummahko purppura. /// </summary> public static readonly Color MediumPurple = new Color(147, 112, 219, 255); /// <summary> /// Tummahko turkoosi. /// </summary> public static readonly Color MediumTurquoise = new Color(72, 209, 204, 255); /// <summary> /// Tummahko punavioletti. /// </summary> public static readonly Color MediumVioletRed = new Color(199, 21, 133, 255); /// <summary> /// Keskiyön sininen. /// </summary> public static readonly Color MidnightBlue = new Color(33, 0, 127, 255); /// <summary> /// Mintunvihreä. /// </summary> public static readonly Color Mint = new Color(62, 180, 137, 255); /// <summary> /// Laivastonsininen. /// </summary> public static readonly Color Navy = new Color(0, 0, 128, 255); /// <summary> /// Oliivi (tumma keltainen). /// </summary> public static readonly Color Olive = new Color(127, 106, 0, 255); /// <summary> /// Oranssi. /// </summary> public static readonly Color Orange = new Color(255, 106, 0, 255); /// <summary> /// Punaoranssi. /// </summary> public static readonly Color OrangeRed = new Color(255, 69, 0, 255); /// <summary> /// Paint.NETin sininen väri. /// </summary> public static readonly Color PaintDotNetBlue = new Color(0, 38, 255, 255); /// <summary> /// Paint.NETin magenta (pinkki) väri. /// </summary> public static readonly Color PaintDotNetMagenta = new Color(255, 0, 220, 255); /// <summary> /// Vaaleanpunainen. /// </summary> public static readonly Color Pink = new Color(255, 192, 203, 255); /// <summary> /// Purppura. /// </summary> public static readonly Color Purple = new Color(127, 0, 110, 255); /// <summary> /// Tumma magenta (purppura). /// </summary> public static readonly Color DarkMagenta = Color.Purple; /// <summary> /// Punainen. /// </summary> public static readonly Color Red = new Color(255, 0, 0, 255); /// <summary> /// Rose (punainen). /// </summary> public static readonly Color Rose = new Color(255, 0, 110, 255); /// <summary> /// Rose-pinkki. /// </summary> public static readonly Color RosePink = new Color(251, 204, 231, 255); /// <summary> /// Rubiininpunainen. /// </summary> public static readonly Color Ruby = new Color(224, 17, 95, 255); /// <summary> /// Lohenpunainen. /// </summary> public static readonly Color Salmon = new Color(250, 128, 114, 255); /// <summary> /// Merensininen. /// </summary> public static readonly Color SeaGreen = new Color(46, 139, 87, 255); /// <summary> /// Hopea. /// </summary> public static readonly Color Silver = new Color(192, 192, 192, 255); /// <summary> /// Taivaansininen. /// </summary> public static readonly Color SkyBlue = new Color(135, 206, 235, 255); /// <summary> /// Saviliuskeensininen. /// </summary> public static readonly Color SlateBlue = new Color(106, 90, 205, 255); /// <summary> /// Saviliuskeenharmaa. /// </summary> public static readonly Color SlateGray = new Color(112, 128, 144, 255); /// <summary> /// Lumenvalkoinen. /// </summary> public static readonly Color Snow = new Color(255, 250, 250, 255); /// <summary> /// Kevään vihreä. /// </summary> public static readonly Color SpringGreen = new Color(0, 255, 144, 255); /// <summary> /// Sinivihreä. /// </summary> public static readonly Color Teal = new Color(0, 128, 128, 255); /// <summary> /// Läpinäkyvä väri. /// </summary> public static readonly Color Transparent = new Color(0, 0, 0, 0); /// <summary> /// Turkoosi. /// </summary> public static readonly Color Turquoise = new Color(64, 224, 208, 255); /// <summary> /// Ultramariini (tumma sininen). /// </summary> public static readonly Color Ultramarine = new Color(18, 10, 143, 255); /// <summary> /// Violetti. /// </summary> public static readonly Color Violet = new Color(178, 0, 255, 255); /// <summary> /// Luonnonvalkoinen. /// </summary> public static readonly Color Wheat = new Color(245, 222, 179, 255); /// <summary> /// Valkoinen. /// </summary> public static readonly Color White = new Color(255, 255, 255, 255); /// <summary> /// Keltainen. /// </summary> public static readonly Color Yellow = new Color(255, 255, 0, 255); /// <summary> /// Keltavihreä. /// </summary> public static readonly Color YellowGreen = new Color(182, 255, 0, 255); } }
using System; using System.Collections.Generic; using System.Text; namespace CommandLineArgumentsParser { [AttributeUsage( AttributeTargets.Property, AllowMultiple=false, Inherited=false) ] public class CommandLineOptionAttribute : Attribute { private bool m_required = false; private Type m_parser; public CommandLineOptionAttribute(Type parser) { if (!typeof(ICommandLineTokenParser).IsAssignableFrom(parser)) { string message = "Invalid command line token parsers type provided " + "(must implement ICommandLineTokenParser interface)"; throw new ArgumentException(message, "parser"); } if(parser.GetConstructor(new Type[0]) == null) { string message = String.Format("Parser type {0} must have a default constructor", parser.FullName); throw new ArgumentException(message, "parser"); } this.m_parser = parser; } public bool Required { get { return m_required; } set { m_required = value; } } public Type Parser { get { return m_parser; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace StartMVC.ViewModels { public class ContactFormViewModel { } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class Panel_LevelNoteInfo { public Sprite Image_SceneImage; public string Text_SceneIntroduce; } public class Panel_LevelNote : BasePanel { public Button Button_EnterBattleScene; public void Init(string levelName) { SetInfos(levelName); SetBtnEvent(levelName); } private void Start() { GetControl<Button>("ExitArea").onClick.AddListener(() => { GetComponent<Animator>().Play("hide"); try { Invoke("HideThis", 2f); } catch { Debug.Log("Bug"); } }); } private void SetBtnEvent(string levelName) { Button_EnterBattleScene.onClick.AddListener(() => { List<EnemyInfo> enemyInfos = null; LevelAward levelAward = null; //GetControl<Button>("Button_EnterBattleScene").gameObject.GetComponent<Image>().color = new Color(0, 0, 0); try { try { enemyInfos = GameConfig.GetInstance().GetEnemyInfos(levelName); levelAward = GameConfig.GetInstance().GetAwards(levelName); } catch { Debug.Log("This"); } PlayerInfo playerInfo = PlayerModelController.GetInstance().GetPlayerInfo(); SceneLoadSvc.GetInstance().LoadSceneWithFX("BattleScene", () => { EventCenter.GetInstance().EventTrigger(EventDic.HideBottomMenu); BattleSys.GetInstance().Init(playerInfo, enemyInfos, levelAward); //HideThis(); try { GetComponent<Animator>().Play("hide"); } catch { Debug.Log("bug"); } }); } catch { } }); } private void Update() { //if (Input.GetKeyDown(KeyCode.D)) //{ // Button_EnterBattleScene.onClick.Invoke(); //} if(SceneManager.GetActiveScene().name!= "MainMenu") { HideThis(); Destroy(this.gameObject); Debug.Log("haha"); } } public void HideThis() { UIManager.GetInstance().HidePanel("Panel_LevelNote"); } private void SetInfos(string levelName) { var info = GameConfig.GetInstance().GetLevelNoteInfo(levelName); GetControl<Image>("Image_SceneImage").sprite =info.Image_SceneImage; GetControl<Text>("Text_SceneIntroduce").text =info.Text_SceneIntroduce; //throw new NotImplementedException(); } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using Microsoft.AspNet.Identity; using SciVacancies.WebApp.Models; using SciVacancies.WebApp.ViewModels.Base; namespace SciVacancies.WebApp.ViewModels { public class ResearcherEditViewModel: PageViewModelBase { public int ExtNumber { get; set; } [Required(ErrorMessage = "Необходимо заполнить Имя")] [MaxLength(1500, ErrorMessage = "Длина строки не более 1500 символов")] public string FirstName { get; set; } [Required(ErrorMessage = "Необходимо заполнить Фамилию")] [MaxLength(1500, ErrorMessage = "Длина строки не более 1500 символов")] public string SecondName { get; set; } [MaxLength(1500, ErrorMessage = "Длина строки не более 1500 символов")] public string Patronymic { get; set; } [Required(ErrorMessage = "Необходимо заполнить Имя на английском")] [MaxLength(1500, ErrorMessage = "Длина строки не более 1500 символов")] public string FirstNameEng { get; set; } [Required(ErrorMessage = "Необходимо заполнить Фамилию на английском")] [MaxLength(1500, ErrorMessage = "Длина строки не более 1500 символов")] public string SecondNameEng { get; set; } [MaxLength(1500, ErrorMessage = "Длина строки не более 1500 символов")] public string PatronymicEng { get; set; } [MaxLength(1500, ErrorMessage = "Длина строки не более 1500 символов")] public string PreviousSecondName { get; set; } [MaxLength(1500, ErrorMessage = "Длина строки не более 1500 символов")] public string PreviousSecondNameEng { get; set; } //public DateTime BirthDate { get; set; } [Required(ErrorMessage = "Требуется выбрать год рождения")] public int BirthYear { get; set; } [Required(ErrorMessage = "Укажите E-mail")] [EmailAddress(ErrorMessage = "Поле E-mail содержит не допустимый адрес электронной почты.")] public string Email { get; set; } [Required(ErrorMessage = "Укажите номер телефона")] [Phone(ErrorMessage = "Поле Телефон содержит не допустимый номер телефона.")] [MaxLength(1500, ErrorMessage = "Длина строки не более 1500 символов")] public string Phone { get; set; } [Phone(ErrorMessage = "Поле Телефон содержит не допустимый номер телефона.")] [MaxLength(1500, ErrorMessage = "Длина строки не более 1500 символов")] public string ExtraPhone { get; set; } [MaxLength(1500, ErrorMessage = "Длина строки не более 1500 символов")] public string ScienceDegree { get; set; } [MaxLength(1500, ErrorMessage = "Длина строки не более 1500 символов")] public string ScienceRank { get; set; } public List<RewardEditViewModel> Rewards { get; set; } = new List<RewardEditViewModel>(); public List<MembershipEditViewModel> Memberships { get; set; } = new List<MembershipEditViewModel>(); public List<ConferenceEditViewModel> Conferences { get; set; } = new List<ConferenceEditViewModel>(); public List<EducationEditViewModel> Educations { get; set; } = new List<EducationEditViewModel>(); public List<PublicationEditViewModel> Publications { get; set; } = new List<PublicationEditViewModel>(); public List<InterestEditViewModel> Interests { get; set; } = new List<InterestEditViewModel>(); public List<ActivityEditViewModel> ResearchActivity { get; set; } = new List<ActivityEditViewModel>(); public List<ActivityEditViewModel> TeachingActivity { get; set; } = new List<ActivityEditViewModel>(); public List<ActivityEditViewModel> OtherActivity { get; set; } = new List<ActivityEditViewModel>(); public IList<UserLoginInfo> Logins { get; set; } public bool IsScienceMapUser { get { return Logins != null && Logins.Any(c => c.LoginProvider == ConstTerms.LoginProviderScienceMap); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Cryptography; using System.IO; using System.Text; using System.Globalization; using System.Data; using System.Data.SqlClient; namespace TYNMU.Data { public class DAO { public static int NonQuery(string sSql) { string ConStr = "Server=.;Trusted_Connection=true;DataBase=TynCompany"; SqlConnection conn = new SqlConnection(); conn.ConnectionString = ConStr; conn.Open(); SqlCommand comm = new SqlCommand(sSql, conn); int iRet=comm.ExecuteNonQuery(); conn.Close(); return iRet; } public static DataSet Query(string sSql) { string ConStr = "Server=.;Trusted_Connection=true;DataBase=TynCompany"; SqlConnection conn = new SqlConnection(); conn.ConnectionString = ConStr; conn.Open(); SqlDataAdapter adapter = new SqlDataAdapter(sSql, conn); DataSet ds = new DataSet(); adapter.Fill(ds); conn.Close(); return ds; } public static string GetMD5(string strPwd) { string pwd = ""; //实例化一个md5对象 MD5 md5 = MD5.Create(); // 加密后是一个字节类型的数组 byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(strPwd)); //翻转生成的MD5码 s.Reverse(); //通过使用循环,将字节类型的数组转换为字符串,此字符串是常规字符格式化所得 //只取MD5码的一部分,这样恶意访问者无法知道取的是哪几位 for (int i = 3; i < s.Length - 1; i++) { //将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母,如果使用大写(X)则格式后的字符是大写字符 //进一步对生成的MD5码做一些改造 pwd = pwd + (s[i] < 198 ? s[i] + 28 : s[i]).ToString("X"); } return pwd; } } }
using System; using Automatonymous; using Meetup.Sagas.Contracts; namespace Meetup.Sagas.BackendCartService { public class ShoppingCartSaga : MassTransitStateMachine<ShoppingCart> { public ShoppingCartSaga() { this.InstanceState(x => x.CurrentState); this.Event(() => this.ItemAdded, x => x.CorrelateBy(cart => cart.UserName, context => context.Message.Username) .SelectId(context => Guid.NewGuid())); this.Event(() => this.CheckedOut, x => x.CorrelateBy((cart, context) => cart.UserName == context.Message.Username)); this.Schedule(() => this.CartExpired, x => x.ExpirationId, x => { x.Delay = TimeSpan.FromSeconds(10); x.Received = e => e.CorrelateById(context => context.Message.CartId); }); this.Initially( this.When(this.ItemAdded) .Then(context => { context.Instance.Created = context.Data.Timestamp; context.Instance.Updated = context.Data.Timestamp; context.Instance.UserName = context.Data.Username; }) .ThenAsync( context => Console.Out.WriteLineAsync( $"Created new saga: {context.Data.Username}, {context.Data.Timestamp}")) .Schedule(this.CartExpired, context => new CartExpiredEvent(context.Instance)) .TransitionTo(this.Active)); this.During(this.Active, this.When(this.ItemAdded) .Then(context => { if (context.Data.Timestamp > context.Instance.Updated) { context.Instance.Updated = context.Data.Timestamp; } }) .ThenAsync(context => Console.Out.WriteLineAsync($"Updating saga with added item {context.Data.Timestamp}")) //.Unschedule(this.CartExpired) .Schedule(this.CartExpired, context => new CartExpiredEvent(context.Instance)), this.When(this.CheckedOut) .Then(context => { if (context.Data.Timestamp > context.Instance.Updated) { context.Instance.Updated = context.Data.Timestamp; } }) .ThenAsync(context => Console.Out.WriteLineAsync($"Completing with checkout cart, {context.Data.Timestamp}")) .Unschedule(this.CartExpired) .Finalize(), this.When(this.CartExpired.Received) .ThenAsync(context => Console.Out.WriteLineAsync("Received expired event!")) .Publish(context => new ShowSadPuppyCommand(context.Instance.UserName)) //.TransitionTo(this.Expired) .Finalize() ); this.SetCompletedWhenFinalized(); } public State Active { get; private set; } public State Expired { get; private set; } // + 2 состояние - Initial и Completed public Event<ItemAdded> ItemAdded { get; private set; } public Event<CheckedOut> CheckedOut { get; private set; } public Schedule<ShoppingCart, CartExpired> CartExpired { get; private set; } } }
using OperatingSystem = Sentry.Protocol.OperatingSystem; namespace Sentry.Android.Extensions; internal static class OperatingSystemExtensions { public static void ApplyFromAndroidRuntime(this OperatingSystem operatingSystem) { operatingSystem.Name ??= "Android"; operatingSystem.Version ??= AndroidBuild.VERSION.Release; operatingSystem.Build ??= AndroidBuild.Display; if (operatingSystem.KernelVersion == null) { // ex: "Linux 5.10.98-android13-0-00003-g6ea688a79989-ab8162051 #1 SMP PREEMPT Tue Feb 8 00:20:26 UTC 2022" var osParts = RuntimeInformation.OSDescription.Split(' '); if (osParts.Length >= 2 && osParts[1].Contains("android", StringComparison.OrdinalIgnoreCase)) { // ex: "5.10.98-android13-0-00003-g6ea688a79989-ab8162051" operatingSystem.KernelVersion = osParts[1]; } } // operatingSystem.RawDescription is already set in Enricher.cs } public static void ApplyFromSentryAndroidSdk(this OperatingSystem operatingSystem, JavaSdk.Protocol.OperatingSystem os) { // We already have everything above, except the Rooted flag. // The Android SDK figures this out in RootChecker.java // TODO: Consider porting the Java root checker to .NET. We probably have access to all the same information. // https://github.com/getsentry/sentry-java/blob/main/sentry-android-core/src/main/java/io/sentry/android/core/internal/util/RootChecker.java operatingSystem.Rooted ??= os.IsRooted()?.BooleanValue(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TfsMobile.Repositories.v1 { class TfsUserHelper { } }
using System; using Microsoft.AspNetCore.Mvc; using WebApi.ViewModels; using Microsoft.AspNetCore.Authorization; using WebApi.BusinessLogic; namespace WebApi.Controllers { [Route("api/[controller]")] [ApiController] public class AccountsModelsController : ControllerBase { private readonly AccountsRequestHundler _accountsModelsRequestHundler; public AccountsModelsController(AccountsRequestHundler accountsModelsRequestHundler) { _accountsModelsRequestHundler = accountsModelsRequestHundler; } // GET: api/AccountsModels/5 [Authorize] [HttpGet("{id}")] public IActionResult GetAccountsModel([FromRoute] Guid id) { return _accountsModelsRequestHundler.GetAccounts(id); } // POST: api/AccountsModels [Authorize] [HttpPost] public IActionResult PostAccountsModel([FromBody] AccountsModel accountsModel) { return _accountsModelsRequestHundler.CreateAccount(accountsModel); } // DELETE: api/AccountsModels/5 [Authorize] [HttpDelete("{id}")] public IActionResult DeleteAccountsModel([FromRoute] Guid id) { return _accountsModelsRequestHundler.CloseAccount(id); } } }
using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using MyCollection.Models; using MyCollection.UnitOfWork; namespace MyCollection.Controllers { [Route("api/v1/[controller]")] [ApiController] public class ItensController : ControllerBase { IUnitOfWork unitOfWork; public ItensController(IUnitOfWork unitOfWork) { this.unitOfWork = unitOfWork; } //api/Itens [HttpGet] public IList<Itens> Get() { return this.unitOfWork.ItensRepository.FindAll().OrderByDescending(x => x.Id).ToList(); } //api/Itens/6 [HttpGet("{id}")] public Itens Get(int id) { return this.unitOfWork.ItensRepository.FindById(id); } //api/Itens [HttpPost] public ActionResult<Itens> Post([FromBody] Itens value) { value.Loan = false; value.Vinculo = null; this.unitOfWork.ItensRepository.Add(value); this.unitOfWork.Save(); return value; } //api/Itens/Alugar [HttpPost("Alugar")] public ActionResult<Vinculo> PostAlugar([FromBody] Vinculo value) { var itemInDb = this.unitOfWork.ItensRepository.FindById(value.Itens.Id); value.Itens = itemInDb; var userInDb = this.unitOfWork.UserRepository.FindById(value.User.Id); value.User = userInDb; if (value.Itens.Id > 0 && value.Itens.Loan == false && value.User.Id > 0) { itemInDb.Loan = true; this.unitOfWork.VinculoRepository.Add(value); this.unitOfWork.Save(); return Ok(); } return BadRequest(); } //api/Itens/Devolver/6 [HttpPost("Devolver/{id}")] public ActionResult<Vinculo> PostDevolver(int id, [FromBody] Vinculo value) { var vinculo = this.unitOfWork.VinculoRepository.FindById(id); var itemInDb = this.unitOfWork.ItensRepository.FindById(value.Itens.Id); value.Itens = itemInDb; var userInDb = this.unitOfWork.UserRepository.FindById(value.User.Id); value.User = userInDb; if (value.Itens.Id > 0 && value.Itens.Loan == true && value.User.Id > 0) { value.Itens.Loan = false; value.Itens.Vinculo = null; value.User.Vinculo = null; this.unitOfWork.VinculoRepository.Remove(vinculo); this.unitOfWork.Save(); return Ok(); } return BadRequest(); } //api/Itens/6 [HttpPut("{id}")] public Itens Put(int id, [FromBody] Itens value) { var itensInDb = this.unitOfWork.ItensRepository.FindById(id); itensInDb.Name = value.Name; itensInDb.Loan = false; itensInDb.Type = value.Type; itensInDb.Vinculo = null; if (value.Id > 0) { this.unitOfWork.ItensRepository.Add(itensInDb); this.unitOfWork.Save(); } return itensInDb; } //api/Itens/6 [HttpDelete("{id}")] public Itens Delete(int id) { var itemInDb = this.unitOfWork.ItensRepository.FindById(id); this.unitOfWork.ItensRepository.Remove(itemInDb); this.unitOfWork.Save(); return itemInDb; } } }
using System; using System.IO; using NHibernate; using NHibernate.Cfg; namespace Gourmet.Models.NHibernate { // Класс для соединения с базой // Используем, когда нужны не только стандартные get/list/save/update // Либо когда нужно подключение к нескольким таблицам по очереди public class DbOperator { private ISessionFactory SessionFactory; public ISession Session; public DbOperator() { Configuration Cfg = new Configuration(); Cfg.Configure(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "hibernate.cfg.xml")); this.SessionFactory = Cfg.BuildSessionFactory(); this.Session = this.SessionFactory.OpenSession(); } public void Close() { this.Session.Close(); this.SessionFactory.Close(); } } }
using System; using Microsoft.Xna.Framework.Input; using StardewModdingAPI; namespace MovementMod.Framework { /// <summary>The mod configuration.</summary> internal class ModConfig { /********* ** Accessors *********/ /// <summary>The player speed to add when running (or 0 for no change).</summary> public int PlayerRunningSpeed { get; set; } = 5; /// <summary>The player speed to add when riding the horse (or 0 for no change).</summary> public int HorseSpeed { get; set; } = 5; /// <summary>The key which causes the player to sprint.</summary> public string SprintKey { get; set; } = "LeftShift"; /// <summary>The multiplier applied to the player speed when sprinting.</summary> public int PlayerSprintingSpeedMultiplier { get; set; } = 2; /// <summary>The stamina drain each second while sprinting.</summary> public float SprintingStaminaDrainPerSecond { get; set; } = 15; /********* ** Public methods *********/ public Keys GetSprintKey(IMonitor monitor) { if (Enum.TryParse(this.SprintKey, out Keys key)) { monitor.Log($"Bound key '{key}' for sprinting."); return key; } monitor.Log($"Failed to find specified key '{this.SprintKey}', using default 'LeftShift' for sprinting.", LogLevel.Warn); return Keys.LeftShift; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using TableroComando.Dominio; using Dominio; using TableroComando.GUIWrapper; using Repositorios; using TableroComando.Clases; using Repositorios; using Dataweb.NShape; using Dataweb.NShape.Advanced; using Dataweb.NShape.GeneralShapes; using Dataweb.NShape.Layouters; namespace TableroComando.Formularios { public partial class Form_InformeGeneral : Form { IList<Perspectiva> ListaPerspectiva; public Form_InformeGeneral(IList<Perspectiva> ListaPerspectiva) { this.ListaPerspectiva = ListaPerspectiva; InitializeComponent(); } private void BtnGenerarReporte_Click(object sender, EventArgs e) { Diagram diagram = new Diagram("D1"); //Project project = new Project(); //XmlStore xml = new XmlStore(); diagram = Clases.MapaEstrategico.CrearMapa(project1, diagram, xmlStore1); Image ImageMapa = diagram.CreateImage(ImageFileFormat.Png); ImageMapa.Save( Application.StartupPath + "\\TempMapa.png", System.Drawing.Imaging.ImageFormat.Png); ImageMapa = Clases.Herramientas.resizeImage(650, 600, Application.StartupPath + "\\TempMapa.png"); ImageMapa.Save(Application.StartupPath + "\\TempMapa1.png", System.Drawing.Imaging.ImageFormat.Png); Reportes.DSPerspectiva DsPerspectiva = new Reportes.DSPerspectiva(); // Cargo el Mapa DataRow FilaMapa = DsPerspectiva.Tables["Mapa"].NewRow(); FilaMapa["Mapa"] = Clases.Herramientas.ConversionImagen(Application.StartupPath + "\\TempMapa1.png"); DsPerspectiva.Tables["Mapa"].Rows.Add(FilaMapa); DsPerspectiva.Tables["Mapa"].AcceptChanges(); // Restricciones IList<RestriccionObjetivo> restriccionesObj = RestriccionGeneralRepository.Instance.All<RestriccionObjetivo>(); IList<RestriccionPerspectiva> restriccionesPersp = RestriccionGeneralRepository.Instance.All<RestriccionPerspectiva>(); // Cargo el responsable IList<Responsable> ListaResponsable = ResponsableRepository.Instance.All(); foreach (Responsable Responsable in ListaResponsable) { DataRow FilaResponsable = DsPerspectiva.Tables["responsables"].NewRow(); FilaResponsable["Id"] = Responsable.Id; FilaResponsable["Area"] = Responsable.Area; FilaResponsable["Persona"] = Responsable.Persona; FilaResponsable["Codigo"] = Responsable.Codigo; DsPerspectiva.Tables["responsables"].Rows.Add(FilaResponsable); } DsPerspectiva.Tables["responsables"].AcceptChanges(); // Cargo la Frecuencia IList<Frecuencia> ListaFrecuencias = FrecuenciaRepository.Instance.All(); foreach (Frecuencia Frecuencia in ListaFrecuencias) { DataRow FilaFrecuencia = DsPerspectiva.Tables["frecuencias"].NewRow(); FilaFrecuencia["Id"] = Frecuencia.Id; FilaFrecuencia["Periodo"] = Frecuencia.Periodo; DsPerspectiva.Tables["frecuencias"].Rows.Add(FilaFrecuencia); } DsPerspectiva.Tables["frecuencias"].AcceptChanges(); // Cargo la perspectiva foreach (Perspectiva Perspectiva in ListaPerspectiva) { DataRow FilaPerspectiva = DsPerspectiva.Tables["Perspectivas"].NewRow(); FilaPerspectiva["Id"] = Perspectiva.Id; FilaPerspectiva["Nombre"] = Perspectiva.Nombre; // Cargo el color segun el estado Color Color = VisualHelper.GetColor(Perspectiva.Estado(restriccionesPersp)); int? ColorPersp = null; if (Color == System.Drawing.Color.Green) ColorPersp = 1; else if (Color == System.Drawing.Color.Yellow) ColorPersp = 0; else if (Color == System.Drawing.Color.Red) ColorPersp = -1; else if (Color == System.Drawing.Color.White) ColorPersp = 2; FilaPerspectiva["Color"] = ColorPersp; DsPerspectiva.Tables["Perspectivas"].Rows.Add(FilaPerspectiva); DsPerspectiva.Tables["Perspectivas"].AcceptChanges(); // Cargo el Objetivo foreach (Objetivo Objetivo in Perspectiva.Objetivos) { DataRow FilaObjetivo = DsPerspectiva.Tables["Objetivos"].NewRow(); FilaObjetivo["Id"] = Objetivo.Id; FilaObjetivo["Nombre"] = Objetivo.Nombre; FilaObjetivo["perspectiva_id"] = Objetivo.Perspectiva.Id; // Cargo el color segun el estado Color = VisualHelper.GetColor(Objetivo.Estado(restriccionesObj)); int? ColorObj = null; if (Color == System.Drawing.Color.Green) ColorObj = 1; else if (Color == System.Drawing.Color.Yellow) ColorObj = 0; else if (Color == System.Drawing.Color.Red) ColorObj = -1; else if (Color == System.Drawing.Color.White) ColorObj = 2; FilaObjetivo["Color"] = ColorObj; DsPerspectiva.Tables["Objetivos"].Rows.Add(FilaObjetivo); DsPerspectiva.Tables["Objetivos"].AcceptChanges(); // Cargo el Indicador foreach (Indicador Indicador in Objetivo.Indicadores) { DataRow Filaindicador = DsPerspectiva.Tables["indicadores"].NewRow(); Filaindicador["Id"] = Indicador.Id; Filaindicador["nombre"] = Indicador.Nombre; Filaindicador["codigo"] = Indicador.Codigo; Filaindicador["ValorEsperado"] = Indicador.ValorEsperado; Filaindicador["objetivo_id"] = Indicador.Objetivo.Id; Filaindicador["responsable_id"] = Indicador.Responsable.Id; Filaindicador["frecuencia_id"] = Indicador.Frecuencia.Id; // Cargo el color segun el estado Color =VisualHelper.GetColor(Indicador.Estado); int? ColorInd = null; if (Color == System.Drawing.Color.Green) ColorInd = 1; else if (Color == System.Drawing.Color.Yellow) ColorInd = 0; else if (Color == System.Drawing.Color.Red) ColorInd = -1; else if (Color == System.Drawing.Color.White) ColorInd = 2; Filaindicador["Color"] = ColorInd; DsPerspectiva.Tables["indicadores"].Rows.Add(Filaindicador); DsPerspectiva.Tables["indicadores"].AcceptChanges(); // Cargo Las mediciones foreach (Medicion medicion in Indicador.Mediciones) { if ((medicion.Fecha.Date >= dateTimePicker1.Value) & (medicion.Fecha.Date <= dateTimePicker2.Value)) { DataRow FilaMedicion = DsPerspectiva.Tables["mediciones"].NewRow(); FilaMedicion["Id"] = medicion.Id; FilaMedicion["Detalle"] = medicion.Detalle; FilaMedicion["Fecha"] = medicion.Fecha.Date; FilaMedicion["Valor"] = medicion.Valor; FilaMedicion["indicador_id"] = medicion.Indicador.Id; // FilaMedicion["frecuencia_id"] = medicion.Frecuencia.Id; DsPerspectiva.Tables["mediciones"].Rows.Add(FilaMedicion); } } DsPerspectiva.Tables["mediciones"].AcceptChanges(); } } } Reportes.CRInformeGeneral reporte = new Reportes.CRInformeGeneral(); reporte.SetDataSource(DsPerspectiva); /* Fecha de Medición reporte.SetParameterValue("FechaDesde", dateTimePicker1.Value.Date); reporte.SetParameterValue("FechaHasta", dateTimePicker2.Value.Date); */ crystalReportViewer1.ReportSource = reporte; crystalReportViewer1.Refresh(); } private void Form_InformeGeneral_Load(object sender, EventArgs e) { } } }
namespace Sentry.PlatformAbstractions; /// <summary> /// Extension method to the <see cref="Runtime"/> class. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static class RuntimeExtensions { /// <summary> /// Is the runtime instance .NET Framework. /// </summary> /// <param name="runtime">The runtime instance to check.</param> /// <returns>True if it's .NET Framework, otherwise false.</returns> public static bool IsNetFx(this Runtime runtime) => runtime.StartsWith(".NET Framework"); /// <summary> /// Is the runtime instance .NET Core (or .NET). /// </summary> /// <param name="runtime">The runtime instance to check.</param> /// <returns>True if it's .NET Core (or .NET), otherwise false.</returns> public static bool IsNetCore(this Runtime runtime) => runtime.StartsWith(".NET Core") || (runtime.StartsWith(".NET") && !runtime.StartsWith(".NET Framework")); /// <summary> /// Is the runtime instance Mono. /// </summary> /// <param name="runtime">The runtime instance to check.</param> /// <returns>True if it's Mono, otherwise false.</returns> public static bool IsMono(this Runtime runtime) => runtime.StartsWith("Mono"); /// <summary> /// Is the runtime instance Browser Web Assembly. /// </summary> /// <param name="runtime">The runtime instance to check.</param> /// <returns>True if it's Browser WASM, otherwise false.</returns> internal static bool IsBrowserWasm(this Runtime runtime) => runtime.Identifier == "browser-wasm"; private static bool StartsWith(this Runtime? runtime, string runtimeName) => runtime?.Name?.StartsWith(runtimeName, StringComparison.OrdinalIgnoreCase) == true || runtime?.Raw?.StartsWith(runtimeName, StringComparison.OrdinalIgnoreCase) == true; }
using System; using System.Collections.Generic; using System.Linq; using CSBaseLib; using MessagePack; namespace OMKServer { public class PKHRoom : PKHandler { List<Room> RoomList = new List<Room>(); private int StartRoomNumber; public void SetRoomList(List<Room> roomList) { RoomList = roomList; StartRoomNumber = roomList[0].Number; } public void RegistPacketHandler(Dictionary<int, Action<ServerPacketData>> pakcetHandlerMap) { pakcetHandlerMap.Add((int)PACKETID.REQ_ROOM_ENTER, RequestRoomEnter); pakcetHandlerMap.Add((int)PACKETID.REQ_ROOM_LEAVE, RequestLeave); pakcetHandlerMap.Add((int)PACKETID.NTF_IN_ROOM_LEAVE, NotifyLeaveInternal); pakcetHandlerMap.Add((int)PACKETID.REQ_ROOM_CHAT, RequestChat); pakcetHandlerMap.Add((int)PACKETID.REQ_GAME_READY, RequestGameReady); pakcetHandlerMap.Add((int)PACKETID.REQ_OMOK_TURN, requestOmokGame); } Room GetRoom(int roomNumber) { var index = roomNumber - StartRoomNumber; // RoomList.Count 는 System.Linq Enumerable의 static Method if (index < 0 || index >= RoomList.Count()) { return null; } return RoomList[index]; } // tuple 사용 (bool, Room, RoomUser) CheckRoomAndRoomUser(int userNetSessionIndex) { var user = UserMgr.GetUser(userNetSessionIndex); if (user == null) { return (false, null, null); } var roomNumber = user.RoomNumber; var room = GetRoom(roomNumber); if (room == null) { return (false, null, null); } var roomUser = room.GetUser(userNetSessionIndex); if (roomUser == null) { return (false, room, null); } return (true, room, roomUser); } public int GetUsableRoom() { int index = -1; foreach (var room in RoomList) { if (room.CurrentUserCount() != 1) { continue; } index = room.Index; break; } if (index != -1) { return index; } foreach (var room in RoomList) { if (room.ChkRoomFull()) { continue; } index = room.Index; break; } return index; } public void RequestRoomEnter(ServerPacketData packetData) { var sessionID = packetData.SessionID; var sessionIndex = packetData.SessionIndex; MainServer.MainLogger.Debug("RequestRoonEnter"); try { // user는 User 객체 var user = UserMgr.GetUser(sessionIndex); if (user == null || user.IsConfirm(sessionID) == false) { ResponseEnterRoomToClient(ERROR_CODE.ROOM_ENTER_INVALID_USER, sessionID, -1); return; } if (user.IsStateRoom()) { ResponseEnterRoomToClient(ERROR_CODE.ROOM_ENTER_INVALID_STATE, sessionID, -1); return; } var reqData = MessagePackSerializer.Deserialize<OMKReqRoomEnter>(packetData.BodyData); int roomNumber = GetUsableRoom(); var room = GetRoom(roomNumber); if (reqData.RoomNumber != -1 || room == null) { ResponseEnterRoomToClient(ERROR_CODE.ROOM_ENTER_INVALID_ROOM_NUMBER, sessionID, -1); return; } // UserList<RoomUser> 객체 추가 if (room.AddUser(user.ID(), sessionIndex, sessionID) == false) { ResponseEnterRoomToClient(ERROR_CODE.ROOM_ENTER_FAIL_ADD_USER, sessionID, -1); return; } if (room.CurrentUserCount() <= 1) // 유저가 자기자신일 뿐일때 { user.setUserPos(0); } else { int otherUserIndex = room.GetOtherUser(sessionIndex); User otherUser = UserMgr.GetUser(otherUserIndex); if (otherUser.UserPos == 1) {user.setUserPos(0);} else {user.setUserPos(1);} } user.EnteredRoom(roomNumber); room.NotifyPacketUserList(sessionID); // Room에 있는 유저 정보 room.NofifyPacketNewUser(sessionIndex, user.ID()); // 새로운 유저 정보 ResponseEnterRoomToClient(ERROR_CODE.NONE, sessionID, user.UserPos); // 유저 정보 MainServer.MainLogger.Debug("RequestEnterInternal = Success, UserPos : " + user.UserPos); } catch (Exception e) { MainServer.MainLogger.Error(e.ToString()); } } void ResponseEnterRoomToClient(ERROR_CODE errorCode, string sessionID, short userPos) { // 0609 여기에 userPos // sessionID로 userPos var resRoomEnter = new OMKResRoomEnter() { Result = (short)errorCode, userPos = userPos }; var bodyData = MessagePackSerializer.Serialize(resRoomEnter); var sendData = PacketToBytes.Make(PACKETID.RES_ROOM_ENTER, bodyData); MainServer.MainLogger.Info("RoomEnterResponse"); // Room 에 잘 들어갔다고 MainServer.SendData 실행 ServerNetwork.SendData(sessionID, sendData); } public void RequestLeave(ServerPacketData packetData) { var sessionID = packetData.SessionID; var sessionIndex = packetData.SessionIndex; MainServer.MainLogger.Debug("로그인 요청 받음"); try { var user = UserMgr.GetUser(sessionIndex); //var room = GetRoom(user.RoomNumber); if (user == null) { return; } // 룸에서 유저 떠남 if (LeaveRoomUser(sessionIndex, user.RoomNumber) == false) { return; } // 유저 객체에 룸에서 떠났다고 알리기 user.LeaveRoom(); // 결과를 해당 유저에게 전달 ResponseLeaveRoomToClient(sessionID); MainServer.MainLogger.Debug("Room RequestLeave - Success"); } catch (Exception e) { MainServer.MainLogger.Error(e.ToString()); } } public void requestOmokGame(ServerPacketData packetData) { var sessionIndex = packetData.SessionIndex; var sessionID = packetData.SessionID; var user = UserMgr.GetUser(sessionIndex); var roomObject = CheckRoomAndRoomUser(sessionIndex); if (user == null || roomObject.Item1 == false) // 유저가 없을 경우 에러 { responseOmokGameToClinet(ERROR_CODE.OMOK_GAME_INVALIED_PACKET, sessionID); return; } var reqData = MessagePackSerializer.Deserialize<OMKReqOmokGame>(packetData.BodyData); ERROR_CODE code = roomObject.Item2.ChkOmokPosition(reqData.X, reqData.Y, user.UserPos); MainServer.MainLogger.Info($"ChkOmokPosition X : {reqData.X} Y : {reqData.Y} user : {user.UserPos}"); responseOmokGameToClinet(code, sessionID); if (code == ERROR_CODE.NONE) { roomObject.Item2.NotifyPacketOmokTurn(reqData.X, reqData.Y, user.UserPos); if (roomObject.Item2.ChkPointer(reqData.X, reqData.Y, user.UserPos)) { // 일단 성공 결과만 전부 보내게 하기 roomObject.Item2.NotifyPacketOmokGame(user.UserPos); MainServer.MainLogger.Info($"USER - {user.UserPos} Win!"); } } return; } // 해당 룸에 (roomNumber) 해당 유저(sessinIndex) 떠남 bool LeaveRoomUser(int sessionIndex, int roomNumber) { MainServer.MainLogger.Debug($"LeaveRoomUser. SessionIndex:{sessionIndex}"); var room = GetRoom(roomNumber); if (room == null) { return false; } var roomUser = room.GetUser(sessionIndex); if (roomUser == null) { return false; } var userID = roomUser.UserID; room.RemoveUser(roomUser); room.initReady(); room.initOmok(); // Pakcet을 뭉쳐서 모든 유저에게 SendData room.NofifyPacketLeaveUser(userID); return true; } void ResponseLeaveRoomToClient(string sessionID) { // MessagePack var resRoomLeave = new OMKResRoomLeave() { Result = (short)ERROR_CODE.NONE }; var bodyData = MessagePackSerializer.Serialize(resRoomLeave); var sendData = PacketToBytes.Make(PACKETID.RES_ROOM_LEAVE, bodyData); // 해당 유저에게 SendData ServerNetwork.SendData(sessionID, sendData); } void ResponseGameReadyToClient(ERROR_CODE errorCode, string sessionID) { var resRoomEnter = new OMKResGameReady() { Result = (short)errorCode }; var bodyData = MessagePackSerializer.Serialize(resRoomEnter); var sendData = PacketToBytes.Make(PACKETID.RES_GAME_READY, bodyData); // Room 에 잘 들어갔다고 MainServer.SendData 실행 ServerNetwork.SendData(sessionID, sendData); } public void responseOmokGameToClinet(ERROR_CODE errorCode, string sessionID) { var resOmokGame = new OMKResOmokTurn() { Result = (short)errorCode }; var bodyData = MessagePackSerializer.Serialize(resOmokGame); var sendData = PacketToBytes.Make(PACKETID.RES_OMOK_TURN, bodyData); ServerNetwork.SendData(sessionID, sendData); MainServer.MainLogger.Info($"RequestOmok, Send Response Omok Message : {resOmokGame.Result}"); } public void NotifyLeaveInternal(ServerPacketData packetData) { // ServerPacketData Object에서 SessionIndex Get var sessionIndex = packetData.SessionIndex; MainServer.MainLogger.Debug($"NotifyLeaveInternal. SessionIndex:{sessionIndex}"); // MessagePack 직렬화 (RoomNumber, UserID) var reqData = MessagePackSerializer.Deserialize<PKTInternalNTFRoomLeave>(packetData.BodyData); LeaveRoomUser(sessionIndex, reqData.RoomNumber); } public void RequestChat(ServerPacketData packetData) { var sessionIndex = packetData.SessionIndex; MainServer.MainLogger.Debug("Room RequestChat"); try { var roomObject = CheckRoomAndRoomUser(sessionIndex); if (roomObject.Item1 == false) { return; } var reqData = MessagePackSerializer.Deserialize<OMKReqRoomChat>(packetData.BodyData); var notifyPacket = new OMKRoomChat() { UserID = roomObject.Item3.UserID, ChatMessage = reqData.ChatMessage }; // Packet 직렬화 var body = MessagePackSerializer.Serialize(notifyPacket); var sendData = PacketToBytes.Make(PACKETID.NTF_ROOM_CHAT, body); // BroadCast -1 이니까 모든 Room에 있는 user에게! roomObject.Item2.Broadcast(-1, sendData); MainServer.MainLogger.Debug("Room RequestChat - Success"); } catch (Exception e) { MainServer.MainLogger.Error(e.ToString()); } } public void RequestGameReady(ServerPacketData packetData) { var sessionID = packetData.SessionID; var sessionIndex = packetData.SessionIndex; MainServer.MainLogger.Debug("게임 준비 요청 받음"); try { // User 객체 var user = UserMgr.GetUser(sessionIndex); if (user == null) { ResponseGameReadyToClient(ERROR_CODE.GAME_READY_INVALIED_USER, sessionID); return; // error } var reqData = MessagePackSerializer.Deserialize<OMKReqGameReady>(packetData.BodyData); short userPos = reqData.UserPos; if (userPos != user.UserPos || userPos == -1) { ResponseGameReadyToClient(ERROR_CODE.GAME_READY_INVALID_STATE, sessionID); return; } var room = GetRoom(user.RoomNumber); // Player 2의 게임 준비 결과 반환 if (userPos == 1) { room.isReady[user.UserPos] = true; //ResponseGameReadyToClient(ERROR_CODE.NONE, sessionID); room.NofifyPacketGameReady(); return; } // Player 1일 때 다른 플레이어가 아직 준비가 되어있지 않으면 오류 if (room.isReady[1] == false) { // error 반환 ResponseGameReadyToClient(ERROR_CODE.GAME_READY_INVALID_CHECK_OTHER_USER, sessionID); return; } // Player 1의 결과를 true 로 변환하고, 모든 유저들에게 게임 시작한다는 알림 room.isReady[user.UserPos] = true; // 반복되는 부분인가? 사용하지 않아도 되는가? foreach (var isReady in room.isReady) { if (isReady == false) { ResponseGameReadyToClient(ERROR_CODE.GAME_READY_INVALID_STATE, sessionID); return; } } // 결과 반환 Noti -> Response -> GameStart room.NofifyPacketGameStart(); } catch (Exception e) { MainServer.MainLogger.Error(e.ToString()); } } } }
using System; using System.Collections.Generic; using System.Linq; /* * tags: greedy, bfs * Time(n), Space(1) */ namespace leetcode { public class Lc45_Jump_Game_II { public int Jump(int[] nums) { int res = 0; for (int far = 0, farthest = 0, i = 0; i < nums.Length - 1; i++) { far = Math.Max(far, i + nums[i]); if (i == farthest) // one more jump { farthest = far; res++; } } return res; } public int JumpBfs(int[] nums) { int res = 0; for (int i = 0, q = 0; q < nums.Length - 1; ) { res++; for (int currq = q; i <= currq; i++) q = Math.Max(q, i + nums[i]); } return res; } public void Test() { var nums = new int[] { 2, 3, 1, 1, 4 }; Console.WriteLine(Jump(nums) == 2); Console.WriteLine(JumpBfs(nums) == 2); } } }
using Alabo.Validations; using Alabo.Web.Mvc.Attributes; using System.ComponentModel.DataAnnotations; namespace Alabo.Framework.Core.WebUis.Models.Previews { [ClassProperty(Name = "链接")] public class PreviewInput { [Required(ErrorMessage = ErrorMessage.NameNotAllowEmpty)] public string Id { get; set; } /// <summary> /// 数据ID /// </summary> public string DataId { get; set; } /// <summary> /// 客户端当前登录用户的Id /// </summary> public long LoginUserId { get; set; } } }
// Copyright (C) 2015 EventDay, Inc using System; using System.Collections.Generic; namespace EventDayDsl.EventDay.Entities { public class Entity : IMessage { public Entity(string name, IEnumerable<MarkerInterface> interfaces) { Name = name; Properties = new HashSet<MessageProperty>(MessageProperty.NameComparer); Interfaces = new HashSet<MarkerInterface>(interfaces); } public string Name { get; set; } public ISet<MessageProperty> Properties { get; } public ISet<MarkerInterface> Interfaces { get; set; } public static IEqualityComparer<Entity> NameComparer { get; } = new NameEqualityComparer(); public string StringFormat { get; set; } public void AddProperty(string name, string type, bool optional = false) { var property = new MessageProperty {Name = name, Type = type.SafeTypeName(), Optional = optional}; if (Properties.Contains(property)) throw new Exception($"Can not overwrite property '{name}'"); Properties.Add(property); } private sealed class NameEqualityComparer : IEqualityComparer<Entity> { public bool Equals(Entity x, Entity y) { if (ReferenceEquals(x, y)) return true; if (ReferenceEquals(x, null)) return false; if (ReferenceEquals(y, null)) return false; if (x.GetType() != y.GetType()) return false; return string.Equals(x.Name, y.Name); } public int GetHashCode(Entity obj) { return obj.Name != null ? obj.Name.GetHashCode() : 0; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Collision_L_Sword : MonoBehaviour { // ソードの当たり判定のオブジェクトの宣言※親 GameObject Sword_L; GameObject Sword_R; // 子オブジェクト用に変数を宣言 Transform Sword_L_Child; Transform Sword_R_Child; public GameObject SpawnMove; public GameObject[] Block = new GameObject[8]; public int Block_Num; public int Speed = 1; public bool Collision_rank_L; public static int Combo_Counter = 0; public bool Collision_flag; // Start is called before the first frame update void Start() { this.Sword_L = GameObject.Find("Sword_L"); this.Sword_R = GameObject.Find("Sword_R"); this.Sword_L_Child = this.Sword_L.transform.Find("effect"); this.Sword_R_Child = this.Sword_R.transform.Find("effect2"); } // Update is called once per frame void Update() { } // 物体がすり抜けた時 public void OnCollisionEnter(Collision collision) { if (this.Sword_L_Child.transform.tag == collision.gameObject.tag) { if (!Collision_flag) { Collision_rank_L = true; Collision_flag = true; Block_Num = Random.Range(0, Block.Length - 1); Instantiate(Block[Block_Num], SpawnMove.transform.position, Block[Block_Num].transform.rotation); } } } // 物体が通り抜け終えた時に呼ばれ public void OnCollisionExit(Collision collision) { // BlockとSword_Lの子オブジェクトのタグと一致している時 // effectのタグと衝突したBlockのタグと同じ時 if (this.Sword_L_Child.transform.tag == collision.gameObject.tag) { Collision_rank_L = false; Collision_flag = false; RankContoller.Collisiton_MoveRank_L = true; Destroy(collision.gameObject); SpeedController.Speed_Move = Speed; Combo_Counter++; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading.Tasks; using DM7_PPLUS_Integration.Daten; using DM7_PPLUS_Integration.Messages.PPLUS; using Datenstand = DM7_PPLUS_Integration.Daten.Datenstand; using Datum = DM7_PPLUS_Integration.Daten.Datum; using Uhrzeit = DM7_PPLUS_Integration.Daten.Uhrzeit; namespace DM7_PPLUS_Integration.Implementierung.PPLUS { public class Test_Server { public static Test_Server Instanz() { return new Test_Server(); } private readonly List<Dienst> _dienste = new List<Dienst>(); private readonly List<Mitarbeiter> _mitarbeiter = new List<Mitarbeiter>(); private readonly Dictionary<(Guid mandant, Datum tag), List<Dienstbuchung>> _dienstbuchungen = new Dictionary<(Guid, Datum), List<Dienstbuchung>>(); private readonly Dictionary<Guid, List<Abwesenheit>> _abwesenheiten = new Dictionary<Guid, List<Abwesenheit>>(); private string _user = "anonymous"; private string _password = "password"; private Test_Server() { } public Test_Server Mit_Diensten(params Dienst[] dienste) { _dienste.Clear(); _dienste.AddRange(dienste); return this; } public Test_Server Mit_Mitarbeitern(params Mitarbeiter[] mitarbeiter) { _mitarbeiter.Clear(); _mitarbeiter.AddRange(mitarbeiter); return this; } public Test_Server Mit_Dienstbuchungen_für(Guid mandant, Datum tag, params Dienstbuchung[] dienstbuchungen) { var key = (mandant, tag); if (_dienstbuchungen.ContainsKey(key)) { _dienstbuchungen[key].Clear(); _dienstbuchungen[key].AddRange(dienstbuchungen); } else { _dienstbuchungen.Add(key, dienstbuchungen.ToList()); } return this; } public Test_Server Mit_Abwesenheiten_für(Guid mandant, params Abwesenheit[] abwesenheiten) { if (_abwesenheiten.ContainsKey(mandant)) { _abwesenheiten[mandant].Clear(); _abwesenheiten[mandant].AddRange(abwesenheiten); } else { _abwesenheiten.Add(mandant, abwesenheiten.ToList()); } return this; } public Test_Server Mit_Authentification(string user, string password) { _user = user; _password = password; return this; } public Test_Host Start(string adresse, int port, out string encryptionKey) { var backend = new Test_PPLUS_Handler(_user, _password, _mitarbeiter, _dienste, _dienstbuchungen, _abwesenheiten); encryptionKey = Encryption.Generate_encoded_Key(); return new Test_Host(backend, adresse, port, encryptionKey); } } internal readonly struct Daten_mit_Version<T> { public readonly T Data; public readonly ulong Version; public Daten_mit_Version(T data, ulong version) { Data = data; Version = version; } } internal class Test_PPLUS_Handler : PPLUS_Handler { private readonly string _user; private readonly string _password; private Token? _token; private readonly List<Daten_mit_Version<Mitarbeiter>> _mitarbeiter; private readonly List<Daten_mit_Version<Dienst>> _dienste; private readonly Dictionary<(Guid mandant, Datum tag), List<Dienstbuchung>> _dienstbuchungen; private readonly Dictionary<Guid, List<Abwesenheit>> _abwesenheiten; private readonly List<Dienstplanabschluss> _dienstplanabschlüsse = new List<Dienstplanabschluss>(); private Soll_Ist_Abgleich? _letzter_Soll_Ist_Abgleich; public Test_PPLUS_Handler( string user, string password, IEnumerable<Mitarbeiter> mitarbeiter, IEnumerable<Dienst> dienste, Dictionary<(Guid mandant, Datum tag), List<Dienstbuchung>> dienstbuchungen, Dictionary<Guid, List<Abwesenheit>> abwesenheiten) { _user = user; _password = password; _mitarbeiter = mitarbeiter.Select(_ => new Daten_mit_Version<Mitarbeiter>(_, 1)).ToList(); _dienste = dienste.Select(_ => new Daten_mit_Version<Dienst>(_, 1)).ToList(); _dienstbuchungen = dienstbuchungen; _abwesenheiten = abwesenheiten; } public Task<Token?> Authenticate(string user, string password, TimeSpan? timeout = null) { return Task.Run(() => { if (user != _user || _password != password) return null; _token = new Token(69); return _token; }); } public Task<Capabilities> Capabilities(TimeSpan? timeout = null) { return Task.FromResult(new Capabilities(new[] { Capability.MITARBEITER_V1, Capability.DIENSTE_V1, Capability.BEGINN_VON_DIENST_V1, Capability.ABWESENHEITEN_V1, Capability.DIENSTBUCHUNGEN_V1, Capability.SOLL_IST_ABGLEICH_V1 }.ToList())); } public Task<QueryResult> HandleQuery(Token token, Query query, TimeSpan? timeout = null) { return Task.Run<QueryResult>(() => { if (_token.HasValue == false || _token.Value != token) { return new IOFehler("Unberechtigter Zugriff"); } switch (query) { case MitarbeiterAbrufenV1 _: return Message_mapper.Mitarbeiterstammdaten_als_Message(Mitarbeiter_abrufen()); case MitarbeiterAbrufenAbV1 q: return Message_mapper.Mitarbeiterstammdaten_als_Message(Mitarbeiter_abrufen_ab(Message_mapper.Stand_aus(q.Value))); case DiensteAbrufenV1 _: return Message_mapper.Dienste_als_Message(Dienste_abrufen()); case DiensteAbrufenAbV1 q: return Message_mapper.Dienste_als_Message(Dienste_abrufen_ab(Message_mapper.Stand_aus(q.Value))); case DienstbeginnZumStichtagV1 _: return Message_mapper.Dienstbeginn_als_Message(Uhrzeit.HH_MM(08, 30)); case DienstbuchungenImZeitraumV1 q: return Message_mapper.Dienstbuchungen_als_Message(Dienstbuchungen_im_Zeitraum(Message_mapper.Guid_aus(q.Mandant), Message_mapper.Datum_aus(q.Von), Message_mapper.Datum_aus(q.Bis))); case AbwesenheitenImZeitraumV1 q: return Message_mapper.Abwesenheiten_als_Message(Abwesenheiten_im_Zeitraum(Message_mapper.Guid_aus(q.Mandant), Message_mapper.Datum_aus(q.Von), Message_mapper.Datum_aus(q.Bis))); default: return new IOFehler($"Query '{query.GetType()}' nicht behandelt"); } }); } public Task<CommandResult> HandleCommand(Token token, Command command, TimeSpan? timeout = null) { return Task.Run<CommandResult>(() => { if (_token.HasValue == false || _token.Value != token) { return new IOFehler("Unberechtigter Zugriff"); } switch (command) { case SollIstAbgleichFreigebenV1 c: { var abgleich = Message_mapper.Soll_Ist_Abgleich_aus(c.Value); _letzter_Soll_Ist_Abgleich = abgleich; var ergebnis = Verarbeite_Soll_Ist_Abgleich(abgleich); return Message_mapper.Soll_Ist_Abgleich_Verarbeitungsergebnis_als_Message(ergebnis); } default: return new IOFehler($"Command '{command.GetType()}' nicht behandelt"); } }); } public event Action Mitarbeiteränderungen_liegen_bereit; public event Action Dienständerungen_liegen_bereit; private Soll_Ist_Abgleich_Verarbeitungsergebnis Verarbeite_Soll_Ist_Abgleich(Soll_Ist_Abgleich abgleich) { if (_dienstplanabschlüsse.Any()) { return new Dienstplanabschluss_verhindert_Verarbeitung(new ReadOnlyCollection<Dienstplanabschluss>(_dienstplanabschlüsse)); } foreach (var nichtGefahreneTour in abgleich.Nicht_gefahrene_Touren) { var key = (nichtGefahreneTour.MandantId, abgleich.Datum); if (!_dienstbuchungen.ContainsKey(key)) continue; _dienstbuchungen[key].RemoveAll(db => db.MitarbeiterId == nichtGefahreneTour.MitarbeiterId && db.DienstId == nichtGefahreneTour.Dienst); } return new Verarbeitet(); } public void Dienste_setzen(IEnumerable<Dienst> dienste) { var nächste_Version = Nächste_Version(_dienste); _dienste.Clear(); _dienste.AddRange(dienste.Select(_ => new Daten_mit_Version<Dienst>(_, nächste_Version))); Dienständerungen_liegen_bereit?.Invoke(); } public void Dienste_hinzufügen(IEnumerable<Dienst> dienste) { var nächste_Version = Nächste_Version(_dienste); _dienste.AddRange(dienste.Select(_ => new Daten_mit_Version<Dienst>(_, nächste_Version))); Dienständerungen_liegen_bereit?.Invoke(); } public void Dienst_löschen(int dienst) { var nächste_Version = Nächste_Version(_dienste); var neue_Dienste = _dienste .Select(_ => _.Data.Id == dienst ? Dienst_als_gelöscht(_.Data) : _.Data) .ToList(); _dienste.Clear(); _dienste.AddRange(neue_Dienste.Select(_ => new Daten_mit_Version<Dienst>(_, nächste_Version))); Dienständerungen_liegen_bereit?.Invoke(); } private static Dienst Dienst_als_gelöscht(Dienst dienst) { return new Dienst( dienst.Id, dienst.Mandantenzugehörigkeiten, dienst.Kurzbezeichnung, dienst.Bezeichnung, dienst.Gültig_an, true ); } public void Mitarbeiter_setzen(IEnumerable<Mitarbeiter> mitarbeiter) { var nächste_Version = Nächste_Version(_mitarbeiter); _mitarbeiter.Clear(); _mitarbeiter.AddRange(mitarbeiter.Select(_ => new Daten_mit_Version<Mitarbeiter>(_, nächste_Version))); Mitarbeiteränderungen_liegen_bereit?.Invoke(); } public void Mitarbeiter_hinzufügen(IEnumerable<Mitarbeiter> mitarbeiter) { var nächste_Version = Nächste_Version(_mitarbeiter); _mitarbeiter.AddRange(mitarbeiter.Select(_ => new Daten_mit_Version<Mitarbeiter>(_, nächste_Version))); Mitarbeiteränderungen_liegen_bereit?.Invoke(); } public void Mitarbeiter_austreten_zum(Datum austrittsdatum, Guid mitarbeiter) { var nächste_Version = Nächste_Version(_mitarbeiter); var neue_Mitarbeiter = _mitarbeiter .Select(_ => _.Data.Id == mitarbeiter ? new Daten_mit_Version<Mitarbeiter>( Mit_Mandantenzugehörigkeit_bis_zum(austrittsdatum, _.Data), nächste_Version) : _) .ToList(); _mitarbeiter.Clear(); _mitarbeiter.AddRange(neue_Mitarbeiter); Mitarbeiteränderungen_liegen_bereit?.Invoke(); } private static Mitarbeiter Mit_Mandantenzugehörigkeit_bis_zum(Datum austrittsdatum, Mitarbeiter mitarbeiter) { return new Mitarbeiter( mitarbeiter.Id, mitarbeiter.PersonenId, new ReadOnlyCollection<DM7_Mandantenzugehörigkeit>( mitarbeiter.DM7_Mandantenzugehörigkeiten .Select(_ => new DM7_Mandantenzugehörigkeit(_.MandantId, _.GueltigAb, austrittsdatum)) .ToList() ), mitarbeiter.Personalnummer, mitarbeiter.Titel, mitarbeiter.Vorname, mitarbeiter.Nachname, mitarbeiter.Postanschrift, mitarbeiter.Handzeichen, mitarbeiter.Geburtstag, mitarbeiter.Geschlecht, mitarbeiter.Konfession, mitarbeiter.Familienstand, mitarbeiter.Qualifikationen, mitarbeiter.Kontakte, mitarbeiter.PIN_für_mobile_Datenerfassung ); } public Stammdaten<Mitarbeiter> Mitarbeiter_abrufen() => new Stammdaten<Mitarbeiter>(_mitarbeiter.Select(_ => _.Data).ToList(), Höchster_Datenstand(_mitarbeiter)); public Stammdaten<Mitarbeiter> Mitarbeiter_abrufen_ab(Datenstand stand) { var mitarbeiter = _mitarbeiter .Where(_ => _.Version > stand.Value) .Select(_ => _.Data) .ToList(); return new Stammdaten<Mitarbeiter>(mitarbeiter, Höchster_Datenstand(_mitarbeiter)); } public Stammdaten<Dienst> Dienste_abrufen() => new Stammdaten<Dienst>(_dienste.Select(_ => _.Data).ToList(), Höchster_Datenstand(_dienste)); public Stammdaten<Dienst> Dienste_abrufen_ab(Datenstand stand) { var dienste = _dienste .Where(_ => _.Version > stand.Value) .Select(_ => _.Data) .ToList(); return new Stammdaten<Dienst>(dienste, Höchster_Datenstand(_dienste)); } public List<(Guid MandantId, Datum datum, Dienstbuchung dienstbuchung)> Dienstbuchungen_abrufen() { return _dienstbuchungen .SelectMany(kv => kv.Value.Select(buchung => (kv.Key.mandant, kv.Key.tag, buchung))) .ToList(); } public List<(Guid MandantId, Abwesenheit abwesenheit)> Abwesenheiten_abrufen() { return _abwesenheiten .SelectMany(kv => kv.Value.Select(abwesenheit => (kv.Key, abwesenheit))) .ToList(); } private Dictionary<Datum, ReadOnlyCollection<Dienstbuchung>> Dienstbuchungen_im_Zeitraum(Guid mandant, Datum von, Datum bis) { var dienstbuchungen = new Dictionary<Datum, ReadOnlyCollection<Dienstbuchung>>(); var b = new DateTime(bis.Jahr, bis.Monat, bis.Tag); for (var v = new DateTime(von.Jahr, von.Monat, von.Tag); v <= b; v = v.AddDays(1)) { var key = (mandant, Datum.DD_MM_YYYY(v.Day, v.Month, v.Year)); if (_dienstbuchungen.ContainsKey(key)) dienstbuchungen.Add(key.Item2, _dienstbuchungen[key].AsReadOnly()); } return dienstbuchungen; } public void Dienstbuchungen_leeren() { _dienstbuchungen.Clear(); } public void Dienstbuchungen_hinzufügen(Guid mandant, Datum tag, IEnumerable<Dienstbuchung> dienstbuchungen) { var key = (mandant, tag); if (_dienstbuchungen.ContainsKey(key)) _dienstbuchungen[key].AddRange(dienstbuchungen); else _dienstbuchungen.Add(key, dienstbuchungen.ToList()); } public void Dienst_streichen(Guid mandant, Datum tag, int dienst) { var key = (mandant, tag); if (_dienstbuchungen.ContainsKey(key)) _dienstbuchungen[key].RemoveAll(buchung => buchung.DienstId == dienst); } private ReadOnlyCollection<Abwesenheit> Abwesenheiten_im_Zeitraum(Guid mandant, Datum von, Datum bis) { var zeitraumbeginn = new DateTime(von.Jahr, von.Monat, von.Tag); var zeitraumende = new DateTime(bis.Jahr, bis.Monat, bis.Tag); bool Gilt_im_Zeitraum(Abwesenheit abwesenheit) { var v = new DateTime(abwesenheit.Abwesend_ab.Datum.Jahr, abwesenheit.Abwesend_ab.Datum.Monat, abwesenheit.Abwesend_ab.Datum.Tag); if (abwesenheit.Vorraussichtlich_wieder_verfügbar_ab.HasValue) { var b = new DateTime(abwesenheit.Vorraussichtlich_wieder_verfügbar_ab.Value.Datum.Jahr, abwesenheit.Vorraussichtlich_wieder_verfügbar_ab.Value.Datum.Monat, abwesenheit.Vorraussichtlich_wieder_verfügbar_ab.Value.Datum.Tag); return (v >= zeitraumbeginn || v <= zeitraumende) && (b <= zeitraumende || b >= zeitraumbeginn); } return (v >= zeitraumbeginn || v <= zeitraumende); } var abwesenheiten = _abwesenheiten.ContainsKey(mandant) ? _abwesenheiten[mandant].Where(Gilt_im_Zeitraum).ToList() : new List<Abwesenheit>(); return abwesenheiten.AsReadOnly(); } public void Abwesenheiten_leeren() { _abwesenheiten.Clear(); } public void Abwesenheiten_eintragen(Guid mandant, IEnumerable<Abwesenheit> abwesenheiten) { if (_abwesenheiten.ContainsKey(mandant)) _abwesenheiten[mandant].AddRange(abwesenheiten); else _abwesenheiten.Add(mandant, abwesenheiten.ToList()); } public void Abwesenheiten_streichen_von(Guid mandant, Guid mitarbeiter) { if (_abwesenheiten.ContainsKey(mandant)) _abwesenheiten[mandant].RemoveAll(abwesenheit => abwesenheit.MitarbeiterId == mitarbeiter); } public void Dienstplanbschlüsse_zum_verhindern_der_Soll_Ist_Abgleich_Verarbeitung(IEnumerable<Dienstplanabschluss> abschlüsse) { _dienstplanabschlüsse.Clear(); _dienstplanabschlüsse.AddRange(abschlüsse); } public void Soll_Ist_Abgleich_Verarbeitung_nicht_verhindern() { _dienstplanabschlüsse.Clear(); } public Soll_Ist_Abgleich? Letzter_Soll_Ist_Abgleich() => _letzter_Soll_Ist_Abgleich; private static Datenstand Höchster_Datenstand<T>(List<Daten_mit_Version<T>> daten) => daten.Any() ? new Datenstand(daten.Max(_ => _.Version)) : new Datenstand(0); private static ulong Nächste_Version<T>(List<Daten_mit_Version<T>> daten) => daten.Any() ? daten.Max(_ => _.Version) + 1 : 1; public void Revoke_Token() { _token = null; } public void Dispose() { } } public class Test_Host : IDisposable { private readonly Adapter _host; private readonly Test_PPLUS_Handler _pplusHandler; private readonly string _adresse; private readonly int _port; internal Test_Host(Test_PPLUS_Handler pplusHandler, string adresse, int port, string encryptionKey) { _pplusHandler = pplusHandler; _adresse = adresse; _port = port; _host = new Adapter(adresse, port, _pplusHandler, encryptionKey); } public string ConnectionString => $"tcp://{_adresse}:{_port}"; public void Revoke_Token() { _pplusHandler.Revoke_Token(); } public void Mitarbeiter_setzen(params Mitarbeiter[] mitarbeiter) { _pplusHandler.Mitarbeiter_setzen(mitarbeiter); } public void Mitarbeiter_hinzufügen(params Mitarbeiter[] mitarbeiter) { _pplusHandler.Mitarbeiter_hinzufügen(mitarbeiter); } public void Mitarbeiter_austreten_zum(Datum austrittsdatum, Guid mitarbeiter) { _pplusHandler.Mitarbeiter_austreten_zum(austrittsdatum, mitarbeiter); } public void Dienst_löschen(int dienstId) { _pplusHandler.Dienst_löschen(dienstId); } public void Dienste_anlegen(params Dienst[] dienste) { _pplusHandler.Dienste_hinzufügen(dienste); } public void Dienste_setzen(params Dienst[] dienste) { _pplusHandler.Dienste_setzen(dienste); } public void Dienstbuchungen_setzen(Guid mandantId, Datum datum, params Dienstbuchung[] dienstbuchungen) { _pplusHandler.Dienstbuchungen_leeren(); _pplusHandler.Dienstbuchungen_hinzufügen(mandantId, datum, dienstbuchungen); } public void Dienste_buchen(Guid mandantId, Datum datum, params Dienstbuchung[] dienstbuchungen) { _pplusHandler.Dienstbuchungen_hinzufügen(mandantId, datum, dienstbuchungen); } public void Dienst_streichen(Guid mandantId, Datum tag, int dienstId) { _pplusHandler.Dienst_streichen(mandantId, tag, dienstId); } public void Abwesenheiten_setzen(Guid mandantId, params Abwesenheit[] abwesenheiten) { _pplusHandler.Abwesenheiten_leeren(); _pplusHandler.Abwesenheiten_eintragen(mandantId, abwesenheiten); } public void Abwesenheiten_eintragen(Guid mandantId, params Abwesenheit[] abwesenheiten) { _pplusHandler.Abwesenheiten_eintragen(mandantId, abwesenheiten); } public void Abwesenheiten_streichen_von(Guid mandantId, Guid mitarbeiter) { _pplusHandler.Abwesenheiten_streichen_von(mandantId, mitarbeiter); } public void Dienstplanbschlüsse_zum_verhindern_der_Soll_Ist_Abgleich_Verarbeitung(params Dienstplanabschluss[] abschlüsse) { _pplusHandler.Dienstplanbschlüsse_zum_verhindern_der_Soll_Ist_Abgleich_Verarbeitung(abschlüsse); } public void Soll_Ist_Abgleich_Verarbeitung_nicht_verhindern() { _pplusHandler.Soll_Ist_Abgleich_Verarbeitung_nicht_verhindern(); } public List<Dienst> Dienste() => _pplusHandler.Dienste_abrufen().ToList(); public List<Mitarbeiter> Mitarbeiter() => _pplusHandler.Mitarbeiter_abrufen().ToList(); public List<(Guid MandantId, Datum datum, Dienstbuchung dienstbuchung)> Dienstbuchungen() => _pplusHandler.Dienstbuchungen_abrufen(); public List<(Guid mandantId, Abwesenheit abwesenheit)> Abwesenheiten() => _pplusHandler.Abwesenheiten_abrufen(); public Soll_Ist_Abgleich? Letzter_Soll_Ist_Abgleich() => _pplusHandler.Letzter_Soll_Ist_Abgleich(); public void Dispose() { _host?.Dispose(); _pplusHandler?.Dispose(); } } }
using System; using System.Collections.Generic; using System.Text; namespace LINQ_Join { class Employee { public int ID { get; set; } public string Name { get; set; } public int AddressId { get; set; } public static List<Employee> GetAllEmployees() { return new List<Employee>() { new Employee { ID = 1, Name = "Preety", AddressId = 1 }, new Employee { ID = 2, Name = "Priyanka", AddressId = 2 }, new Employee { ID = 3, Name = "Anurag", AddressId = 3 }, new Employee { ID = 4, Name = "Pranaya", AddressId = 4 }, new Employee { ID = 5, Name = "Hina", AddressId = 5 }, new Employee { ID = 6, Name = "Sambit", AddressId = 6 }, new Employee { ID = 7, Name = "Happy", AddressId = 7}, new Employee { ID = 8, Name = "Tarun", AddressId = 8 }, new Employee { ID = 9, Name = "Santosh", AddressId = 9 }, new Employee { ID = 10, Name = "Raja", AddressId = 10}, new Employee { ID = 11, Name = "Sudhanshu", AddressId = 11} }; } } public class Address { public int ID { get; set; } public string AddressLine { get; set; } public static List<Address> GetAllAddresses() { return new List<Address>() { new Address { ID = 1, AddressLine = "AddressLine1"}, new Address { ID = 2, AddressLine = "AddressLine2"}, new Address { ID = 3, AddressLine = "AddressLine3"}, new Address { ID = 4, AddressLine = "AddressLine4"}, new Address { ID = 5, AddressLine = "AddressLine5"}, new Address { ID = 9, AddressLine = "AddressLine9"}, new Address { ID = 10, AddressLine = "AddressLine10"}, new Address { ID = 11, AddressLine = "AddressLine11"}, }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Cryptography.X509Certificates; using System.Web.Http; using prjSecondApplication.Models; namespace prjSecondApplication.Controllers { public class CountryController : ApiController { [Route("countrylist")] public HttpResponseMessage Get() { //list of countries List<Country> Countries = new List<Country>(); Country country = new Country(); country.ID = 1; country.CountryName = "India"; country.Capital = "New Delhi"; Countries.Add(country); //Countries to the response body HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, Countries); return response; } public IHttpActionResult Get(int id) { List<Country> Countries = new List<Country>(); Country country = new Country(); country.ID = 1; country.CountryName = "UK"; country.Capital = "London"; Countries.Add(country); //findinng country based on provided id var result = Countries.FirstOrDefault(x => x.ID == id); if(result == null) { //Create a 404 (Not Found) response return NotFound(); } else { //Create a 200(OK) response that contains the country return Ok(result); } } } }
namespace UnicodeCharacters { using System; using System.Text; public class Startup { public static void Main(string[] args) { Console.WriteLine(Execute()); } private static string Execute() { var input = Console.ReadLine(); var builder = new StringBuilder(); for (int i = 0; i < input.Length; i++) { builder.Append("\\u" + ((int)input[i]).ToString("X4").ToLower()); } return builder.ToString(); } } }
using System.Text; using System.Threading; using System.Threading.Tasks; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace Queue { public class QueueExample { public void RunConsumer() { Task.Run(() => { var factory = new ConnectionFactory() { HostName = "localhost", UserName = "rabbitmq", Password = "rabbitmq", VirtualHost = "/" }; var connection = factory.CreateConnection(); var channel = connection.CreateModel(); channel.QueueDeclare("fila-01", false, false, false, null); channel.BasicQos(0, 1, false); var consumer = new EventingBasicConsumer(channel); consumer.Received += ((model, ea) => { var message = Encoding.UTF8.GetString(ea.Body.ToArray()); System.Console.WriteLine(message); for (int i = 0; i < int.MaxValue; i++) { var t = message; } channel.BasicAck(ea.DeliveryTag, false); }); channel.BasicConsume("fila-01", false, consumer); while (true) { Thread.Sleep(1000); } }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Client.Features.Folders { public interface IFolderRepository { Task<List<Models.CollectPath>> GetPaths(); Task<bool> Insert(Models.CollectPath collectPath); Task<bool> Delete(Models.CollectPath collectPath); Task UpdateFolders(string directory); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GraphicalEditor.DTO.EventSourcingDTO { class RoomSelectionEventDTO { public String Username { get; set; } public int RoomNumber { get; set; } public RoomSelectionEventDTO() {} public RoomSelectionEventDTO(string username, int roomNumber) { Username = username; RoomNumber = roomNumber; } } }
using mato; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class kategori : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btn1_Click(object sender, EventArgs e) { // Konum yeni = new Konum(); // List<ResimClass> ye = yeni.ResimGetir(); //Session["Resim"] = ye; Session["dizi[0]"] = "skdkkjkdjdsjdmdjj"; Response.Redirect("~/zoom.aspx"); } protected void btn2_Click(object sender, EventArgs e) { } protected void lbl4_Click(object sender, EventArgs e) { } protected void lbt11_Click(object sender, EventArgs e) { } protected void lbl3_Click(object sender, EventArgs e) { } protected void lbt5_Click(object sender, EventArgs e) { } protected void lbt6_Click(object sender, EventArgs e) { } protected void lbt7_Click(object sender, EventArgs e) { } protected void lbt8_Click(object sender, EventArgs e) { } protected void lbt9_Click(object sender, EventArgs e) { } protected void lbt10_Click(object sender, EventArgs e) { } }
 using PhotonInMaze.Common; namespace PhotonInMaze.Maze.Generator { //<summary> //Class representation of target cell //</summary> internal struct CellToVisit { public int Row { get; private set; } public int Column { get; private set; } public Direction MoveMade { get; private set; } public CellToVisit(int row, int column, Direction move) { Row = row; Column = column; MoveMade = move; } public override bool Equals(object obj) { if(!(obj is CellToVisit)) { return false; } var visit = (CellToVisit)obj; return Row == visit.Row && Column == visit.Column && MoveMade == visit.MoveMade; } public override int GetHashCode() { var hashCode = 739816171; hashCode = hashCode * -1521134295 + Row.GetHashCode(); hashCode = hashCode * -1521134295 + Column.GetHashCode(); hashCode = hashCode * -1521134295 + MoveMade.GetHashCode(); return hashCode; } public override string ToString() { return string.Format("[MazeCell {0} {1}]", Row, Column); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XH.Queries.Projects.Dtos { public class ProjectOverviewDto { public string Id { get; set; } public virtual string Name { get; set; } public virtual string EntrustEnterprise { get; set; } public virtual string Principal { get; set; } public virtual string PhoneNumber { get; set; } public virtual ICollection<string> Members { get; set; } } }
using Alabo.Domains.Services; using System.Threading.Tasks; using ZKCloud.Open.ApiBase.Models; namespace Alabo.Tables.Domain.Services { /// <summary> /// 授权服务 /// </summary> public interface IOpenService : IService { /// <summary> /// 平台预留手机号码 /// </summary> string OpenMobile { get; } /// <summary> /// 发送单条 使用异步方法发送短信 /// </summary> /// <param name="mobile"></param> /// <param name="message"></param> /// <returns></returns> Task SendRawAsync(string mobile, string message); /// <summary> /// 同步方式发送单条 /// </summary> /// <param name="mobile"></param> /// <param name="message"></param> ApiResult SendRaw(string mobile, string message); /// <summary> /// 生成验证码 /// </summary> /// <param name="mobile"></param> /// <returns></returns> long GenerateVerifiyCode(string mobile); /// <summary> /// 校验验证码 /// </summary> /// <param name="mobile"></param> /// <param name="code"></param> /// <returns></returns> bool CheckVerifiyCode(string mobile, long code); /// <summary> /// 验证手机格式 /// </summary> /// <param name="mobile"></param> /// <returns></returns> bool CheckMobile(string mobile); } }
using System; using System.Web; using System.ComponentModel; namespace Projecten2Groep23.Exceptions { public class MedewerkerAlToegevoegdException : System.Exception { public MedewerkerAlToegevoegdException() : base("De medewerker werd al toegevoegd.") { } public MedewerkerAlToegevoegdException(string message) : base(message) { } } }
using Cs_Gerencial.Aplicacao.Interfaces; using Cs_Gerencial.Dominio.Entities; using Cs_Gerencial.Dominio.Interfaces.Servicos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Gerencial.Aplicacao.ServicosApp { public class AppServicoNacionalidadesOnu: AppServicoBase<NacionalidadesOnu>, IAppServicoNacionalidadesOnu { private readonly IServicoNacionalidadesOnu _servicoNacionalidadesOnu; public AppServicoNacionalidadesOnu(IServicoNacionalidadesOnu servicoNacionalidadesOnu) : base(servicoNacionalidadesOnu) { _servicoNacionalidadesOnu = servicoNacionalidadesOnu; } public NacionalidadesOnu ObterNacionalidadeOnuPorCodigoPais(int codigo) { return _servicoNacionalidadesOnu.ObterNacionalidadeOnuPorCodigoPais(codigo); } } }
namespace CODE.Framework.Wpf.Interfaces { /// <summary> /// Interface to identify the source of some object or element /// </summary> public interface ISourceInformation { /// <summary> /// Location an element was originally loaded from /// </summary> /// <value>The original document load location.</value> string OriginalLoadLocation { get; set; } } }
// // QuickCuts Copyright (c) 2017 C. Jared Cone jared.cone@gmail.com // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Windows; namespace QuickCutsUI { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { public static new App Current { get { return Application.Current as QuickCutsUI.App; } } public bool bLog { get; set; } protected override void OnStartup(StartupEventArgs e) { // this is necessary since the Start With Windows option puts our directory in System32 if (System.Diagnostics.Debugger.IsAttached == false) { var DirName = System.Reflection.Assembly.GetExecutingAssembly().Location; DirName = System.IO.Path.GetDirectoryName(DirName); System.IO.Directory.SetCurrentDirectory(DirName); } bool bResetAppSettings = false; var options = new NDesk.Options.OptionSet() { { "r|reset", "Reset application settings to default", s => bResetAppSettings = s != null }, { "log", "output debug information to a log file", s => bLog = s != null }, }; options.Parse(e.Args); if (bResetAppSettings) { QuickCutsUI.Properties.Settings.Default.Reset(); } base.OnStartup(e); } protected override void OnExit(ExitEventArgs e) { QuickCutsUI.Properties.Settings.Default.Save(); base.OnExit(e); } public static void Log(string msgFormat, params object[] args) { if (App.Current.bLog) { var logFile = "QuickCutsUI.log"; System.IO.StreamWriter log; if (!System.IO.File.Exists(logFile)) { log = new System.IO.StreamWriter(logFile); } else { log = System.IO.File.AppendText(logFile); } log.WriteLine("[{0}] {1}", DateTime.Now, String.Format(msgFormat, args)); log.Close(); } } } }
namespace Arm { public interface IConnect { } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using MineGame.Components; using System; namespace MineGame { class GameOverComponent { private readonly Game1 game; private readonly SpriteFont fontLarge; private const string gameOverText = "You Died"; private Texture2D gradientTexture; private MenuComponent menu; private int screenHeight = Constants.ScreenHeight; private int backgroundAlpha = 0; public GameOverComponent(Game1 game) { this.game = game; fontLarge = game.Content.Load<SpriteFont>("PithazardLarge"); gradientTexture = CreateRedGradientTexture(game.GraphicsDevice, 1000, 600, reverse: true); menu = new MenuComponent(game); menu.AddOption("Retry", () => { game.Restart(); }); menu.AddOption("Exit", () => { game.Exit(); }); } /// <summary> /// Creates a pretty cool gradient texture! /// Used for a background Texture! /// </summary> /// <param name="width">The width of the current viewport</param> /// <param name="height">The height of the current viewport</param> /// A Texture2D with a gradient applied. private Texture2D CreateRedGradientTexture(GraphicsDevice graphicsDevice, int width, int height, bool reverse, int gradientOffset = 12) { var texture = new Texture2D(graphicsDevice, width, height); Color[] bgc = new Color[height * width]; int texColour; // Defines the colour of the gradient. for (int i = 0; i < bgc.Length; i++) { texColour = (i / (screenHeight * gradientOffset)); // Create a pixel that's slightly more Red then the previous one bgc[i] = new Color(texColour, 0, 0, 128); } if (reverse) { Array.Reverse(bgc); } texture.SetData(bgc); return texture; } internal void Update() { if (backgroundAlpha < 255) { backgroundAlpha += 3; } menu.Update(); } public void Draw(SpriteBatch sb) { sb.Draw(gradientTexture, new Vector2(0, 0), new Color(backgroundAlpha, backgroundAlpha, backgroundAlpha)); DrawTitle(sb); menu.Draw(sb); } private void DrawTitle(SpriteBatch sb) { var stringLength = fontLarge.MeasureString(gameOverText); var screenCenter = Constants.ScreenWidth / 2; var textX = screenCenter - stringLength.X / 2; var textY = 100; sb.DrawString(fontLarge, gameOverText, new Vector2(textX, textY), Color.Red); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Docller.Core.Common; using Docller.Core.Storage; namespace Docller { public class CloudDeployment { public static void Initialize() { if (DocllerEnvironment.UseAzureBlobStorage) { CreateContainers(); } } private static void CreateContainers() { IBlobStorageProvider blobStorage = Factory.GetInstance<IBlobStorageProvider>(); blobStorage.CreateContainer(Constants.SystemContainer); blobStorage.CreateContainer(Constants.PreviewImagesContainer); blobStorage.CreateContainer(Constants.CustomerContainer); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using Ghostpunch.OnlyDown.Common; using Ghostpunch.OnlyDown.Common.Views; using Ghostpunch.OnlyDown.Menu.ViewModels; using strange.extensions.mediation.impl; using strange.extensions.signal.impl; using UnityEngine; using UnityEngine.UI; namespace Ghostpunch.OnlyDown.Menu.Views { public class MenuView : View { public GameObject _mainMenu, _gameOverMenu; [Inject] public MenuViewModel VM { get; set; } protected override void Start() { base.Start(); VM.PropertyChanged += VM_PropertyChanged; } private void VM_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsMainMenuVisible") { _mainMenu.SetActive(VM.IsMainMenuVisible); } else if (e.PropertyName == "IsGameOverVisible") { //Debug.Log("Setting _gameOverMenu.SetActive to ") _gameOverMenu.SetActive(VM.IsGameOverVisible); } if (e.PropertyName == "MainMenuAlpha") { _mainMenu.GetComponent<CanvasRenderer>().SetAlpha(VM.MainMenuAlpha); } } } }
using Microsoft.EntityFrameworkCore; using CS295NTermProject.Models; namespace CS295NTermProject.Repositories { public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<MusicTrack> MusicTracks { get; set; } public DbSet<GenreTag> GenreTags { get; set; } public DbSet<MoodTag> MoodTags { get; set; } public DbSet<InstrumentTag> InstrumentTags { get; set; } public DbSet<OtherTag> OtherTags { get; set; } public DbSet<MusicTrackMoodTag> MusicTrackMoodTags { get; set; } public DbSet<Comment> Comments { get; set; } public DbSet<Rating> Ratings { get; set; } public DbSet<Message> Messages { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<MusicTrackMoodTag>() .HasKey(x => new { x.MusicTrackID, x.MoodTagID }); modelBuilder.Entity<MusicTrackMoodTag>() .HasOne(x => x.MusicTrack) .WithMany(y => y.MusicTrackMoodTags) .HasForeignKey(y => y.MusicTrackID); modelBuilder.Entity<MusicTrackMoodTag>() .HasOne(x => x.MoodTag) .WithMany(y => y.MusicTrackMoodTags) .HasForeignKey(y => y.MoodTagID); modelBuilder.Entity<MusicTrackInstrumentTag>() .HasKey(x => new { x.MusicTrackID, x.InstrumentTagID }); modelBuilder.Entity<MusicTrackInstrumentTag>() .HasOne(x => x.MusicTrack) .WithMany(y => y.MusicTrackInstrumentTags) .HasForeignKey(y => y.MusicTrackID); modelBuilder.Entity<MusicTrackInstrumentTag>() .HasOne(x => x.InstrumentTag) .WithMany(y => y.MusicTrackInstrumentTags) .HasForeignKey(y => y.InstrumentTagID); modelBuilder.Entity<MusicTrackOtherTag>() .HasKey(x => new { x.MusicTrackID, x.OtherTagID }); modelBuilder.Entity<MusicTrackOtherTag>() .HasOne(x => x.MusicTrack) .WithMany(y => y.MusicTrackOtherTags) .HasForeignKey(y => y.MusicTrackID); modelBuilder.Entity<MusicTrackOtherTag>() .HasOne(x => x.OtherTag) .WithMany(y => y.MusicTrackOtherTags) .HasForeignKey(y => y.OtherTagID); } } }
using UnityEngine; using System.Collections; public class skull : monster { public override void Update () { base.Update(); if(onLight) { PRBody = player.GetComponent<Rigidbody2D>(); RBody.velocity = PRBody.velocity*2; } else { PRBody = null; if (!isAlerted) { if (Timer >= 2f) { RBody.velocity = new Vector2(Random.Range(-1, 2), Random.Range(-1, 2)); Timer = 0; } else { Timer += Time.deltaTime; } } else if (isAlerted) { target = player.GetComponent<Transform>(); this.transform.position = Vector3.MoveTowards(transform.position, target.position, speed); } } if(!ninjaGirl.theLight.activeSelf) { onLight = false; } } void OnCollisionEnter2D(Collision2D col) { if(col.transform.tag == "player") { ninjaGirl.shortage = true; } } }
using System; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using ClotheOurKids.Web.Models; using System.Net.Http; using System.Collections.Generic; using System.Web.Helpers; using ClotheOurKids.Model; using ClotheOurKids.Model.Repository; using System.Configuration; using Microsoft.AspNet.Identity.EntityFramework; namespace ClotheOurKids.Web.Controllers { [Authorize] public class AccountController : Controller { private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager; private ApplicationRoleManager _roleManager; public AccountController() { } public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, ApplicationRoleManager roleManager ) { UserManager = userManager; SignInManager = signInManager; RoleManager = roleManager; } public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } // Utility // Add RoleManager #region public ApplicationRoleManager RoleManager public ApplicationRoleManager RoleManager { get { return _roleManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationRoleManager>(); } private set { _roleManager = value; } } #endregion // Add CreateAdminIfNeeded #region private void CreateAdminIfNeeded() private void CreateAdminRoleIfNeeded() { // Get Admin Account string AdminUserName = "givekidsclothes@gmail.com"; // See if Admin exists var objAdminUser = UserManager.FindByEmail(AdminUserName); if (objAdminUser != null) { //See if the Admin role exists if (!RoleManager.RoleExists("Administrator")) { // Create the Admin Role (if needed) IdentityRole objAdminRole = new IdentityRole("Administrator"); RoleManager.Create(objAdminRole); } // Put user in Admin role UserManager.AddToRole(objAdminUser.Id, "Administrator"); } } #endregion // // GET: /Login [AllowAnonymous] [Route("Login", Name = "LoginPage")] public ActionResult Login(string returnUrl) { return View(); } // // POST: /Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { string totalError; if (!ModelState.IsValid) { //return PartialView("_LoginForm", model); totalError = CompileErrorMsg(ModelState); return Json(new { Success = 0, errorMsg = new Exception(totalError).Message.ToString() }); } var user = await UserManager.FindAsync(model.Email, model.Password); if (user != null) { if (await UserManager.IsEmailConfirmedAsync(user.Id)) { await SignInManager.SignInAsync(user, model.RememberMe, model.RememberMe); return Json(new { Success = 1, errorMsg = "" }); } else { //var callbackUrl = Url.Action("Confirm", "Account", new { Email = user.Email}, protocol: Request.Url.Scheme); var tempAppSetting = ConfigurationManager.AppSettings["SMTPHost"]; string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Clothe Our Kids Account Confirmation"); return Json(new { Success = 0, errorMsg = "You must have a confirmed email to log on. <br/> The confirmation token has been resent to your email address."}); } } else { ModelState.AddModelError("", "Invalid username or password."); } totalError = CompileErrorMsg(ModelState); ////If we got this far, something failed, redisplay form return Json(new { Success = 0, errorMsg = new Exception(totalError).Message.ToString(), confirmEmail = "" }); // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); //switch (result) //{ // case SignInStatus.Success: // return RedirectToLocal(returnUrl); // case SignInStatus.LockedOut: // return View("Lockout"); // case SignInStatus.RequiresVerification: // return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); // case SignInStatus.Failure: // default: // ModelState.AddModelError("", "Invalid login attempt."); // //return PartialView("_LoginForm", model); // // return View(model); //} } private string CompileErrorMsg (ModelStateDictionary ModelState) { string totalError = ""; foreach (var obj in ModelState.Values) { foreach (var error in obj.Errors) { if (!string.IsNullOrEmpty(error.ErrorMessage)) { totalError = totalError + error.ErrorMessage + Environment.NewLine; } } } return totalError; } // // GET: /Account/VerifyCode [AllowAnonymous] public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe) { // Require that the user has already logged in via username/password or external login if (!await SignInManager.HasBeenVerifiedAsync()) { return View("Error"); } return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. // You can configure the account lockout settings in IdentityConfig var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser); switch (result) { case SignInStatus.Success: return RedirectToLocal(model.ReturnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid code."); return View(model); } } // // GET: /Account/Register [AllowAnonymous] [Route("Register", Name = "RegisterPage")] public ActionResult Register() { //CreateAdminRoleIfNeeded(); var model = new RegisterViewModel(); PopulateRegisterModel(model); return View(model); } [AllowAnonymous] [AcceptVerbs(HttpVerbs.Get)] [Route("Get-Offices", Name = "GetOffices")] public ActionResult GetOfficesByOfficeTypeId (string officeTypeId) { if (String.IsNullOrEmpty(officeTypeId)) { throw new ArgumentNullException("officeTypeId"); } int id = 0; var repository = new RegisterFormRepository(); bool isValid = Int32.TryParse(officeTypeId, out id); var offices = repository.GetOfficesByOfficeType(id); var result = (from o in offices select new { id = o.OfficeId, name = o.Name }).ToList(); return Json(result, JsonRequestBehavior.AllowGet); } [AllowAnonymous] [AcceptVerbs(HttpVerbs.Get)] [Route("Get-Positions", Name = "GetPositions")] public ActionResult GetPositionsByOfficeId (string officeTypeId) { if (String.IsNullOrEmpty(officeTypeId)) { throw new ArgumentNullException("officeTypeId"); } int id = 0; var repository = new RegisterFormRepository(); bool isValid = Int32.TryParse(officeTypeId, out id); var positions = repository.GetPositionsByOfficeType(id); var result = (from p in positions select new { id = p.PositionId, name = p.Name }).ToList(); return Json(result, JsonRequestBehavior.AllowGet); } private RegisterViewModel PopulateRegisterModel (RegisterViewModel model) { var repository = new RegisterFormRepository(); //Populate Office Types var officeTypes = repository.GetAllOfficeTypes(); var officeTypeList = (from ot in officeTypes select new { id = ot.OfficeTypeId, name = ot.Name }).ToList(); foreach (var officeType in officeTypeList) { model.AvailableOfficeTypes.Add(new SelectListItem() { Text = officeType.name, Value = officeType.id.ToString() }); } //Populate Contact Methods var contactMethods = repository.GetAllContactMethods(); var contactMethodList = (from c in contactMethods select new { id = c.ContactMethodId, name = c.Name }).ToList(); foreach (var contactMethod in contactMethodList) { model.AvailableContactMethods.Add(new SelectListItem() { Text = contactMethod.name, Value = contactMethod.id.ToString() }); } //Seed Position and Office Dropdowns with placeholder model.AvailablePositions.Add(new SelectListItem() { Text = "Choose Your Position", Value = "0" }); model.AvailableOffices.Add(new SelectListItem() { Text = "Choose Your Office", Value = "0" }); //Populate Office and Position dropdowns based on OfficeTypeId if (model.OfficeTypeId.HasValue) { var offices = repository.GetOfficesByOfficeType((int)model.OfficeTypeId); var officeList = (from o in offices select new { id = o.OfficeId, name = o.Name }).ToList(); foreach (var office in officeList) { model.AvailableOffices.Add(new SelectListItem() { Text = office.name, Value = office.id.ToString() }); } var positions = repository.GetPositionsByOfficeType((int)model.OfficeTypeId); var positionList = (from p in positions select new { id = p.PositionId, name = p.Name }).ToList(); foreach (var position in positionList) { model.AvailablePositions.Add(new SelectListItem() { Text = position.name, Value = position.id.ToString() }); } } return model; } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] [Route("Register", Name = "RegisterPost")] public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, PositionId = (short)model.PositionId, OfficeId = (short)model.OfficeId, PhoneNumber = model.PhoneNumber, ContactMethodId = (short)model.ContactMethodId }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { //Commented to prevent login until user confirms email address //await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false); string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Clothe Our Kids Account Confirmation"); // Uncomment to debug locally // TempData["ViewBagLink"] = callbackUrl; return RedirectToAction("Confirm", "Account", new { Email = user.Email }); } AddErrors(result); } PopulateRegisterModel(model); // If we got this far, something failed, redisplay form return View(model); } [AllowAnonymous] public ActionResult Confirm (string Email) { ViewBag.Email = Email; return View(); } // // GET: /Account/ConfirmEmail [AllowAnonymous] public async Task<ActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var result = await UserManager.ConfirmEmailAsync(userId, code); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } private async Task<string> SendEmailConfirmationTokenAsync(string userID, string subject) { // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link: string code = await UserManager.GenerateEmailConfirmationTokenAsync(userID); var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = userID, code = code }, protocol: Request.Url.Scheme); await UserManager.SendEmailAsync(userID, subject, "You must confirm your email before you can log in to GiveKidsClothes.com and request clothes from Clothe Our Kids. Please confirm your account by clicking <a href=\"" + callbackUrl + "\"> here</a>"); return callbackUrl; } // // GET: /Account/ForgotPassword [AllowAnonymous] [Route("ForgotPassword", Name = "ForgotPasswordPage")] public ActionResult ForgotPassword() { return View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] [Route("ForgotPassword", Name = "ForgotPasswordPost")] public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await UserManager.FindByNameAsync(model.Email); if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); await UserManager.SendEmailAsync(user.Id, "Reset Password", "We receieved a request to reset your password for GiveKidsClothes.com. <br/> <br/> If you did not request this reset, please let us know at 256-887-KIDS(5437). <br/> <br/> Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>"); return RedirectToAction("ForgotPasswordConfirmation", "Account"); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ForgotPasswordConfirmation [AllowAnonymous] public ActionResult ForgotPasswordConfirmation() { return View(); } // // GET: /Account/ResetPassword [AllowAnonymous] public ActionResult ResetPassword(string code) { return code == null ? View("Error") : View(); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await UserManager.FindByNameAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction("ResetPasswordConfirmation", "Account"); } var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction("ResetPasswordConfirmation", "Account"); } AddErrors(result); return View(); } // // GET: /Account/ResetPasswordConfirmation [AllowAnonymous] public ActionResult ResetPasswordConfirmation() { return View(); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult ExternalLogin(string provider, string returnUrl) { // Request a redirect to the external login provider return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl })); } // // GET: /Account/SendCode [AllowAnonymous] public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe) { var userId = await SignInManager.GetVerifiedUserIdAsync(); if (userId == null) { return View("Error"); } var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } // Generate the token and send it if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider)) { return View("Error"); } return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); } // // GET: /Account/ExternalLoginCallback [AllowAnonymous] public async Task<ActionResult> ExternalLoginCallback(string returnUrl) { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return RedirectToAction("Login"); } // Sign in the user with this external login provider if the user already has a login var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }); case SignInStatus.Failure: default: // If the user does not have an account, then prompt the user to create an account ViewBag.ReturnUrl = returnUrl; ViewBag.LoginProvider = loginInfo.Login.LoginProvider; return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, PositionId = model.PositionId, OfficeId = model.OfficeId }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); return RedirectToAction("Index", "Home"); } // // GET: /Account/ExternalLoginFailure [AllowAnonymous] public ActionResult ExternalLoginFailure() { return View(); } protected override void Dispose(bool disposing) { if (disposing) { if (_userManager != null) { _userManager.Dispose(); _userManager = null; } if (_signInManager != null) { _signInManager.Dispose(); _signInManager = null; } } base.Dispose(disposing); } #region Helpers // Used for XSRF protection when adding external logins private const string XsrfKey = "XsrfId"; private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } return RedirectToAction("Index", "Home"); } internal class ChallengeResult : HttpUnauthorizedResult { public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) { } public ChallengeResult(string provider, string redirectUri, string userId) { LoginProvider = provider; RedirectUri = redirectUri; UserId = userId; } public string LoginProvider { get; set; } public string RedirectUri { get; set; } public string UserId { get; set; } public override void ExecuteResult(ControllerContext context) { var properties = new AuthenticationProperties { RedirectUri = RedirectUri }; if (UserId != null) { properties.Dictionary[XsrfKey] = UserId; } context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); } } #endregion } }
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using TennisBookings.Web.External; using TennisBookings.Web.IntegrationTests.Fakes; using TennisBookings.Web.IntegrationTests.Helpers; using TennisBookings.Web.Services; namespace TennisBookings.Web.IntegrationTests { public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class { protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseEnvironment("Production"); builder.ConfigureTestServices(services => { services.AddSingleton<IWeatherApiClient, FakeWithDataWeatherApiClient>(); services.AddSingleton<IDateTime, FixedDateTime>(); }); } } }
using NUnit.Framework; using OpenQA.Selenium; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Training { public class Task17 : Base { [Test] public void Task_17() { driver.Navigate().GoToUrl("http://localhost/litecart/admin/"); driver.FindElement(By.Name("username")).SendKeys("admin"); driver.FindElement(By.Name("password")).SendKeys("admin"); driver.FindElement(By.Name("login")).Click(); driver.FindElement(By.LinkText("Catalog")).Click(); driver.FindElement(By.LinkText("Rubber Ducks")).Click(); List<string> productLinks = new List<string>(); var products = driver.FindElements(By.CssSelector(".dataTable .row td:nth-child(3) a")); for (int i = 2; i < products.Count-5; i++) { productLinks.Add(products[i].GetAttribute("href")); } foreach (var link in productLinks) { driver.Navigate().GoToUrl(link); Assert.IsEmpty(driver.Manage().Logs.GetLog(LogType.Browser).ToList()); } } } }
using Application.Base; using Application.Models; using Application.Requests; using Domain.Contracts; using Domain.Entities; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; namespace Application.Services { public class EmpleadoService : Service<Empleado> { public EmpleadoService(IUnitOfWork unitOfWork) : base(unitOfWork, unitOfWork.EmpleadoRepository) { } public Response<Empleado> Crear(EmpleadoRequest request) { Empleado empleado = _unitOfWork.EmpleadoRepository.FindFirstOrDefault(x => x.Cedula == request.Cedula); if (empleado != null) { return new Response<Empleado> { Mensaje = $"El empleado con Cédula = {request.Cedula}, ya está registrado.", Entity = request.ToEntity() }; } return base.Agregar(request.ToEntity()); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems.AdventOfCode.Y2022 { public class Problem13 : AdventOfCodeBase { public override string ProblemName => "Advent of Code 2022: 13"; public override string GetAnswer() { return Answer1(Input()).ToString(); } public override string GetAnswer2() { return Answer2(Input()).ToString(); } private int Answer1(List<string> input) { var pairs = GetPairs(input); return GetSum(pairs); } private int Answer2(List<string> input) { input.Add("[[2]]"); input.Add("[[6]]"); var items = GetAll(input); var divider1 = items[items.Count - 1]; var divider2 = items[items.Count - 2]; divider1.IsDivider = true; divider2.IsDivider = true; items = items.OrderBy(x => x, new ItemComparer()).ToList(); return (items.IndexOf(divider1) + 1) * (items.IndexOf(divider2) + 1); } private int GetSum(List<Item[]> pairs) { int index = 1; int sum = 0; var comparer = new ItemComparer(); foreach (var pair in pairs) { var order = comparer.Compare(pair[0], pair[1]); if (order == -1) sum += index; index++; } return sum; } private List<Item[]> GetPairs(List<string> input) { var pairs = new List<Item[]>(); int index = 0; while (index < input.Count) { var item1 = GetList(input[index].Substring(1, input[index].Length - 2)); var item2 = GetList(input[index + 1].Substring(1, input[index + 1].Length - 2)); pairs.Add(new Item[] { item1, item2 }); index += 3; } return pairs; } private List<Item> GetAll(List<string> input) { var items = new List<Item>(); foreach (var line in input) { if (!string.IsNullOrEmpty(line)) items.Add(GetList(line.Substring(1, line.Length - 2))); } return items; } private Item GetList(string text) { Item list = new ItemList() { Items = new List<Item>() }; var highest = list; List<char> currentNum = null; foreach (var digit in text) { if (digit == '[') { var newList = new ItemList() { Items = new List<Item>(), Parent = list }; ((ItemList)list).Items.Add(newList); list = newList; } else if (digit == ']') { if (currentNum != null) { ((ItemList)list).Items.Add(new ItemNumber() { Parent = list, Number = Convert.ToInt32(new string(currentNum.ToArray())) }); currentNum = null; } list = list.Parent; } else if (digit == ',') { if (currentNum != null) { ((ItemList)list).Items.Add(new ItemNumber() { Parent = list, Number = Convert.ToInt32(new string(currentNum.ToArray())) }); currentNum = null; } } else { if (currentNum == null) currentNum = new List<char>(); currentNum.Add(digit); } } if (currentNum != null) { ((ItemList)list).Items.Add(new ItemNumber() { Parent = list, Number = Convert.ToInt32(new string(currentNum.ToArray())) }); } return highest; } private class ItemComparer : IComparer<Item> { public int Compare(Item x, Item y) { if (x.IsList != y.IsList) { if (!x.IsList) { var newList = new ItemList() { Items = new List<Item>(), Parent = x.Parent }; var number = new ItemNumber() { Number = ((ItemNumber)x).Number, Parent = newList }; newList.Items.Add(number); x = newList; } else { var newList = new ItemList() { Items = new List<Item>(), Parent = y.Parent }; var number = new ItemNumber() { Number = ((ItemNumber)y).Number, Parent = newList }; newList.Items.Add(number); y = newList; } } if (!x.IsList && !y.IsList) { var num1 = ((ItemNumber)x).Number; var num2 = ((ItemNumber)y).Number; if (num1 > num2) { return 1; } else if (num1 < num2) { return -1; } } else { var list1 = ((ItemList)x).Items; var list2 = ((ItemList)y).Items; int index = 0; do { if (index == list1.Count && index == list2.Count) { return 0; } else if (index == list1.Count) { return -1; } else if (index == list2.Count) { return 1; } else { var order = Compare(list1[index], list2[index]); if (order != 0) return order; } index++; } while (true); } return 0; } } private abstract class Item { public abstract bool IsList { get; } public Item Parent { get; set; } public bool IsDivider { get; set; } } private class ItemList : Item { public List<Item> Items { get; set; } public override bool IsList => true; } private class ItemNumber : Item { public int Number { get; set; } public override bool IsList => false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using OccBooking.Persistence.DbContexts; using OccBooking.Persistence.Entities; using OccBooking.Persistence.Repositories; using Moq; using OccBooking.Common.Dispatchers; using OccBooking.Domain.Entities; using OccBooking.Domain.Enums; using OccBooking.Domain.Events; using OccBooking.Domain.ValueObjects; using Xunit; namespace OccBooking.Persistence.Tests.Repositories { public class ReservationRequestRepositoryTests { public static Client CorrectClient => new Client("Michal", "Kowalski", "michal@michal.com", "505111111"); public static Address CorrectAddress => new Address("Akacjowa", "Orzesze", "43-100", "śląskie"); public static Place CorrectPlace => new Place(new Guid("619e8c4e-69ae-482a-98eb-492afe60352b"), "Calvados", false, "", CorrectAddress, new Guid("4ea10f9e-ae5f-43a1-acfa-c82b678e6ee1")); [Fact] public async Task GetImpossibleReservationRequestsAsync_ShouldWork() { var dbContext = GetDatabaseContext(); var hallRepositoryMock = new Mock<IHallRepository>(); var place = CorrectPlace; var hall1 = new Hall(Guid.NewGuid(), "Big", 30); var hall2 = new Hall(Guid.NewGuid(), "Big", 30); var hall3 = new Hall(Guid.NewGuid(), "Big", 30); var menu = new Menu(Guid.NewGuid(), "Vegetarian", MenuType.Vegetarian, 50); place.AllowParty(OccasionType.Wedding); place.AssignMenu(menu); hall1.AddPossibleJoin(hall2); hall2.AddPossibleJoin(hall3); place.AddHall(hall1); place.AddHall(hall2); place.AddHall(hall3); var reservation1 = new ReservationRequest(Guid.NewGuid(), DateTime.Today, CorrectClient, OccasionType.Wedding, new List<PlaceAdditionalOption>(), new List<MenuOrder>() {new MenuOrder(menu, 50)}); var reservation2 = new ReservationRequest(Guid.NewGuid(), DateTime.Today, CorrectClient, OccasionType.Wedding, new List<PlaceAdditionalOption>(), new List<MenuOrder>() {new MenuOrder(menu, 50)}); var reservation3 = new ReservationRequest(Guid.NewGuid(), DateTime.Today.AddDays(1), CorrectClient, OccasionType.Wedding, new List<PlaceAdditionalOption>(), new List<MenuOrder>() {new MenuOrder(menu, 50)}); var reservation4 = new ReservationRequest(Guid.NewGuid(), DateTime.Today, CorrectClient, OccasionType.Wedding, new List<PlaceAdditionalOption>(), new List<MenuOrder>() {new MenuOrder(menu, 30)}); dbContext.Add(menu); dbContext.Add(reservation1); dbContext.Add(reservation2); dbContext.Add(reservation3); dbContext.Add(reservation4); dbContext.Add(place); dbContext.Add(hall1); dbContext.Add(hall2); dbContext.Add(hall3); place.MakeReservationRequest(reservation1); place.MakeReservationRequest(reservation2); place.MakeReservationRequest(reservation3); place.MakeReservationRequest(reservation4); hall1.MakeReservation(reservation1); hall2.MakeReservation(reservation1); reservation1.Accept(place.Id, new List<Guid>() {hall1.Id, hall2.Id}.AsEnumerable()); dbContext.SaveChanges(); hallRepositoryMock.Setup(m => m.GetHallsAsync(place.Id)) .ReturnsAsync(new List<Hall>() {hall1, hall2, hall3}); var eventDispatcherMock = new Mock<EventDispatcher>(null); var sut = new ReservationRequestRepository(dbContext, hallRepositoryMock.Object, eventDispatcherMock.Object); var result = await sut.GetImpossibleReservationRequestsAsync(place.Id); Assert.Contains(reservation2, result); Assert.DoesNotContain(reservation1, result); Assert.DoesNotContain(reservation3, result); Assert.DoesNotContain(reservation4, result); } private OccBookingDbContext GetDatabaseContext() { var options = new DbContextOptionsBuilder<OccBookingDbContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()).Options; var databaseContext = new OccBookingDbContext(options); databaseContext.Database.EnsureCreated(); return databaseContext; } } }
using UnityEngine; //列舉(下拉式選單) public enum StateNPC { NOMission,Missioning,Finish } //ScriptableObject腳本化物件:將資料儲存於專案 //CreateAssetMenu建立菜單:檔案名稱與菜單名稱(fileName = "NPC 資料" , menuName = "TANG/NPC 資料")] [CreateAssetMenu(fileName = "NPC 資料" , menuName = "TANG/NPC 資料")] public class NPCData : ScriptableObject { [Header("打字速度"), Range(0f, 3f)] public float speed = 0.5f; [Header("打字音效")] public AudioClip soundType; [Header("任務需求數量"), Range(5, 50)] public int count; [Header("對話"), TextArea(3,10)] public string[] dialogs = new string[3]; [Header("NPC 狀態")] public StateNPC state; }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class Health : MonoBehaviour { public float health = 100f; public float MollysHealth = 100f; public GameObject CanvasObject; public Text text; // for the setting of health on screen public Text ammoText; // for the setting of ammo on screen private int randHealth; // store result of random number gen for health during health drop private int healthLow = 1; // bottom range of health during health drop private int healthHigh = 10; // bottom range of health during health drop private int randAmmo; // store result of random number gen for ammo during an ammo drop private int ammoLow = 1; // bottom range of ammo during an ammo drop private int ammoHigh = 10; // bottom range of ammo during an ammo drop // Use this for initialization void Start () { // Mollys Health Starts Off At 100 PlayerPrefs.SetFloat("MollysHealth", health); PlayerPrefs.SetInt("latheExperience", 0); PlayerPrefs.SetInt("lathedAmmo", 0); //MollysHealth = PlayerPrefs.GetInt("MollysHealth"); } // Update is called once per frame void Update () { MollysHealth = PlayerPrefs.GetFloat("MollysHealth"); text.text = "Health : " + Mathf.Round(MollysHealth); if (MollysHealth <= 0) { //Application.Quit(); loadMenu(); print("Ahhh I have just diedddddddd......"); } } public void loadMenu() { //int currentProfile = PlayerPrefs.GetInt("currentProfile"); int currentProfile = 1; if (currentProfile == 1) { print("You are within the load menu section"); int dayCounter = PlayerPrefs.GetInt("dayCounter"); PlayerPrefs.SetInt("profile1_dayCounter", dayCounter); int ShotGunAmmo = PlayerPrefs.GetInt("ShotGunAmmo"); PlayerPrefs.SetInt("profile1_ShotGunAmmo", ShotGunAmmo); int lathedAmmo = PlayerPrefs.GetInt("lathedAmmo"); PlayerPrefs.SetInt("profile1_lathedAmmo", lathedAmmo); int IronTot = PlayerPrefs.GetInt("IronTot"); PlayerPrefs.SetInt("profile1_IronTot", IronTot); int RockTot = PlayerPrefs.GetInt("RockTot"); PlayerPrefs.SetInt("profile1_RockTot", RockTot); int latheExperience = PlayerPrefs.GetInt("latheExperience"); PlayerPrefs.SetInt("profile1_latheExperience", latheExperience); } SceneManager.LoadScene(0); // 0 is the menu screen // set to 1 if you want to restart level away when you die print("This is from the loadMenu function......"); } // Once you are hit once by ghost zombie private void OnTriggerEnter(Collider other) { //print("Printed from OnTriggerEnter"); if (other.gameObject.tag == "Zombie") { PlayerPrefs.SetFloat("MollysHealth", health = health - 5); //print("Molly Is Hurt By A Zombie - OnTriggerEnter." + health); } if (other.gameObject.tag == "TastyBush") { //randHealth = Random.Range(healthLow, healthHigh); PlayerPrefs.SetFloat("MollysHealth", health = health + 40); //other.gameObject.Destroy(gameObject, 19.0f); Destroy(other.gameObject); //print("Molly Is Hurt By A Zombie - OnTriggerEnter." + health); } if (other.gameObject.tag == "healthCube") { randHealth = Random.Range(healthLow, healthHigh); PlayerPrefs.SetFloat("MollysHealth", health = health + randHealth); //other.gameObject.Destroy(gameObject, 19.0f); Destroy(other.gameObject); //print("Molly Is Hurt By A Zombie - OnTriggerEnter." + health); } if (other.gameObject.tag == "ammoCube") { int currentAmmo = PlayerPrefs.GetInt("ShotGunAmmo"); randAmmo = Random.Range(ammoLow, ammoHigh); PlayerPrefs.SetInt("ShotGunAmmo", currentAmmo = currentAmmo + randAmmo); currentAmmo = PlayerPrefs.GetInt("ShotGunAmmo"); ammoText.text = currentAmmo.ToString(); Destroy(other.gameObject); } } private void OnTriggerStay(Collider other) { //print("Printed from OnTriggerStay"); if (other.gameObject.tag == "Zombie") { PlayerPrefs.SetFloat("MollysHealth", health = health - 0.1f); //print("Molly Is Hurt By A Zombie - OnTriggerStay." + health); } } private void OnTriggerExit(Collider other) { //print("Printed from OnTriggerExit"); if (other.gameObject.tag == "Zombie") { PlayerPrefs.SetFloat("MollysHealth", health = health - 2); //print("Molly Is Hurt By A Zombie - OnTriggerExit." + health); } } }
namespace BalancedBrackets { using System; public class StartUp { public static void Main() { int num = int.Parse(Console.ReadLine()); int firstBracket = 0; int secondBracket = 0; bool closingBrackets = false; for (int i = 0; i < num; i++) { string character = Console.ReadLine(); if (character.Length == 1) { char currentChar = char.Parse(character); firstBracket += currentChar == '(' ? (int)1 : (int)0; secondBracket += currentChar == ')' ? (int)1 : (int)0; if (!(firstBracket == secondBracket || firstBracket == secondBracket + 1)) { closingBrackets = true; } } } bool isBalanced = firstBracket == secondBracket; Console.WriteLine(isBalanced && !closingBrackets ? "BALANCED" : "UNBALANCED"); } } }
using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using WorkScheduleManagement.Data.Entities; using WorkScheduleManagement.Data.Enums; namespace WorkScheduleManagement.Persistence.DbInitialization { public static class RequestTypesInitializer { public static async Task InitializeAsync(AppDbContext context) { var requestTypes = new List<RequestTypes> { new RequestTypes {Id = RequestType.OnHoliday, Name = "Заявка на отгул"}, new RequestTypes {Id = RequestType.OnVacation, Name = "Заявка на отпуск"}, new RequestTypes {Id = RequestType.OnRemoteWork, Name = "Заявка на удаленную работу"}, new RequestTypes {Id = RequestType.OnDayOffInsteadOverworking, Name = "Заявка на выходной в счет отработки"}, new RequestTypes {Id = RequestType.OnDayOffInsteadVacation, Name = "Заявка на выходной в счет отпуска"}, }; foreach (var requestType in requestTypes) { if (await context.RequestTypes.FirstOrDefaultAsync(s => s.Id == requestType.Id) == null) { await context.RequestTypes.AddAsync(requestType); } } await context.SaveChangesAsync(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using TransitionMetalColourRevisionGame.TransMetals; namespace TransitionMetalColourRevisionGame { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { bool popupMenuOpened = false; GameControl _GameControl = new GameControl(); HighScore _HighScore = new HighScore(); public string chosenMetal; public string chosenReagent; int amtLeft = 8; public MainWindow() { InitializeComponent(); chosenMetal = _GameControl.CycleThroughMetals(); chosenReagent = _GameControl.CycleThroughReagents(); _GameControl.SetButtonContent(chosenReagent,chosenMetal,ReagentAdded, transMetal, Opt1, Opt2, Opt3, Opt4, Opt5, Opt6, Opt7, Opt8); _HighScore.SetHighScore(highStreakNum); Opt1.Click += HandleButtonClicks; Opt2.Click += HandleButtonClicks; Opt3.Click += HandleButtonClicks; Opt4.Click += HandleButtonClicks; Opt5.Click += HandleButtonClicks; Opt6.Click += HandleButtonClicks; Opt7.Click += HandleButtonClicks; Opt8.Click += HandleButtonClicks; setTransMetalMenu(transMetal); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); Application.Current.Shutdown(); } public void SwitchMetals(string newMetal) { _GameControl.RefreshReagents(); _GameControl.ClearButtons(Opt1, Opt2, Opt3, Opt4, Opt5, Opt6, Opt7, Opt8); chosenReagent = _GameControl.CycleThroughReagents(); _GameControl.SetButtonContent(chosenReagent,newMetal, ReagentAdded, transMetal, Opt1, Opt2, Opt3, Opt4, Opt5, Opt6, Opt7, Opt8); amtLeft = 8; Opt1.IsEnabled = true; Opt2.IsEnabled = true; Opt3.IsEnabled = true; Opt4.IsEnabled = true; Opt5.IsEnabled = true; Opt6.IsEnabled = true; Opt7.IsEnabled = true; Opt8.IsEnabled = true; } private void HandleButtonClicks(object sender, RoutedEventArgs e) { Button button = sender as Button; CheckForCorrect(button); } public void CheckForCorrect(Button button) { CustomMessageBox msgBox = new CustomMessageBox(); if ((string)button.Tag == "correct" && amtLeft != 0) { amtLeft -= 1; msgBox.SetMsgBox("Correct!",_GameControl.FindHexAqFormula(chosenMetal),_GameControl.FindHexAqColour(chosenMetal), button); msgBox.Owner = this; msgBox.WindowStartupLocation = WindowStartupLocation.CenterOwner; msgBox.Show(); _HighScore.UpdateCurScore("correct", curStreakNum, highStreakNum); _GameControl.ClearButtons(Opt1,Opt2,Opt3,Opt4,Opt5,Opt6,Opt7, Opt8); chosenReagent = _GameControl.CycleThroughReagents(); _GameControl.SetButtonContent(chosenReagent, chosenMetal, ReagentAdded, transMetal, Opt1, Opt2, Opt3, Opt4, Opt5, Opt6, Opt7, Opt8); button.IsEnabled = false; //correctAnswer = true; } else if ((string)button.Tag != "correct" && amtLeft != 0) { msgBox.SetMsgBox("Wrong!", _GameControl.FindHexAqFormula(chosenMetal), _GameControl.FindHexAqColour(chosenMetal), button); msgBox.Owner = this; msgBox.WindowStartupLocation = WindowStartupLocation.CenterOwner; msgBox.Show(); _HighScore.UpdateCurScore("incorrect", curStreakNum, highStreakNum); } if (amtLeft == 0) { string newMetal = _GameControl.CycleThroughMetals(); chosenMetal = newMetal; amtLeft = 8; SwitchMetals(newMetal); } } public void setTransMetalMenu(TextBlock transMetal) { ContextMenu metalMenu = new ContextMenu(); MenuItem Aluminium = new MenuItem(); MenuItem Chromium = new MenuItem(); MenuItem Cobalt = new MenuItem(); MenuItem Copper = new MenuItem(); MenuItem IronII = new MenuItem(); MenuItem IronIII = new MenuItem(); MenuItem Random = new MenuItem(); Aluminium.Click += MetalMenuClickHandler; Aluminium.Header = "Aluminium"; metalMenu.Items.Add(Aluminium); Chromium.Click += MetalMenuClickHandler; Chromium.Header = "Chromium"; metalMenu.Items.Add(Chromium); Cobalt.Click += MetalMenuClickHandler; Cobalt.Header = "Cobalt"; metalMenu.Items.Add(Cobalt); Copper.Click += MetalMenuClickHandler; Copper.Header = "Copper"; metalMenu.Items.Add(Copper); IronII.Click += MetalMenuClickHandler; IronII.Header = "Iron(II)"; metalMenu.Items.Add(IronII); IronIII.Click += MetalMenuClickHandler; IronIII.Header = "Iron(III)"; metalMenu.Items.Add(IronIII); Random.Click += MetalMenuClickHandler; Random.Header = "Random"; metalMenu.Items.Add(Random); transMetal.ContextMenu = metalMenu; } private void MetalMenuClickHandler(object sender, RoutedEventArgs e) { MenuItem clickedItem = sender as MenuItem; if ((string)clickedItem.Header == "Aluminium") { SwitchMetals("Aluminium"); chosenMetal = "Aluminium"; } else if ((string)clickedItem.Header == "Chromium") { SwitchMetals("Chromium"); chosenMetal = "Chromium"; } else if ((string)clickedItem.Header == "Cobalt") { SwitchMetals("Cobalt"); chosenMetal = "Cobalt"; } else if ((string)clickedItem.Header == "Copper") { SwitchMetals("Copper"); chosenMetal = "Copper"; } else if ((string)clickedItem.Header == "Iron(II)") { SwitchMetals("Iron(II)"); chosenMetal = "Iron(II)"; } else if ((string)clickedItem.Header == "Iron(III)") { SwitchMetals("Iron(III)"); chosenMetal = "Iron(III)"; } else if ((string)clickedItem.Header == "Random") { string newMetal = _GameControl.CycleThroughMetals(); SwitchMetals(newMetal); chosenMetal = newMetal; } } private void Window_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Escape && popupMenuOpened == false ) { MenuPopUp.Visibility = Visibility.Visible; MenuPopUp.FadeIn(); popupMenuOpened = true; } else if (e.Key == Key.Escape && popupMenuOpened == true) { MenuPopUp.Visibility = Visibility.Hidden; MenuPopUp._InstructionsUC.Visibility = Visibility.Hidden; popupMenuOpened = false; } else if (e.Key == Key.B) { string chemFact = _GameControl.PickChemFact(); string msg = string.Format("You have discovered the Truls Bjørvik easter egg! This person contributed massively to the Kickstarter campaign and I am very grateful.\n \n{0}", chemFact); MessageBox.Show(msg); } } } }
// <copyright file="SecondTaskTest.cs" company="MyCompany.com"> // Contains the solutions to tasks of the 'Basic Coding in C#' module. // </copyright> // <author>Daryn Akhmetov</author> namespace Basic_coding_in_CSharp_Tests { using Basic_coding_in_CSharp; using NUnit.Framework; /// <summary> /// This is a test class for SecondTask and is intended /// to contain all SecondTask Unit Tests. /// </summary> [TestFixture] public class SecondTaskTest { /// <summary> /// A test for FindMaxRecursive. /// </summary> /// <param name="sourceArray">The array in which we find the maximum element.</param> /// <returns>Maximum element in unsortedArray.</returns> [TestCase(new int[] { 1, 1, 1, 1, 1, 1, 1 }, ExpectedResult = 1)] [TestCase(new int[] { 0, -1, 11, 21, 1, 2, 8, 65, 34, 21, 765, -12, 566, 7878, -199, 0, 34, 65, 87, 12, 34 }, ExpectedResult = 7878)] public int FindMaxRecursiveTest(int[] sourceArray) { return SecondTask.FindMaxRecursive(sourceArray, sourceArray.Length - 1); } } }
using Common.Data; using Common.Exceptions; using System; using System.Data; using System.Data.SqlClient; namespace Entity { public partial class SystemDefaults { public string[] GetConformingDirectories(string connectionString) { string[] result = new string[2]; //select value from system_defaults where id = 'CONFORMINGPROJECTS' string sql = "P_Conforming_TrackB_EmailTraffic_GetValue"; using (Database database = new Database(connectionString)) { try { result[0] = database.ExecuteSelectString(sql, CommandType.StoredProcedure); //select value from system_defaults where id = 'CONFORMINGPROJECTS_STAGING' sql = "P_Conforming_TrackB_EmailTraffic_GetValue2"; result[1] = database.ExecuteSelectString(sql, CommandType.StoredProcedure); } catch (Exception e) { throw new EntityException(sql, e); } } return result; } public string GetPathById(string connectionString, string id) { string result = String.Empty; string sql = String.Format("select value from system_defaults where id = '{0}'", id); using (Database database = new Database(connectionString)) { try { result = database.ExecuteSelectString(sql); } catch (Exception e) { throw new EntityException(sql, e); } } return result; } } }
using System; using System.Linq; using CG.Web.MegaApiClient.Tests.Context; using Xunit; using Xunit.Abstractions; namespace CG.Web.MegaApiClient.Tests { [Collection("AuthenticatedLoginTests")] public class NodeOperationsAuthenticated : NodeOperations { public NodeOperationsAuthenticated(AuthenticatedTestContext context, ITestOutputHelper testOutputHelper) : base(context, testOutputHelper) { } [Theory] [InlineData(AuthenticatedTestContext.FolderId, "bsxVBKLL", NodeType.Directory, "SharedFolder", 0, "2017-07-11T10:48:00.0000000+07:00", null)] [InlineData(AuthenticatedTestContext.SubFolderId, AuthenticatedTestContext.FolderId, NodeType.Directory, "SharedSubFolder", 0, "2017-07-11T10:48:01.0000000+07:00", null)] [InlineData(AuthenticatedTestContext.FileId, AuthenticatedTestContext.FolderId, NodeType.File, "SharedFile.jpg", 523265, "2017-07-11T10:48:10.0000000+07:00", "2015-07-14T14:04:51.0000000+08:00")] [InlineData("b0I0QDhA", "u4IgDb5K", NodeType.Directory, "SharedRemoteFolder", 0, "2015-05-21T02:35:22.0000000+08:00", null)] [InlineData("e5wjkSJB", "b0I0QDhA", NodeType.File, "SharedRemoteFile.jpg", 523265, "2015-05-21T02:36:06.0000000+08:00", "2015-05-19T09:39:50.0000000+08:00")] [InlineData("KhZSWI7C", "b0I0QDhA", NodeType.Directory, "SharedRemoteSubFolder", 0, "2015-07-14T17:05:03.0000000+08:00", null)] [InlineData("HtonzYYY", "KhZSWI7C", NodeType.File, "SharedRemoteSubFile.jpg", 523265, "2015-07-14T18:06:27.0000000+08:00", "2015-05-27T02:42:21.0000000+08:00")] [InlineData("z1YCibCT", "KhZSWI7C", NodeType.Directory, "SharedRemoteSubSubFolder", 0, "2015-07-14T18:01:56.0000000+08:00", null)] public void Validate_PermanentNodes_Succeeds( string id, string expectedParent, NodeType expectedNodeType, string expectedName, long expectedSize, string expectedCreationDate, string expectedModificationDate ) { var node = this.GetNode(id); Assert.Equal(expectedNodeType, node.Type); Assert.Equal(expectedParent,node.ParentId); Assert.Equal(expectedName, node.Name); Assert.Equal(expectedSize, node.Size); Assert.Equal(DateTime.Parse(expectedCreationDate), node.CreationDate); Assert.Equal(expectedModificationDate == null ? (DateTime?)null : DateTime.Parse(expectedModificationDate), node.ModificationDate); } [Theory] [InlineData(NodeType.Root, 523265)] [InlineData(NodeType.Inbox, 0)] [InlineData(NodeType.Trash, 0)] public void GetFoldersize_FromNodeType_Succeeds(NodeType nodeType, long expectedSize) { var node = this.GetNode(nodeType); Assert.Equal(expectedSize, node.GetFolderSize(this.context.Client)); Assert.Equal(expectedSize, node.GetFolderSizeAsync(this.context.Client).Result); Assert.Equal(expectedSize, node.GetFolderSize(this.context.Client.GetNodes())); Assert.Equal(expectedSize, node.GetFolderSizeAsync(this.context.Client.GetNodes()).Result); } [Fact] public void GetFoldersize_FromFile_Throws() { var node = this.context.Client.GetNodes().First(x => x.Type == NodeType.File); Assert.Throws<InvalidOperationException>(() => node.GetFolderSize(this.context.Client)); var aggregateException = Assert.Throws<AggregateException>(() => node.GetFolderSizeAsync(this.context.Client).Result); Assert.IsType<InvalidOperationException>(aggregateException.GetBaseException()); Assert.Throws<InvalidOperationException>(() => node.GetFolderSize(this.context.Client.GetNodes())); aggregateException = Assert.Throws<AggregateException>(() => node.GetFolderSizeAsync(this.context.Client.GetNodes()).Result); Assert.IsType<InvalidOperationException>(aggregateException.GetBaseException()); } [Theory] [InlineData(AuthenticatedTestContext.FolderId, 523265)] [InlineData(AuthenticatedTestContext.SubFolderId, 0)] public void GetFoldersize_FromDirectory_Succeeds(string nodeId, long expectedSize) { var node = this.GetNode(nodeId); Assert.Equal(expectedSize, node.GetFolderSize(this.context.Client)); Assert.Equal(expectedSize, node.GetFolderSizeAsync(this.context.Client).Result); Assert.Equal(expectedSize, node.GetFolderSize(this.context.Client.GetNodes())); Assert.Equal(expectedSize, node.GetFolderSizeAsync(this.context.Client.GetNodes()).Result); } } }
using ClassLibrary; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsForms { public partial class sellform : Form { public sellform() { InitializeComponent(); } #region 初始化放映列表 /// <summary> /// 初始化放映列表 /// </summary> public void InitFilmNamelist() { DateTime dt = DateTime.Now; //获取当前日期与数据库中的比较 列出今天的放映列表 string str = dt.ToString("yyyy-MM-dd"); string sqlstr = "select * from Table_film where datatime='"+str+"'"; SqlConnection sqlConnection1 = new SqlConnection(Mytool.connstr); sqlConnection1.Open(); SqlDataAdapter sqldataAdapter = new SqlDataAdapter(sqlstr, sqlConnection1); DataSet dataset1 = new DataSet(); sqldataAdapter.Fill(dataset1,"film"); DataView dv = new DataView(dataset1.Tables["film"]); if (dv.Count != 0)//判断是否有数据,有数据则进行添加操作 { //添加父节点 TreeNode pnode = new TreeNode(); pnode.Text = dv[0]["name"].ToString(); pnode.Tag = dv[0]["id"].ToString(); pnode.Name = dv[0]["name"].ToString(); this.treeView_movielist.Nodes.Add(pnode); for (int i = 0; i < dv.Count - 1; i++) { Boolean isDifferent = false; foreach (TreeNode node in this.treeView_movielist.Nodes) { if (node.Name.ToString().Equals(dv[i + 1]["name"].ToString())) { isDifferent = false; break; } isDifferent = true; } if (isDifferent) { pnode = new TreeNode(); pnode.Text = dv[i + 1]["name"].ToString(); pnode.Tag = dv[i + 1]["id"].ToString(); pnode.Name = dv[i + 1]["name"].ToString(); this.treeView_movielist.Nodes.Add(pnode); } } //添加子节点 TreeNode tn; for (int i = 0; i < dv.Count; i++) { foreach (TreeNode node in this.treeView_movielist.Nodes) { if (dv[i]["name"].ToString().Equals(node.Name.ToString())) { tn = new TreeNode(); tn.Text = dv[i]["filmbegintime"].ToString() + "-" + dv[i]["filmendtime"].ToString(); tn.Tag = dv[i]["id"].ToString(); tn.Name = dv[i]["name"].ToString(); node.Nodes.Add(tn); } } } } } #endregion private void sellform_Load(object sender, EventArgs e) { InitFilmNamelist(); } private void treeView_movielist_AfterSelect(object sender, TreeViewEventArgs e)//选择树节点后 判断是树节点还是子节点 { string nodeName = treeView_movielist.SelectedNode.Text; if (e.Node.Parent == null)//父节点trv1_movieList.SelectedNode.Text.Trim() { string sqlstr = "select * from Table_film where name='" + nodeName + "'"; SqlConnection sqlConnection1 = new SqlConnection(Mytool.connstr); sqlConnection1.Open(); SqlDataAdapter sqldataAdapter = new SqlDataAdapter(sqlstr, sqlConnection1); DataSet dataset1 = new DataSet(); sqldataAdapter.Fill(dataset1, "film"); DataView dv = new DataView(dataset1.Tables["film"]); name.Text = dv[0]["name"].ToString(); dir.Text = dv[0]["director"].ToString(); role.Text = dv[0]["mainrole"].ToString(); typ.Text = dv[0]["type"].ToString(); pric.Text = dv[0]["price"].ToString(); disc.Text = pric.Text; //label_data.Text = dv[0]["datatime"].ToString(); if (dv[0]["picture"].ToString().Length>0) pictureBox1.Image = Image.FromFile(dv[0]["picture"].ToString()); } else { string filmName = this.treeView_movielist.SelectedNode.Parent.Text; string sqlstr1 = "select * from Table_film where name='" + filmName + "'"; SqlConnection sqlConnection1 = new SqlConnection(Mytool.connstr); sqlConnection1.Open(); SqlDataAdapter sqldataAdapter1 = new SqlDataAdapter(sqlstr1, sqlConnection1); DataSet dataset2 = new DataSet(); sqldataAdapter1.Fill(dataset2, "film"); DataView dv = new DataView(dataset2.Tables["film"]); name.Text = dv[0]["name"].ToString(); dir.Text = dv[0]["director"].ToString(); role.Text = dv[0]["mainrole"].ToString(); typ.Text = dv[0]["type"].ToString(); pric.Text = dv[0]["price"].ToString(); disc.Text = pric.Text; //label_data.Text = dv[0]["datatime"].ToString(); if (dv[0]["picture"].ToString().Length > 0) pictureBox1.Image = Image.FromFile(dv[0]["picture"].ToString()); sqlConnection1.Close(); int index = nodeName.IndexOf('-'); string begintime = nodeName.Substring(0, index); string sqlstr = "select seatnumber from Table_film,Table_sold where Table_film.id=Table_sold.filmid and name='"+ filmName +"' and filmbegintime='"+begintime+"'"; sqlConnection1.Open(); SqlDataAdapter sqldataAdapter = new SqlDataAdapter(sqlstr, sqlConnection1); DataSet dataset1 = new DataSet(); sqldataAdapter.Fill(dataset1, "seat"); Button[] btn = new Button[25]; Control[] cc = null; for (int i = 0; i < 25; i++) //将控件类转化为数组 { cc = this.Controls.Find("button" + (i+1).ToString(), true); foreach (Control ctr in cc) { btn[i] = (Button)ctr; btn[i].Enabled = true; btn[i].BackColor = Color.Yellow; btn[i].Visible = true; } } for (int i = 0; i < dataset1.Tables["seat"].Rows.Count; i++) { int seat =Convert.ToInt32(dataset1.Tables["seat"].Rows[i]["seatnumber"].ToString()); btn[seat-1].Enabled = false; btn[seat - 1].BackColor = Color.Red; } } } private void button25_Click(object sender, EventArgs e) { Button btn = sender as Button; btn.BackColor = Color.Red ; buy.Visible = true; } private void buy_Click(object sender, EventArgs e) { if (this.treeView_movielist.SelectedNode.Parent == null) { MessageBox.Show("请选择时间段","错误"); } else { string filmName = this.treeView_movielist.SelectedNode.Parent.Text; string nodeName = this.treeView_movielist.SelectedNode.Text; Button[] btn = new Button[25]; Control[] cc = null; for (int i = 0; i < 25; i++) //将控件类转化为数组 { cc = this.Controls.Find("button" + (i + 1).ToString(), true); foreach (Control ctr in cc) { btn[i] = (Button)ctr; } } for (int i = 0; i < 25; i++) //将座位信息写入表中 { if (btn[i].Enabled == true && btn[i].BackColor == Color.Red) { int index = nodeName.IndexOf('-'); string begintime = nodeName.Substring(0, index); int j = Mytool.getfilmid(filmName, begintime); int a = i + 1; string sqlstr = "insert into Table_sold(filmid,seatnumber,usernum)values('" + j + "','" + a + "','" + Mytool.currentuseraccount + "')"; SqlConnection sqlConnection1 = new SqlConnection(Mytool.connstr); sqlConnection1.Open(); SqlCommand sqlCommand1 = new SqlCommand(sqlstr, sqlConnection1); int succnum = sqlCommand1.ExecuteNonQuery(); sqlConnection1.Close(); if (succnum > 0) MessageBox.Show("购买成功"); btn[i].Enabled = false; } } } } private void search_Click(object sender, EventArgs e) { treeView_movielist.Nodes.Clear(); DateTime dt = dateTimePicker1.Value; //获取当前日期与数据库中的比较 列出今天的放映列表 string str = dt.ToString("yyyy-MM-dd"); string sqlstr = "select * from Table_film where datatime='" + str + "'"; SqlConnection sqlConnection1 = new SqlConnection(Mytool.connstr); sqlConnection1.Open(); SqlDataAdapter sqldataAdapter = new SqlDataAdapter(sqlstr, sqlConnection1); DataSet dataset1 = new DataSet(); sqldataAdapter.Fill(dataset1, "film"); DataView dv = new DataView(dataset1.Tables["film"]); if (dv.Count != 0)//判断是否有数据,有数据则进行添加操作 { //添加父节点 TreeNode pnode = new TreeNode(); pnode.Text = dv[0]["name"].ToString(); pnode.Tag = dv[0]["id"].ToString(); pnode.Name = dv[0]["name"].ToString(); this.treeView_movielist.Nodes.Add(pnode); for (int i = 0; i < dv.Count - 1; i++) { Boolean isDifferent = false; foreach (TreeNode node in this.treeView_movielist.Nodes) { if (node.Name.ToString().Equals(dv[i + 1]["name"].ToString())) { isDifferent = false; break; } isDifferent = true; } if (isDifferent) { pnode = new TreeNode(); pnode.Text = dv[i + 1]["name"].ToString(); pnode.Tag = dv[i + 1]["id"].ToString(); pnode.Name = dv[i + 1]["name"].ToString(); this.treeView_movielist.Nodes.Add(pnode); } } //添加子节点 TreeNode tn; for (int i = 0; i < dv.Count; i++) { foreach (TreeNode node in this.treeView_movielist.Nodes) { if (dv[i]["name"].ToString().Equals(node.Name.ToString())) { tn = new TreeNode(); tn.Text = dv[i]["filmbegintime"].ToString() + "-" + dv[i]["filmendtime"].ToString(); tn.Tag = dv[i]["id"].ToString(); tn.Name = dv[i]["name"].ToString(); node.Nodes.Add(tn); } } } } } } }
using System; using System.Collections.Generic; namespace ModUpdateMenu.Extensions { static class ListExtensions { /// <summary>Create lists of tuples more easily.</summary> public static void Add<T1, T2>(this IList<Tuple<T1, T2>> list, T1 item1, T2 item2) { list.Add(new Tuple<T1, T2>(item1, item2)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using UnityEngine.EventSystems; public class UIBase : MonoBehaviour { public bool startHidden; public Graphic[] graphicElements; public RectTransform[] transformableElements; // aniamtions protected const float AnimationDuration = 0.15f; protected const float AnimationDistance = 10f; static AnimationCurve animationCurve = AnimationCurve.EaseInOut (0, 0, 1, 1); public enum UICommonAnimation { None, LowerAlpha, RaiseAlpha, BounceUp, BounceDown, Enlarge, Unenlarge, EnlargeSideways, UnenlargeSideways } public UICommonAnimation hoverAnimation; public UICommonAnimation unhoverAnimation; public UICommonAnimation pressAnimation; public UICommonAnimation unpressAnimation; public enum UIShowHideAnimation { None, RiseInFallOut, ScaleInOutSideways } public UIShowHideAnimation showHideAnimation = UIShowHideAnimation.RiseInFallOut; Queue<IEnumerator> animationQueue = new Queue<IEnumerator> (); bool animationQueueWorkerAlive = false; bool[] graphicsElementsRaycastTargetable; Vector3[] transformableElementsOriginalLocations; // events [System.Serializable] public class UIEventVoid:UnityEvent { } public UIEventVoid OnHover; public UIEventVoid OnUnhover; public UIEventVoid OnPress; public UIEventVoid OnUnpress; public bool hidden { get; protected set; } protected virtual void Awake () { graphicsElementsRaycastTargetable = new bool[graphicElements.Length]; for (int i = 0; i < graphicElements.Length; i++) { graphicsElementsRaycastTargetable [i] = graphicElements [i].raycastTarget; } transformableElementsOriginalLocations = new Vector3[transformableElements.Length]; for (int i = 0; i < transformableElements.Length; i++) { transformableElementsOriginalLocations [i] = transformableElements [i].transform.localPosition; } } protected virtual void Start () { if (startHidden) { foreach (UIBase element in GetComponentsInChildren<UIBase>()) { element.HideImmediately (); } } } //---------------------// public virtual void OnPointerHover (GameObject source) { if (!hidden) { OnHover.Invoke (); QueueAnimation (_OnPointerHover ()); } } IEnumerator _OnPointerHover () { yield return PlayCommonAnimation (hoverAnimation); } public virtual void OnPointerUnhover (GameObject source) { if (!hidden) { OnUnhover.Invoke (); QueueAnimation (_OnPointerUnhover ()); } } IEnumerator _OnPointerUnhover () { yield return PlayCommonAnimation (unhoverAnimation); } public virtual void OnPointerPress (GameObject source) { if (!hidden) { OnPress.Invoke (); QueueAnimation (_OnPointerPress ()); } } IEnumerator _OnPointerPress () { yield return PlayCommonAnimation (pressAnimation); } public virtual void OnPointerUnpress (GameObject source) { if (!hidden) { OnUnpress.Invoke (); QueueAnimation (_OnPointerUnpress ()); } } IEnumerator _OnPointerUnpress () { yield return PlayCommonAnimation (unpressAnimation); } IEnumerator PlayCommonAnimation (UICommonAnimation commonAnimation) { switch (commonAnimation) { case UICommonAnimation.BounceUp: yield return A_BounceUp (); break; case UICommonAnimation.BounceDown: yield return A_BounceDown (); break; case UICommonAnimation.RaiseAlpha: yield return A_RaiseAlpha (); break; case UICommonAnimation.LowerAlpha: yield return A_LowerAlhpa (); break; case UICommonAnimation.Enlarge: yield return A_Enlarge (); break; case UICommonAnimation.Unenlarge: yield return A_Unenlarge (); break; case UICommonAnimation.EnlargeSideways: yield return A_EnlargeSideways (); break; case UICommonAnimation.UnenlargeSideways: yield return A_UnenlargeSideways (); break; } } //----------------------// public void Show () { StartCoroutine (_Show ()); for(int i=0; i<transform.childCount;i++){ UIBase childElement = transform.GetChild (i).GetComponent<UIBase> (); if (childElement && !childElement.startHidden) { childElement.Show (); } } } IEnumerator _Show () { SetElementsScale (1); switch (showHideAnimation) { case UIShowHideAnimation.RiseInFallOut: yield return A_RiseIn (); break; case UIShowHideAnimation.ScaleInOutSideways: yield return A_ScaleInSideways (); break; } ShowImmediately (); } void ShowImmediately () { SetElementsRaycastTargetable (true); SetElementsAlpha (1); SetElementsScale (1); SetElementsOffset (Vector2.zero); hidden = false; } public void Hide () { foreach (UIBase element in GetComponentsInChildren<UIBase>()) { element.StartCoroutine (element._Hide ()); } } void HideImmediately () { hidden = true; SetElementsAlpha (0); SetElementsScale (1); SetElementsOffset (Vector2.zero); SetElementsRaycastTargetable (false); animationQueue.Clear (); } IEnumerator _Hide () { hidden = true; SetElementsRaycastTargetable (false); animationQueue.Clear (); switch (showHideAnimation) { case UIShowHideAnimation.RiseInFallOut: yield return A_FallOut (); break; case UIShowHideAnimation.ScaleInOutSideways: yield return A_ScaleOutSideways (); break; } HideImmediately (); } IEnumerator A_RiseIn () { float lifetime = 0; while (lifetime < AnimationDuration) { float frac = animationCurve.Evaluate (lifetime / AnimationDuration); SetElementsOffset (Vector3.down * AnimationDistance * (1 - frac)); SetElementsAlpha (frac); yield return null; lifetime += Time.deltaTime; } SetElementsOffset (Vector3.zero); SetElementsAlpha (1); } IEnumerator A_FallOut () { float lifetime = 0; while (lifetime < AnimationDuration) { float frac = animationCurve.Evaluate (lifetime / AnimationDuration); SetElementsOffset (Vector3.down * AnimationDistance * frac); SetElementsAlpha (1 - frac); yield return null; lifetime += Time.deltaTime; } SetElementsOffset (Vector3.down * AnimationDistance); SetElementsAlpha (0); } IEnumerator A_ScaleInSideways () { SetElementsAlpha (1); float lifetime = 0; while (lifetime < AnimationDuration) { float frac = animationCurve.Evaluate (lifetime / AnimationDuration); SetElementsScale (new Vector2 (frac, 1)); yield return null; lifetime += Time.deltaTime; } SetElementsScale (1); } IEnumerator A_ScaleOutSideways () { float lifetime = 0; while (lifetime < AnimationDuration) { float frac = animationCurve.Evaluate (lifetime / AnimationDuration); SetElementsScale (new Vector2 (1 - frac, 1)); yield return null; lifetime += Time.deltaTime; } SetElementsScale (0); } //---------------------// IEnumerator A_BounceDown () { float lifetime = 0; while (lifetime < AnimationDuration) { float frac = animationCurve.Evaluate (lifetime / AnimationDuration); SetElementsOffset (Vector3.up * AnimationDistance * (1 - frac)); yield return null; lifetime += Time.deltaTime * 2; } SetElementsOffset (Vector3.zero); } IEnumerator A_BounceUp () { float lifetime = 0; while (lifetime < AnimationDuration) { float frac = animationCurve.Evaluate (lifetime / AnimationDuration); SetElementsOffset (Vector3.up * AnimationDistance * frac); yield return null; lifetime += Time.deltaTime * 2; } SetElementsOffset (Vector3.up * AnimationDistance); } IEnumerator A_LowerAlhpa () { float lifetime = 0; while (lifetime < AnimationDuration) { float frac = animationCurve.Evaluate (lifetime / AnimationDuration); SetElementsAlpha (1 - 0.2f * frac); yield return null; lifetime += Time.deltaTime; } SetElementsAlpha (0.8f); } IEnumerator A_RaiseAlpha () { float lifetime = 0; while (lifetime < AnimationDuration) { float frac = animationCurve.Evaluate (lifetime / AnimationDuration); SetElementsAlpha (0.8f + 0.2f * frac); yield return null; lifetime += Time.deltaTime; } SetElementsAlpha (1); } IEnumerator A_Enlarge () { float lifetime = 0; while (lifetime < AnimationDuration) { float frac = animationCurve.Evaluate (lifetime / AnimationDuration); SetElementsScale (1 + 0.1f * frac); yield return null; lifetime += Time.deltaTime; } SetElementsScale (1.1f); } IEnumerator A_Unenlarge () { float lifetime = 0; while (lifetime < AnimationDuration) { float frac = animationCurve.Evaluate (lifetime / AnimationDuration); SetElementsScale (1 + 0.1f * (1 - frac)); yield return null; lifetime += Time.deltaTime; } SetElementsScale (1); } IEnumerator A_EnlargeSideways () { float lifetime = 0; while (lifetime < AnimationDuration) { float frac = animationCurve.Evaluate (lifetime / AnimationDuration); SetElementsScale (new Vector2 (1 + 0.1f * frac, 1)); yield return null; lifetime += Time.deltaTime; } SetElementsScale (new Vector2 (1.1f, 1)); } IEnumerator A_UnenlargeSideways () { float lifetime = 0; while (lifetime < AnimationDuration) { float frac = animationCurve.Evaluate (lifetime / AnimationDuration); SetElementsScale (new Vector2 (1 + 0.1f * (1 - frac), 1)); yield return null; lifetime += Time.deltaTime; } SetElementsScale (1); } //--------// protected void QueueAnimation (IEnumerator animation) { animationQueue.Enqueue (animation); if (!animationQueueWorkerAlive) { StartCoroutine (AnimationQueueWorker ()); } } IEnumerator AnimationQueueWorker () { animationQueueWorkerAlive = true; while (animationQueue.Count > 0 && !hidden) { IEnumerator animation = animationQueue.Dequeue (); while (animation.MoveNext () && !hidden) { yield return animation.Current; } } animationQueueWorkerAlive = false; } protected void SetElementsAlpha (float alpha) { for (int i = 0; i < graphicElements.Length; i++) { graphicElements [i].CrossFadeAlpha (alpha, 0, true); } } protected void SetElementsRaycastTargetable (bool targetable) { for (int i = 0; i < graphicElements.Length; i++) { if (graphicsElementsRaycastTargetable [i]) { graphicElements [i].raycastTarget = targetable; } } } protected void SetElementsScale (float scale) { SetElementsScale (Vector2.one * scale); } protected void SetElementsScale (Vector2 scale) { for (int i = 0; i < transformableElements.Length; i++) { transformableElements [i].transform.localScale = new Vector3 (scale.x, scale.y, 1); } } protected void SetElementsOffset (Vector3 offset) { for (int i = 0; i < transformableElements.Length; i++) { transformableElements [i].transform.localPosition = transformableElementsOriginalLocations [i] + offset; } } }
using System.Collections.Generic; using System.Linq; using System.Threading; using MTD.SDVTwitch.Models; using StardewModdingAPI; using StardewValley; namespace MTD.SDVTwitch { public class SDVTwitch : Mod { internal static Config Config; private List<User> _followersAtStart = new List<User>(); private TwitchClient _client; public override void Entry(IModHelper helper) { Config = (Config)helper.ReadJsonFile<Config>("config.json"); _client = new TwitchClient(Config); _followersAtStart = _client.GetUsersByName(Config.TwitchName); new Thread(TwitchLoop).Start(); } private void TwitchLoop() { while (true) { if (Context.IsWorldReady) { foreach (var user1 in _client.GetUsersByName(Config.TwitchName)) { var user = user1; if (_followersAtStart.FirstOrDefault(u => u.DisplayName == user.DisplayName) != null) { continue; } _followersAtStart.Add(user); Game1.addHUDMessage(new HUDMessage($"New Follower: {user.DisplayName}!", 2)); } } Thread.Sleep(15000); } } } }
using System; using System.Collections.Generic; using System.Text; namespace Softhouse.Data { public enum PhoneType { Mobile, Landline } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects.Entities.Documents; namespace KartObjects { public interface IDocumentEditView { /// <summary> /// Редактируемая сущность /// </summary> Document Document { get; set; } /// <summary> /// Режим редактирования /// </summary> bool AddMode { get; set; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using MailKit; using MailKit.Net.Imap; using MailKit.Search; using MailKit.Security; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using MimeKit; namespace TF47_Mailbot.Services { public class MailService { private readonly ILogger<MailService> _logger; private readonly IConfiguration _configuration; public MailService( ILogger<MailService> logger, IConfiguration configuration) { _logger = logger; _configuration = configuration; } public async Task<List<MessageResponse>> GetUnreadMails() { var client = new ImapClient(); try { await client.ConnectAsync(_configuration["Mail:Server"], int.Parse(_configuration["Mail:Port"]), SecureSocketOptions.Auto); await client.AuthenticateAsync(_configuration["Mail:Username"], _configuration["Mail:Password"]); } catch (Exception ex) { _logger.LogError("Failed to connect to IMAP Server: ", ex.Message); return null; } var inbox = client.Inbox; await inbox.OpenAsync(FolderAccess.ReadWrite); var notSeen = await inbox.SearchAsync(SearchQuery.NotSeen); var response = new List<MessageResponse>(); foreach (var uniqueId in notSeen) { await inbox.SetFlagsAsync(uniqueId, MessageFlags.Seen, true); var message = await inbox.GetMessageAsync(uniqueId); if (string.IsNullOrEmpty(message.TextBody) && !string.IsNullOrEmpty(message.HtmlBody)) { response.Add(new MessageResponse(message.From.ToString(), message.Date.DateTime, message.Subject, message.HtmlBody, true)); continue; } if (message.TextBody.Length > 1024) response.Add(new MessageResponse(message.From.ToString(), message.Date.DateTime, message.Subject, message.TextBody, true)); else response.Add(new MessageResponse(message.From.ToString(), message.Date.DateTime, message.Subject, message.TextBody, false)); } return response; } public record MessageResponse(string FromMail, DateTime InboxTime, string Subject, string Message, bool IsHtml); } }
using System; using System.Collections.Generic; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace GIFU.Controllers { public class AccountController : Controller { private Models.AccountServices accountServices = new Models.AccountServices(); private Models.NotificationServices notificationServices = new Models.NotificationServices(); private Models.OrderServices orderServices = new Models.OrderServices(); private Models.GoodsServices goodsServices = new Models.GoodsServices(); private bool IsSessionLogin() { if (Session["UserId"] != null) return true; return false; } [Authorize] public ActionResult ManageInfo() { if (!IsSessionLogin()) { return RedirectToAction("SignOut"); } Models.Account account = accountServices.GetAccountDetailById(Convert.ToInt32(Session["userId"])); ViewBag.tag = "ManageInfo"; return View("_ManagePartial", account); } public ActionResult ManageInfoPartial(Models.Account account) { return PartialView("ManageInfo", account); } /// <summary> /// 更新帳戶 /// </summary> /// <param name="account"></param> /// <returns></returns> [HttpPost] [Authorize] public ActionResult ManageInfo(Models.Account account) { if (!IsSessionLogin()) { return RedirectToAction("SignOut"); } int result = -1; string message = "個人資料修改失敗"; if (account.UserId != null) { result = accountServices.UpdateAccount(account); if (result > 0) { message = "個人資料修改完成"; Session["username"] = account.Name; } } TempData["result"] = result; TempData["message"] = message; return RedirectToAction("ManageInfo"); } /// <summary> /// 管理索取清單 /// </summary> /// <returns></returns> [Authorize] public ActionResult ManageOrders() { if (!IsSessionLogin()) { return RedirectToAction("SignOut"); } Models.Account account = accountServices.GetAccountDetailById(Convert.ToInt32(Session["userId"])); ViewBag.tag = "ManageOrders"; return View("_ManagePartial", account); } [Authorize] public ActionResult ManageOrdersPartial() { ViewBag.Orders = orderServices.GetOrdersDetailByUserId(Convert.ToInt32(Session["userId"])); return PartialView("ManageOrders"); } /// <summary> /// 管理物品 /// </summary> /// <returns></returns> [Authorize] public ActionResult ManageGoods() { if (!IsSessionLogin()) { return RedirectToAction("SignOut"); } Models.Account account = accountServices.GetAccountDetailById(Convert.ToInt32(Session["userId"])); ViewBag.tag = "ManageGoods"; return View("_ManagePartial", account); } [Authorize] public ActionResult ManageGoodsPartial() { ViewBag.Goods = goodsServices.GetGoodsDetailByUserId(Convert.ToInt32(Session["userId"])); return PartialView("ManageGoods"); } /// <summary> /// 註冊頁面 /// </summary> /// <returns></returns> public ActionResult Register() { if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Store"); } return View(new Models.Account()); } /// <summary> /// 註冊頁面處理 /// </summary> /// <param name="account"></param> /// <returns></returns> [HttpPost] public ActionResult Register(Models.Account account) { TempData["result"] = -1; TempData["message"] = "輸入錯誤,請重新輸入一次。"; if (ModelState.IsValid) { int userId = accountServices.AddAccount(account); if (userId > 0) { TempData["result"] = 1; TempData["message"] = "註冊成功,請到信箱收信驗證。"; //產生token,寄信 Models.MailServices mailServices = new Models.MailServices(); string token = mailServices.CreateAToken(userId); Tools.EmailSender emailSender = new Tools.EmailSender(); emailSender.SendAnEmail(new Tools.MailModel() { From = Variable.GetMailAccount, To = account.Email, Subject = Variable.GetMailSubject, Body = Variable.GetAuthenciateionTemplate.Replace("<!--USERNAME-->", account.Name) .Replace("<!--URL-->", Variable.GetCurrentHost + "/Account/Authentication/" + userId + "?token=" + HttpUtility.UrlEncode(token)) }); //ViewBag.UserId = userId; return RedirectToAction("Authentication", new { id = userId }); } else if (userId == -1) { TempData["result"] = -1; TempData["message"] = "帳號已存在。"; } } return View(account); } public ActionResult Authentication(int? id, string token) { int userId = 0; if (id != null) { userId = Convert.ToInt32(id); ViewBag.UserId = userId; } else return RedirectToAction("Login"); Models.Account account = accountServices.GetAccountDetailById(userId); if (account.IsValid == "T" || account.UserId == null) { return RedirectToAction("Login"); } if (token != null) { Models.MailServices mailServices = new Models.MailServices(); if (mailServices.VerifyToken(userId, token)) { ViewBag.Result = accountServices.SetUserIsValid(userId, "T"); } else { ViewBag.Result = -1; } } return View(); } public void ReSendAuthenticationMail(int? userId) { int id = (userId != null) ? Convert.ToInt32(userId) : 0; Models.Account account = accountServices.GetAccountDetailById(id); Models.MailServices mailServices = new Models.MailServices(); string token = mailServices.CreateAToken(id); Tools.EmailSender emailSender = new Tools.EmailSender(); emailSender.SendAnEmail(new Tools.MailModel() { From = Variable.GetMailAccount, To = account.Email, Subject = Variable.GetMailSubject, Body = Variable.GetAuthenciateionTemplate.Replace("<!--USERNAME-->", account.Name) .Replace("<!--URL-->", Variable.GetCurrentHost + "/Account/Authentication/" + userId + "?token=" + HttpUtility.UrlEncode(token)) }); } /// <summary> /// 登入 /// </summary> /// <returns></returns> public ActionResult Login() { if (User.Identity.IsAuthenticated) return RedirectToAction("SignOut"); return View(new Models.LoginVM()); } /// <summary> /// 登入 /// </summary> /// <param name="loginVM"></param> /// <returns></returns> [AllowAnonymous] [HttpPost] public ActionResult Login(Models.LoginVM loginVM) { //檢驗帳號、密碼為必輸 if (!ModelState.IsValid) { TempData["Error"] = "請輸入帳號密碼!"; return View(loginVM); } //loginVM.ShaPasswd = FormsAuthentication.HashPasswordForStoringInConfigFile(loginVM.Passwd, "SHA1"); //檢查帳號是否存在 Models.Account account = accountServices.Authentication(loginVM); if (account.Email == null) { TempData["Error"] = "您輸入的帳號不存在或者密碼錯誤!"; return View(loginVM); } if (account.IsValid == "F") { return RedirectToAction("Authentication", new { id = account.UserId }); } Session.RemoveAll(); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, account.Email, //User.Identity.Name DateTime.Now, DateTime.Now.AddMinutes(30), false, account.UserId.ToString(), FormsAuthentication.FormsCookiePath); string encTicket = FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); Session["username"] = account.Name; Session["userId"] = account.UserId; //以下只會執行一個 //FormsAuthentication.RedirectFromLoginPage(loginVM.Email, false); //string returnRul = FormsAuthentication.GetRedirectUrl(loginVM.Email, false).TrimEnd('/'); return Redirect(FormsAuthentication.GetRedirectUrl(loginVM.Email, false)); } /// <summary> /// 登出 /// </summary> [Authorize] public void SignOut() { //HttpCookie cookie = FormsAuthentication.GetAuthCookie(User.Identity.Name, false); //HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName]; //FormsAuthenticationTicket decrypt = FormsAuthentication.Decrypt(cookie.Value); if (User.Identity.IsAuthenticated) { //清除Session中的資料 Session.Abandon(); Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now.AddYears(-1); FormsAuthentication.SignOut(); } //FormsAuthentication.RedirectToLoginPage(); Response.Redirect(FormsAuthentication.LoginUrl); } /// <summary> /// 取得帳戶詳細資料 /// </summary> /// <param name="accountId"></param> /// <returns></returns> [HttpPost] public JsonResult GetAccountDetailById(string accountId) { int id = Convert.ToInt32(accountId); var account = accountServices.GetAccountDetailById(id); return this.Json(account); } //[HttpPost] public ActionResult GetMessages() { List<Models.Notification> notifications = notificationServices.GetMessages(); return PartialView("_MessagesList", notifications); } [HttpPost] public ActionResult GetMessagesById(int? userId) { List<Models.Notification> notifications = notificationServices.GetMessagesById(userId); return PartialView("_MessagesList", notifications); } /// <summary> /// 標示訊息為已讀 /// </summary> /// <param name="userId"></param> /// <returns></returns> [HttpPost] public JsonResult SetAllMessagesWereRead(int? userId) { int result = notificationServices.SetIsRead(userId); string message; if (result > 0) message = "訊息已讀"; else message = "更新錯誤"; return this.Json(Variable.GetResult(result, message)); } } }
using System; using System.Linq; using cyrka.api.common.identities; using NUnit.Framework; namespace cyrka.api.test.common { [TestFixture] public class CompositeSerialIdShould { [Test] public void BeCreatedFromPartsToString() { var rand = TestContext.CurrentContext.Random; var serial = rand.NextULong(); var prefixesCount = rand.NextUShort(0, 10); var prefixes = Enumerable.Range(0, prefixesCount) .Select(i => { object res; if (rand.NextBool()) res = rand.GetString(rand.Next(1, 20)); else if (rand.NextBool()) res = rand.NextULong(); else res = new DateTime(rand.NextLong(DateTime.MinValue.Ticks, DateTime.MinValue.Ticks)); return res; }) .ToArray(); var subjToTest = new CompositeSerialId(serial, prefixes); var actualId = subjToTest.ToString(); for (int i = 0; i < prefixes.Length - 1; i++) Assert.IsTrue(actualId.Contains(prefixes[i].ToString())); Assert.AreEqual(serial, subjToTest.Serial); } [Test] public void BeGoodOnEmptyPrefixes() { var rand = TestContext.CurrentContext.Random; var serial = rand.NextULong(); var subjToTest = new CompositeSerialId(serial); var actualId = subjToTest.ToString(); Assert.AreEqual(serial, ulong.Parse(actualId)); } [Test] public void BeCastToStringImplicitly() { var subjUnderTest = new CompositeSerialId(298, "SUBST", "18", "02"); var expectedId = "SUBST-18-02-298"; var actualId = (string)subjUnderTest; Assert.AreEqual(expectedId, actualId); } [Test] public void BeCastFromStringExplicitly() { var expectedId = "SUBST-1802-298"; var subjUnderTest = (CompositeSerialId)expectedId; var actualId = (string)subjUnderTest; Assert.AreEqual(expectedId, actualId); } [Test] public void ThrowIfCastFromStringWithoutNumberAtEnd() { var stringId = "i-throw-exception"; Assert.Throws<InvalidCastException>(() => { var x = (CompositeSerialId)stringId; }); } [Test] public void GetSerialNumberOfId() { var rand = TestContext.CurrentContext.Random; var expectedSerial = rand.NextULong(); var prefixesCount = rand.NextUShort(0, 10); var prefixes = Enumerable.Range(0, prefixesCount) .Select(i => { object res; if (rand.NextBool()) res = rand.GetString(rand.Next(1, 20)); else if (rand.NextBool()) res = rand.NextULong(); else res = new DateTime(rand.NextLong(DateTime.MinValue.Ticks, DateTime.MinValue.Ticks)); return res; }) .ToArray(); var subjToTest = new CompositeSerialId(expectedSerial, prefixes); var actualSerial = subjToTest.Serial; Assert.AreEqual(expectedSerial, actualSerial); } } }
using System; using KeepTeamAutotests; using KeepTeamAutotests.Model; using NUnit.Framework; using System.Collections.Generic; using Newtonsoft.Json; using System.IO; using KeepTeamAutotests.AppLogic; namespace KeepTeamTests { [TestFixture()] public class EditRelativesTests : InternalPageTests { [SetUp] public void Login() { app.userHelper .loginAs(app.userHelper.getUserByRole("pFamilyRW")); } [Test, TestCaseSource(typeof(FileHelper),"relatives")] public void Edit_Relatives(Employee employee) { app.employeeHelper.clearRelatives(); //Редактирование app.employeeHelper.editRelatives(employee); //создание тестового юзера для сравнения Employee testEmployee = app.employeeHelper.getRelatives(); //Проверка соответствия двух пользователей. Assert.IsTrue(app.employeeHelper.CompareRelatives(employee, testEmployee)); employee.WriteToConsole(); testEmployee.WriteToConsole(); } [Test, TestCaseSource(typeof(FileHelper), "relativesreq")] public void Edit_Employee_Relatives_Validation(Employee invalidEmployee) { //Очистка основной информации app.employeeHelper.clearRelatives(); //Редактирование app.employeeHelper.editRelatives(invalidEmployee); //проверка текста валидации Assert.AreEqual(app.userHelper.EMPTYINPUTMSG, app.userHelper.getValidationMessage()); } } }
using System.Collections.Generic; using NHibernate; using NHibernate.Criterion; using NHibernate.SqlCommand; using NHibernate.Transform; using NHibernate.Type; using Profiling2.Domain.Contracts.Queries.Search; using Profiling2.Domain.Prf.Careers; using SharpArch.NHibernate; namespace Profiling2.Infrastructure.Queries { public class RoleSearchQuery : NHibernateQuery, IRoleSearchQuery { public IList<Role> GetResults(string term) { //var qo = Session.QueryOver<Role>(); //if (!string.IsNullOrEmpty(term)) // return qo.Where(Restrictions.On<Role>(x => x.RoleName).IsLike("%" + term + "%")) // .OrderBy(x => x.RoleName).Asc // .Take(50) // .List<Role>(); //else // return new List<Role>(); // Alphabetically ordered with insensitive LIKE //if (!string.IsNullOrEmpty(term)) // return Session.CreateCriteria<Role>() // .Add(Expression.Sql("RoleName LIKE ? COLLATE Latin1_general_CI_AI", "%" + term + "%", NHibernateUtil.String)) // .AddOrder(Order.Asc("RoleName")) // .SetMaxResults(50) // .List<Role>(); //else // return new List<Role>(); // Sorted by Career popularity with insensitive LIKE if (!string.IsNullOrEmpty(term)) return Session.CreateCriteria<Career>() .CreateAlias("Role", "r", JoinType.RightOuterJoin) .Add(Expression.Sql(@" RoleName LIKE ? COLLATE Latin1_general_CI_AI OR RoleNameFr LIKE ? COLLATE Latin1_general_CI_AI", new string[] { "%" + term + "%", "%" + term + "%" }, new IType[] { NHibernateUtil.String, NHibernateUtil.String })) .SetProjection(Projections.ProjectionList() .Add(Projections.Property("r.Id"), "Id") .Add(Projections.Property("r.RoleName"), "RoleName") .Add(Projections.Property("r.RoleNameFr"), "RoleNameFr") .Add(Projections.Property("r.Archive"), "Archive") .Add(Projections.Property("r.Notes"), "Notes") .Add(Projections.Count("r.Id")) .Add(Projections.GroupProperty("r.Id")) .Add(Projections.GroupProperty("r.RoleName")) .Add(Projections.GroupProperty("r.RoleNameFr")) .Add(Projections.GroupProperty("r.Archive")) .Add(Projections.GroupProperty("r.Notes")) ) .AddOrder(Order.Desc(Projections.Count("r.Id"))) .SetMaxResults(50) .SetResultTransformer(Transformers.AliasToBean<Role>()) .List<Role>(); else return new List<Role>(); } } }
using System; using System.Collections.Generic; namespace OrgMan.DomainObjects.Common { public class MembershipDomainModel { public Guid UID { get; set; } public List<Guid> MandatorUIDs { get; set; } public string Title { get; set; } public string Code { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Step_140a { class Program { static void Main() { List<Employee> employees = new List<Employee>(); employees.Add(new Employee() { FirstName = "Joe", LastName = "Smith", EmpID = 1 }); employees.Add(new Employee() { FirstName = "Abbey", LastName = "Cleman", EmpID = 2 }); employees.Add(new Employee() { FirstName = "Lorri", LastName = "Henry", EmpID = 3 }); employees.Add(new Employee() { FirstName = "Bryan", LastName = "Finlay", EmpID = 4 }); employees.Add(new Employee() { FirstName = "Tyler", LastName = "Vehrenkamp", EmpID = 5 }); employees.Add(new Employee() { FirstName = "Lane", LastName = "Vehrenkamp", EmpID = 6 }); employees.Add(new Employee() { FirstName = "Joe", LastName = "Jones", EmpID = 7 }); employees.Add(new Employee() { FirstName = "Lance", LastName = "Poole", EmpID = 8 }); employees.Add(new Employee() { FirstName = "Erin", LastName = "Deschermeier", EmpID = 9 }); employees.Add(new Employee() { FirstName = "Steven", LastName = "Deschermeier", EmpID = 10 }); employees.Add(new Employee() { FirstName = "John", LastName = "Dietz", EmpID = 11 }); Console.WriteLine(); foreach (Employee aemployee in employees) { string FirstName = null; if (FirstName == "Joe") { //employees.Add(aemployee); Console.WriteLine(employees); } } //Console.WriteLine(employee3); //Console.WriteLine(employees); Console.ReadLine(); } } }
using Nailhang.IndexBase.PublicApi; using System; using System.Collections.Generic; using System.Text; namespace Nailhang.Display.NetPublicSearch.Base { public interface INetSearch { IEnumerable<NamespaceInfo> GetNamespaces(); IEnumerable<ISearchItem> Search(string query); void RebuildIndex(); } }
using System; using System.ComponentModel; using System.Windows; using System.Windows.Controls; namespace KeypadEntryApplication { /// <summary> /// Interaction logic for KeypadEntry.xaml /// </summary> public partial class KeypadEntry : Window, INotifyPropertyChanged { private string _result; private readonly int minNumber = 5; private readonly int maxNumber = 10000; public string Result { get { return _result; } private set { _result = value; OnPropertyChanged("Result"); } } public KeypadEntry(Window owner, string entry) { InitializeComponent(); Result = entry; Owner = owner; DataContext = this; } private void Button_Click(object sender, RoutedEventArgs args) { Button button = sender as Button; switch (button.CommandParameter.ToString()) { case "Return": if(ValidateEntry(Result)) DialogResult = true; break; case "Backspace": if (Result?.Length > 0) Result = Result.Remove(Result.Length - 1); break; case "Clear": Result = string.Empty; break; case "Decimal": if (Result != null && !Result.Contains(".")) Result += button.Content.ToString(); break; default: Result += button.Content.ToString(); break; } } private bool ValidateEntry(string entry) { if (!decimal.TryParse(entry, out decimal number)) { MessageBox.Show("Not a valid number, please try again."); return false; } if (number < minNumber || number > maxNumber) { MessageBox.Show("The number is not in a valid range, please enter number between " + minNumber + " and " + maxNumber + "."); return false; } return true; } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string info) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; namespace Fuzzing.Fuzzers { public abstract class TypeFuzzer<T> : IFuzzer { protected RandomNumberGenerator RandomNumberGenerator { get; private set; } protected TypeFuzzer() { RandomNumberGenerator = RandomNumberGenerator.Create(); } public bool CanFuzzType(Type type) { var result = (typeof (T) == type); return result; } public Type FuzzedType { get { return typeof (T); } } public object Fuzz(Type type) { return Fuzz(); } public IEnumerable<object> Fuzz(Type type, int count) { return Fuzz(count) .Cast<object>(); } public abstract T Fuzz(); public IEnumerable<T> Fuzz(int count) { return Enumerable.Range(0, count) .Select(x => Fuzz()); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; public class UILabel : UIBase { [System.Serializable] public class UIEventString:UnityEvent<string> { } public UIEventString OnHoverString; public UIEventString OnUnhoverString; public UIEventString OnPressString; public UIEventString OnUnpressString; Text label; public virtual string stringElement { get { return label.text; } set { label.text = value; } } protected override void Awake () { base.Awake (); foreach (Graphic graphic in graphicElements) { if (graphic is Text) { if (label) { Debug.LogWarning ("Don't put multiple Texts on a single UILabel"); } label = (Text)graphic; break; } } } public void SetString (string s) { stringElement = s; } public void SetString (float value) { stringElement = value.ToString (); } public override void OnPointerHover (GameObject source) { base.OnPointerHover (source); if (!hidden) { OnHoverString.Invoke (stringElement); } } public override void OnPointerUnhover (GameObject source) { base.OnPointerUnhover (source); if (!hidden) { OnUnhoverString.Invoke (stringElement); } } public override void OnPointerPress (GameObject source) { base.OnPointerPress (source); if (!hidden) { OnPressString.Invoke (stringElement); } } public override void OnPointerUnpress (GameObject source) { base.OnPointerUnpress (source); if (!hidden) { OnUnpressString.Invoke (stringElement); } } }
using System; using System.Collections.Generic; using Fbtc.Domain.Entities; using Fbtc.Domain.Interfaces.Services; using Fbtc.Application.Interfaces; using prmToolkit.Validation; using Fbtc.Application.Helper; namespace Fbtc.Application.Services { public class EnderecoApplication : IEnderecoApplication { private readonly IEnderecoService _enderecoService; public EnderecoApplication(IEnderecoService enderecoService) { _enderecoService = enderecoService; } public string DeleteById(int id) { throw new NotImplementedException(); } public string DeleteByPessoaId(int id) { throw new NotImplementedException(); } public IEnumerable<EstadoEnderecoCepDao> GetAllNomesEstados() { return _enderecoService.GetAllNomesEstados(); } public IEnumerable<Endereco> GetByPessoaId(int id) { return _enderecoService.GetByPessoaId(id); } public Endereco GetEnderecoById(int id) { return _enderecoService.GetEnderecoById(id); } public IEnumerable<CidadeEnderecoCepDao> GetNomesCidadesByEstado(string nomeEstado) { return _enderecoService.GetNomesCidadesByEstado(nomeEstado); } public string Save(Endereco e) { Endereco _e = new Endereco() { EnderecoId = e.EnderecoId, PessoaId = e.PessoaId, Logradouro = Functions.AjustaTamanhoString(e.Logradouro, 100), Numero = Functions.AjustaTamanhoString(e.Numero, 10), Complemento = Functions.AjustaTamanhoString(e.Complemento, 100), Bairro = Functions.AjustaTamanhoString(e.Bairro, 100), Cidade = Functions.AjustaTamanhoString(e.Cidade, 100), Estado = Functions.AjustaTamanhoString(e.Estado, 2), Cep = Functions.AjustaTamanhoString(e.Cep, 10), TipoEndereco = e.TipoEndereco }; try { if (_e.EnderecoId == 0) { return _enderecoService.Insert(_e); } else { return _enderecoService.Update(e.EnderecoId, _e); } } catch (Exception ex) { throw ex; } } public Endereco SetEndereco() { Endereco e = new Endereco() { EnderecoId = 0, PessoaId = 0, Logradouro = "", Numero = "", Complemento = "", Bairro = "", Cidade = "", Estado = "", Cep = "", TipoEndereco = "" }; return e; } } }
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PaperbanknotesServer.Database { public class CarDatabaseContext : DbContext { public CarDatabaseContext(DbContextOptions<CarDatabaseContext> options) : base(options) { } public DbSet<model.Car> CarDbItems { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Xlns.BusBook.Core.Model; namespace Xlns.BusBook.UI.Web.Models { public class DettaglioUtenteView { public String NomeAdv { get { if (string.IsNullOrEmpty(search)) return utente.Cognome; else { var start = utente.Cognome.ToLower().IndexOf(search.ToLower()); if (start >= 0) { var originalString = utente.Cognome.Substring(start, search.Length); var retString = utente.Cognome.Replace(originalString, "<span class='matchString'>" + originalString + "</span>"); return retString; } else return utente.Cognome; } } } private String search; public Utente utente { get; set; } public DettaglioUtenteView(Utente u, String s) { utente = u; search = s; } } }
using UnityEngine; using UnityEngine.UI; using Photon.Pun; using Photon.Realtime; using System.Collections.Generic; public class PhotonLobbyManager : MonoBehaviourPunCallbacks { const string playerNamePrefKey = "PlayerName"; const string gameVersion = "1"; public GameObject DebugText; public GameObject JoinRoomButton; public GameObject StartGameButton; public GameObject PlayerNameInput; private Text txtDebug; private Button btnJoinRoom; private Button btnStartGame; private InputField txtPlayerName; private bool playerReady; private string output; private string playerName; void Awake() { PhotonNetwork.AutomaticallySyncScene = true; } void Start() { playerReady = false; try { btnJoinRoom = JoinRoomButton.GetComponent<Button>(); btnStartGame = StartGameButton.GetComponent<Button>(); txtPlayerName = PlayerNameInput.GetComponent<InputField>(); btnJoinRoom.interactable = false; btnStartGame.interactable = false; txtPlayerName.interactable = false; output = "Connecting to server"; ConnectToPUNServer(); } catch (System.Exception ex) { Debug.LogError("Game cannot be iniitalized, please double-check gameobject mapping."); } if (DebugText != null) { txtDebug = DebugText.GetComponent<Text>(); } } void ConnectToPUNServer() { if (!PhotonNetwork.IsConnected) { PhotonNetwork.ConnectUsingSettings(); PhotonNetwork.GameVersion = gameVersion; } } void Update() { if (DebugText != null) { if (PhotonNetwork.InRoom) { txtDebug.text = "Current players: " + PhotonNetwork.CurrentRoom.PlayerCount.ToString() + "\n"; foreach (Player p in PhotonNetwork.PlayerList) { txtDebug.text += p.NickName + " | "; } } else { txtDebug.text = output; } } if (PhotonNetwork.InRoom) { if (PhotonNetwork.CurrentRoom.PlayerCount >= 2) { btnStartGame.interactable = true; } else { btnStartGame.interactable = false; } } else { btnStartGame.interactable = false; } } public void JoinRoom() { btnJoinRoom.image.color = Color.yellow; if (!PhotonNetwork.InRoom) { txtPlayerName.interactable = false; playerName = txtPlayerName.text; PlayerPrefs.SetString(playerNamePrefKey, playerName); PhotonNetwork.NickName = playerName; PhotonNetwork.JoinRandomRoom(); } else { LeaveRoom(); } } public void LeaveRoom() { txtPlayerName.interactable = true; btnJoinRoom.image.color = Color.white; PhotonNetwork.LeaveRoom(); } public void PlayerReady() { // toggle ready status playerReady = !playerReady; PhotonNetwork.LocalPlayer.CustomProperties["ready"] = true; if (playerReady) { btnStartGame.image.color = Color.green; if (isAllPlayersReady()) { PhotonNetwork.CurrentRoom.IsOpen = false; if (PhotonNetwork.IsMasterClient) { //PhotonNetwork.LoadLevel("PhotonTest_Game"); PhotonNetwork.LoadLevel("Gameplay"); } } } else { btnStartGame.image.color = Color.white; PhotonNetwork.LocalPlayer.CustomProperties["ready"] = false; } } private bool isAllPlayersReady() { foreach (Player p in PhotonNetwork.PlayerList) { object readyVal; p.CustomProperties.TryGetValue("ready", out readyVal); if (readyVal is bool && (bool) readyVal == false) { return false; } } return true; } /// <summary> /// PUN Callbacks, should not be directly invoked /// </summary> public override void OnConnectedToMaster() { output = "Connected to PUN server"; btnJoinRoom.interactable = true; txtPlayerName.interactable = true; if (PlayerPrefs.HasKey(playerNamePrefKey)) { playerName = PlayerPrefs.GetString(playerNamePrefKey); txtPlayerName.text = playerName; } else { playerName = ""; } } public override void OnDisconnected(DisconnectCause cause) { Debug.Log("Player disconnected: " + cause.ToString()); btnJoinRoom.interactable = false; btnStartGame.interactable = false; txtPlayerName.interactable = false; output = "Disconnected from server"; } public override void OnJoinRandomFailed(short returnCode, string message) { Debug.Log("No open room found, creating new room."); PhotonNetwork.CreateRoom(null, new RoomOptions()); } public override void OnJoinedRoom() { Debug.Log("Player joined the room"); } public override void OnPlayerLeftRoom(Player otherPlayer) { Debug.Log("Player left the room"); base.OnPlayerLeftRoom(otherPlayer); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace ProyectoPP.Models { public class DocumentacionModel { [Display(Name = "Id")] public int Id { get; set; } [Display(Name = "Nombre")] public string Nombre { get; set; } [Display(Name = "ContentType")] public string ContentType { get; set; } [Display(Name = "Data")] public byte[] Data { get; set; } [Display(Name = "HUId")] public String HUid { get; set; } } }
using System; using System.IO; using System.Collections.Generic; using System.Text; namespace Core { public class Speech { public byte[] Wave { get; set; } public string SpeechId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProyectoLP2 { public class Transportista : AgenteExterno { private Alcance alcance; private List<string> destinos; public Transportista() { } public Transportista(Alcance alcance, List<string> destinos, string nombre, List<Direccion> lista, string ruc, string email, int telefono,int celular,int id, string apellidoP, string apellidoM) : base (nombre, lista, ruc, email, telefono,celular,id, apellidoP, apellidoM) { this.Alcance = alcance; this.Destinos = destinos; } public Alcance Alcance { get => alcance; set => alcance = value; } public List<string> Destinos { get => destinos; set => destinos = value; } } }
// <copyright file="IndexDataOfName.cs" company="WaterTrans"> // © 2020 WaterTrans // </copyright> using System.Collections.Generic; namespace WaterTrans.GlyphLoader.Internal.OpenType.CFF { /// <summary> /// The Compact FontFormat Specification Name INDEX. /// </summary> internal class IndexDataOfName : IndexData { /// <summary> /// Initializes a new instance of the <see cref="IndexDataOfName"/> class. /// </summary> /// <param name="reader">The <see cref="TypefaceReader"/>.</param> internal IndexDataOfName(TypefaceReader reader) : base(reader) { for (int i = 0; i < Objects.Count; i++) { Names.Add(System.Text.Encoding.UTF8.GetString(Objects[i], 0, Objects[i].Length)); } } /// <summary> /// Gets a list of name. /// </summary> public List<string> Names { get; } = new List<string>(); } }
#if Top using Phenix.Core.Web; #endif using System; using System.Collections.Generic; using System.Data.Common; using System.IO; using System.Reflection; using Phenix.Core; using Phenix.Core.Data; using Phenix.Core.IO; using Phenix.Core.Log; namespace Phenix.Business { /// <summary> /// 指令基类 /// 在DataPortal_Execute()、DoExecute()函数(任选一处)中编写运行在服务端的指令处理代码 /// 消费者调用Execute()函数提交指令 /// </summary> [Serializable] public abstract class CommandBase<T> : Phenix.Business.Core.CommandBase<T> where T : CommandBase<T> { #region 属性 private ShallEventArgs _executeResult = new ShallEventArgs(); /// <summary> /// 执行结果 /// </summary> [Newtonsoft.Json.JsonIgnore] [System.ComponentModel.Browsable(false)] [System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)] public ShallEventArgs ExecuteResult { get { return _executeResult; } } #endregion #region 方法 /// <summary> /// 置换为与source相同内容的对象 /// </summary> protected virtual void ReplaceFrom(T source) { if (object.ReferenceEquals(source, null) || object.ReferenceEquals(source, this)) return; Phenix.Core.Reflection.Utilities.FillFieldValues(source, this, true); _executeResult = source._executeResult; } /// <summary> /// 执行指令 /// </summary> /// <returns>this</returns> public T Execute() { ReplaceFrom(Execute((T)this)); return (T)this; } /// <summary> /// 执行指令 /// </summary> /// <param name="inParam">输入参数对象</param> /// <returns>输出参数对象</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T Execute(T inParam) { if (inParam == null) throw new ArgumentNullException("inParam"); if (!inParam.OnExecuting()) return null; try { inParam._executeResult.Applied = true; T result = Csla.DataPortal.Update(inParam); inParam.OnExecuted(null as Exception); return result; } catch (Exception ex) { inParam._executeResult.Succeed = false; EventLog.Save(inParam.GetType(), MethodBase.GetCurrentMethod(), ex); string s = inParam.OnExecuted(ex); if (String.IsNullOrEmpty(s)) throw; else throw new ExecuteException(s, ex); } } /// <summary> /// 上传文件 /// </summary> /// <param name="fileNames">待上传的文件路径</param> /// <returns>this</returns> public T UploadFiles(params string[] fileNames) { ReplaceFrom(UploadFiles((T)this, fileNames)); return (T)this; } /// <summary> /// 上传文件 /// </summary> /// <param name="inParam">输入参数对象</param> /// <param name="fileNames">待上传的文件路径</param> /// <returns>输出参数对象</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T UploadFiles(T inParam, params string[] fileNames) { if (inParam == null) throw new ArgumentNullException("inParam"); if (!inParam.OnExecuting()) return null; try { inParam._executeResult.Applied = true; T result; #if Top if (AppHub.DataProxy != null) result = AppHub.DataProxy.UploadFiles(inParam, fileNames); else #endif result = (T)DataHub.UploadFiles(inParam, fileNames); inParam.OnExecuted(null as Exception); return result; } catch (Exception ex) { inParam._executeResult.Succeed = false; EventLog.Save(inParam.GetType(), MethodBase.GetCurrentMethod(), ex); string s = inParam.OnExecuted(ex); if (String.IsNullOrEmpty(s)) throw; else throw new ExecuteException(s, ex); } } /// <summary> /// 上传大文件 /// </summary> /// <param name="fileName">待上传的文件路径</param> /// <param name="doProgress">执行进度干预</param> /// <returns>this</returns> public T UploadBigFile(string fileName, Func<object, FileChunkInfo, bool> doProgress) { ReplaceFrom(UploadBigFile((T)this, fileName, doProgress)); return (T)this; } /// <summary> /// 上传大文件 /// </summary> /// <param name="inParam">输入参数对象</param> /// <param name="fileName">待上传的文件路径</param> /// <param name="doProgress">执行进度干预</param> /// <returns>输出参数对象</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T UploadBigFile(T inParam, string fileName, Func<object, FileChunkInfo, bool> doProgress) { if (inParam == null) throw new ArgumentNullException("inParam"); try { inParam._executeResult.Applied = true; T result; #if Top if (AppHub.DataProxy != null) result = AppHub.DataProxy.UploadBigFile(inParam, fileName, doProgress); else #endif result = (T)DataHub.UploadBigFile(inParam, fileName, doProgress); inParam.OnExecuted(null as Exception); return result; } catch (Exception ex) { inParam._executeResult.Succeed = false; EventLog.Save(inParam.GetType(), MethodBase.GetCurrentMethod(), ex); string s = inParam.OnExecuted(ex); if (String.IsNullOrEmpty(s)) throw; else throw new ExecuteException(s, ex); } } /// <summary> /// 下载文件 /// </summary> /// <param name="fileName">待保存的文件路径</param> public void DownloadFile(string fileName) { DownloadFile((T)this, fileName); } /// <summary> /// 下载文件 /// </summary> /// <param name="inParam">输入参数对象</param> /// <param name="fileName">待保存的文件路径</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static void DownloadFile(T inParam, string fileName) { if (inParam == null) throw new ArgumentNullException("inParam"); if (!inParam.OnExecuting()) return; try { inParam._executeResult.Applied = true; #if Top if (AppHub.DataProxy != null) AppHub.DataProxy.DownloadFile(inParam, fileName); else #endif DataHub.DownloadFileBytes(inParam, fileName); inParam.OnExecuted(null as Exception); } catch (Exception ex) { inParam._executeResult.Succeed = false; EventLog.Save(inParam.GetType(), MethodBase.GetCurrentMethod(), ex); string s = inParam.OnExecuted(ex); if (String.IsNullOrEmpty(s)) throw; else throw new ExecuteException(s, ex); } } /// <summary> /// 下载大文件 /// </summary> /// <param name="fileName">待保存的文件路径</param> /// <param name="doProgress">执行进度干预</param> public void DownloadBigFile(string fileName, Func<object, FileChunkInfo, bool> doProgress) { DownloadBigFile((T)this, fileName, doProgress); } /// <summary> /// 下载大文件 /// </summary> /// <param name="inParam">输入参数对象</param> /// <param name="fileName">待保存的文件路径</param> /// <param name="doProgress">执行进度干预</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static void DownloadBigFile(T inParam, string fileName, Func<object, FileChunkInfo, bool> doProgress) { if (inParam == null) throw new ArgumentNullException("inParam"); if (!inParam.OnExecuting()) return; try { inParam._executeResult.Applied = true; #if Top if (AppHub.DataProxy != null) AppHub.DataProxy.DownloadBigFile(inParam, fileName, doProgress); else #endif DataHub.DownloadBigFile(inParam, fileName, doProgress); inParam.OnExecuted(null as Exception); } catch (Exception ex) { inParam._executeResult.Succeed = false; EventLog.Save(inParam.GetType(), MethodBase.GetCurrentMethod(), ex); string s = inParam.OnExecuted(ex); if (String.IsNullOrEmpty(s)) throw; else throw new ExecuteException(s, ex); } } /// <summary> /// 执行指令 /// </summary> /// <param name="connection">数据库连接</param> /// <returns>this</returns> public T Execute(DbConnection connection) { return Execute(connection, (T)this); } /// <summary> /// 执行指令 /// </summary> /// <param name="connection">数据库连接</param> /// <param name="inParam">输入参数对象</param> /// <returns>输出参数对象</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T Execute(DbConnection connection, T inParam) { if (inParam == null) throw new ArgumentNullException("inParam"); if (!inParam.OnExecuting()) return null; try { inParam._executeResult.Applied = true; inParam.DoExecute(connection); inParam.OnExecuted(null as Exception); return inParam; } catch (Exception ex) { inParam._executeResult.Succeed = false; EventLog.Save(inParam.GetType(), MethodBase.GetCurrentMethod(), ex); string s = inParam.OnExecuted(ex); if (String.IsNullOrEmpty(s)) throw; else throw new ExecuteException(s, ex); } } /// <summary> /// 执行指令 /// </summary> /// <param name="transaction">数据库事务</param> /// <returns>this</returns> public T Execute(DbTransaction transaction) { return Execute(transaction, (T)this); } /// <summary> /// 执行指令 /// </summary> /// <param name="transaction">数据库事务</param> /// <param name="inParam">输入参数对象</param> /// <returns>输出参数对象</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")] public static T Execute(DbTransaction transaction, T inParam) { if (inParam == null) throw new ArgumentNullException("inParam"); if (!inParam.OnExecuting()) return null; try { inParam._executeResult.Applied = true; inParam.DoExecute(transaction); inParam.OnExecuted(null as Exception); return inParam; } catch (Exception ex) { inParam._executeResult.Succeed = false; EventLog.Save(inParam.GetType(), MethodBase.GetCurrentMethod(), ex); string s = inParam.OnExecuted(ex); if (String.IsNullOrEmpty(s)) throw; else throw new ExecuteException(s, ex); } } /// <summary> /// 执行指令之前 /// </summary> /// <returns>是否继续, 缺省为 true</returns> protected virtual bool OnExecuting() { return true; } /// <summary> /// 执行指令之后 /// </summary> /// <param name="ex">错误信息</param> /// <returns>发生错误时的友好提示信息, 缺省为 null</returns> protected virtual string OnExecuted(Exception ex) { return null; } #region Data Access /// <summary> /// 处理执行指令(运行在持久层的程序域里) /// </summary> protected override void DoExecute() { try { if (typeof(T).GetMethod("DoExecute", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(DbConnection) }, null) != null) DbConnectionHelper.Execute(DataSourceKey, (Action<DbConnection>)DoExecute); if (typeof(T).GetMethod("DoExecute", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(DbTransaction) }, null) != null) DbConnectionHelper.Execute(DataSourceKey, (Action<DbTransaction>)DoExecute); } finally { base.DoExecute(); } } /// <summary> /// 处理执行指令(运行在持久层的程序域里) /// 请使用业务对象处理逻辑 /// 如直接操作数据也请用Phenix.Core.Data.DbCommandHelper与数据库交互以保证可移植性 /// 如果重载了DoExecute()且未调用base.DoExecute(),则本函数将不会执行到 /// 如果重载了DataPortal_Execute()且未调用base.DataPortal_Execute(),则本函数将不会执行到 /// </summary> /// <param name="connection">数据库连接</param> protected virtual void DoExecute(DbConnection connection) { } /// <summary> /// 处理执行指令(运行在持久层的程序域里) /// 请使用业务对象处理逻辑 /// 如直接操作数据也请用Phenix.Core.Data.DbCommandHelper与数据库交互以保证可移植性 /// 如果重载了DoExecute()且未调用base.DoExecute(),则本函数将不会执行到 /// 如果重载了DataPortal_Execute()且未调用base.DataPortal_Execute(),则本函数将不会执行到 /// 如果拦截了异常,请处理后继续抛出,以便交给基类执行Rollback() /// </summary> /// <param name="transaction">数据库事务</param> protected virtual void DoExecute(DbTransaction transaction) { } /// <summary> /// 处理上传文件(运行在持久层的程序域里) /// </summary> /// <param name="fileStreams">待处理的文件流</param> protected override void DoUploadFiles(IDictionary<string, Stream> fileStreams) { try { if (typeof(T).GetMethod("DoUploadFiles", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(DbConnection), typeof(IDictionary<string, Stream>) }, null) != null) DbConnectionHelper.Execute(DataSourceKey, (Action<DbConnection, IDictionary<string, Stream>>)DoUploadFiles, fileStreams); if (typeof(T).GetMethod("DoUploadFiles", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(DbTransaction), typeof(IDictionary<string, Stream>) }, null) != null) DbConnectionHelper.Execute(DataSourceKey, (Action<DbTransaction, IDictionary<string, Stream>>)DoUploadFiles, fileStreams); } finally { base.DoUploadFiles(fileStreams); } } /// <summary> /// 处理上传文件(运行在持久层的程序域里) /// 请使用业务对象处理逻辑 /// 如直接操作数据也请用Phenix.Core.Data.DbCommandHelper与数据库交互以保证可移植性 /// 如果重载了DoUploadFiles()且未调用base.DoUploadFiles(),则本函数将不会执行到 /// </summary> /// <param name="connection">数据库连接</param> /// <param name="fileStreams">待处理的文件流</param> protected virtual void DoUploadFiles(DbConnection connection, IDictionary<string, Stream> fileStreams) { } /// <summary> /// 处理上传文件(运行在持久层的程序域里) /// 请使用业务对象处理逻辑 /// 如直接操作数据也请用Phenix.Core.Data.DbCommandHelper与数据库交互以保证可移植性 /// 如果重载了DoUploadFiles()且未调用base.DoUploadFiles(),则本函数将不会执行到 /// 如果拦截了异常,请处理后继续抛出,以便交给基类执行Rollback() /// </summary> /// <param name="transaction">数据库事务</param> /// <param name="fileStreams">待处理的文件流</param> protected virtual void DoUploadFiles(DbTransaction transaction, IDictionary<string, Stream> fileStreams) { } /// <summary> /// 处理上传大文件(运行在持久层的程序域里) /// </summary> /// <param name="fileChunkInfo">待处理的文件块信息</param> protected override void DoUploadBigFile(FileChunkInfo fileChunkInfo) { try { if (typeof(T).GetMethod("DoUploadBigFile", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(DbConnection), typeof(FileChunkInfo) }, null) != null) DbConnectionHelper.Execute(DataSourceKey, (Action<DbConnection, FileChunkInfo>)DoUploadBigFile, fileChunkInfo); if (typeof(T).GetMethod("DoUploadBigFile", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(DbTransaction), typeof(FileChunkInfo) }, null) != null) DbConnectionHelper.Execute(DataSourceKey, (Action<DbTransaction, FileChunkInfo>)DoUploadBigFile, fileChunkInfo); } finally { base.DoUploadBigFile(fileChunkInfo); } } /// <summary> /// 处理上传大文件(运行在持久层的程序域里) /// 请使用业务对象处理逻辑 /// 如直接操作数据也请用Phenix.Core.Data.DbCommandHelper与数据库交互以保证可移植性 /// 如果重载了DoUploadBigFile()且未调用base.DoUploadBigFile(),则本函数将不会执行到 /// </summary> /// <param name="connection">数据库连接</param> /// <param name="fileChunkInfo">待处理的文件块信息</param> protected virtual void DoUploadBigFile(DbConnection connection, FileChunkInfo fileChunkInfo) { } /// <summary> /// 处理上传大文件(运行在持久层的程序域里) /// 请使用业务对象处理逻辑 /// 如直接操作数据也请用Phenix.Core.Data.DbCommandHelper与数据库交互以保证可移植性 /// 如果重载了DoUploadBigFile()且未调用base.DoUploadBigFile(),则本函数将不会执行到 /// 如果拦截了异常,请处理后继续抛出,以便交给基类执行Rollback() /// </summary> /// <param name="transaction">数据库事务</param> /// <param name="fileChunkInfo">待处理的文件块信息</param> protected virtual void DoUploadBigFile(DbTransaction transaction, FileChunkInfo fileChunkInfo) { } /// <summary> /// 获取下载文件(运行在持久层的程序域里) /// </summary> /// <returns>文件流</returns> protected override Stream DoDownloadFile() { try { if (typeof(T).GetMethod("DoDownloadFile", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(DbConnection) }, null) != null) return DbConnectionHelper.ExecuteGet<Stream>(DataSourceKey, (Func<DbConnection, Stream>)DoDownloadFile); if (typeof(T).GetMethod("DoDownloadFile", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(DbTransaction) }, null) != null) return DbConnectionHelper.ExecuteGet<Stream>(DataSourceKey, (Func<DbTransaction, Stream>)DoDownloadFile); return null; } finally { base.DoDownloadFile(); } } /// <summary> /// 获取下载文件(运行在持久层的程序域里) /// 请使用业务对象处理逻辑 /// 如直接操作数据也请用Phenix.Core.Data.DbCommandHelper与数据库交互以保证可移植性 /// 如果重载了DoDownloadFile()且未调用base.DoDownloadFile(),则本函数将不会执行到 /// </summary> /// <param name="connection">数据库连接</param> /// <returns>文件流</returns> protected virtual Stream DoDownloadFile(DbConnection connection) { return null; } /// <summary> /// 获取下载文件(运行在持久层的程序域里) /// 请使用业务对象处理逻辑 /// 如直接操作数据也请用Phenix.Core.Data.DbCommandHelper与数据库交互以保证可移植性 /// 如果重载了DoDownloadFile()且未调用base.DoDownloadFile(),则本函数将不会执行到 /// 如果拦截了异常,请处理后继续抛出,以便交给基类执行Rollback() /// </summary> /// <param name="transaction">数据库事务</param> /// <returns>文件流</returns> protected virtual Stream DoDownloadFile(DbTransaction transaction) { return null; } /// <summary> /// 获取下载大文件(运行在持久层的程序域里) /// </summary> /// <param name="chunkNumber">块号</param> /// <returns>文件块信息</returns> protected override FileChunkInfo DoDownloadBigFile(int chunkNumber) { try { if (typeof(T).GetMethod("DoDownloadBigFile", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(DbConnection), typeof(int) }, null) != null) return DbConnectionHelper.ExecuteGet<int, FileChunkInfo>(DataSourceKey, (Func<DbConnection, int, FileChunkInfo>)DoDownloadBigFile, chunkNumber); if (typeof(T).GetMethod("DoDownloadBigFile", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[] { typeof(DbTransaction), typeof(int) }, null) != null) return DbConnectionHelper.ExecuteGet<int, FileChunkInfo>(DataSourceKey, (Func<DbTransaction, int, FileChunkInfo>)DoDownloadBigFile, chunkNumber); return null; } finally { base.DoDownloadBigFile(chunkNumber); } } /// <summary> /// 获取下载大文件(运行在持久层的程序域里) /// 请使用业务对象处理逻辑 /// 如直接操作数据也请用Phenix.Core.Data.DbCommandHelper与数据库交互以保证可移植性 /// 如果重载了DoDownloadBigFile()且未调用base.DoDownloadBigFile(),则本函数将不会执行到 /// </summary> /// <param name="connection">数据库连接</param> /// <param name="chunkNumber">块号</param> /// <returns>文件块信息</returns> protected virtual FileChunkInfo DoDownloadBigFile(DbConnection connection, int chunkNumber) { return null; } /// <summary> /// 获取下载大文件(运行在持久层的程序域里) /// 请使用业务对象处理逻辑 /// 如直接操作数据也请用Phenix.Core.Data.DbCommandHelper与数据库交互以保证可移植性 /// 如果重载了DoDownloadBigFile()且未调用base.DoDownloadBigFile(),则本函数将不会执行到 /// 如果拦截了异常,请处理后继续抛出,以便交给基类执行Rollback() /// </summary> /// <param name="transaction">数据库事务</param> /// <param name="chunkNumber">块号</param> /// <returns>文件块信息</returns> protected virtual FileChunkInfo DoDownloadBigFile(DbTransaction transaction, int chunkNumber) { return null; } #endregion #endregion } }
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 GraphicalEditor.DTO; using GraphicalEditor.Service; namespace GraphicalEditor { /// <summary> /// Interaction logic for EquipmentRelocationInRoomMoreDetailsDialog.xaml /// </summary> public partial class EquipmentRelocationInRoomMoreDetailsDialog : Window { public int RelocationId { get; set; } public TransferEquipmentDTO RelocationForDisplay { get; set; } EquipmentService _equipmentService; public EquipmentRelocationInRoomMoreDetailsDialog(int relocationId) { InitializeComponent(); DataContext = this; RelocationId = relocationId; _equipmentService = new EquipmentService(); //RelocationForDisplay = _equipmentService.GetEquipmentTransferById(RelocationId); } private void ShowRelocationSuccessfullyCancelledDialog() { InfoDialog infoDialog = new InfoDialog("Uspešno ste otkazali premeštanje opreme!"); infoDialog.ShowDialog(); } private void CancelRelocationButton_Click(object sender, RoutedEventArgs e) { _equipmentService.DeleteEquipmentTransfer(RelocationId); this.Close(); ShowRelocationSuccessfullyCancelledDialog(); } private void CloseButton_Click(object sender, RoutedEventArgs e) { this.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClotheOurKids.Model.Repository { public class RegisterFormRepository : IRegisterFormRepository { private ClotheOurKidsEntities context; public RegisterFormRepository() { context = new ClotheOurKidsEntities(); } public IList<OfficeType> GetAllOfficeTypes() { var query = from officeTypes in context.OfficeTypes select officeTypes; var content = query.ToList<OfficeType>(); return content; } public IList<Office> GetAllOffices() { var query = from offices in context.Offices select offices; var content = query.OrderBy(office => office.Name).ToList<Office>(); return content; } public IList<Position> GetAllPositions() { var query = from positions in context.Positions select positions; var content = query.ToList<Position>(); return content; } public IList<Position> GetPositionsByOfficeType(int officeTypeId) { var query = from positions in context.Positions where positions.PositionOfficeTypes.Any(p => p.OfficeTypeId == officeTypeId) select positions; var content = query.ToList<Position>(); return content; } public IList<Office> GetOfficesByZipCode(string zipcode) { var query = from offices in context.Offices where offices.Address.PostalCode == zipcode select offices; var content = query.OrderBy(office => office.Name).ToList<Office>(); return content; } public IList<Office> GetOfficesByOfficeType(int officeTypeId) { var query = from offices in context.Offices where offices.OfficeTypeId == officeTypeId select offices; var content = query.OrderBy(office => office.Name).ToList<Office>(); return content; } public IList<Position> GetPositionsByOffice(int officeId) { var officeTypeId = (from offices in context.Offices where offices.OfficeId == officeId select offices.OfficeTypeId).FirstOrDefault(); var query = from positions in context.Positions where positions.PositionOfficeTypes.Any(p => p.OfficeTypeId == officeTypeId) select positions; var content = query.ToList<Position>(); return content; } public IList<ContactMethod> GetAllContactMethods() { var query = from contactMethods in context.ContactMethods select contactMethods; var content = query.ToList<ContactMethod>(); return content; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; public class MenuAction : MonoBehaviour { public bool isInGUI = false; protected void OnMouseDown() { if (!isInGUI) { TakeAction(); } } public virtual void TakeAction() { } }
using System; using System.Linq; using MassEffect.Exceptions; namespace MassEffect.Engine.Commands { using MassEffect.Interfaces; public class AttackCommand : Command { public AttackCommand(IGameEngine gameEngine) : base(gameEngine) { } public override void Execute(string[] commandArgs) { string atShipName = commandArgs[1]; string deShipName = commandArgs[2]; IStarship attShip = null; IStarship defShip = null; attShip = this.GameEngine.Starships.First(x => x.Name == atShipName); defShip = this.GameEngine.Starships.First(x => x.Name == deShipName); this.ProcessStarshipBattle(attShip, defShip); } private void ProcessStarshipBattle(IStarship attShip, IStarship defShip) { base.ValidateAlive(attShip); base.ValidateAlive(defShip); if (attShip.Location.Name != defShip.Location.Name) { throw new ShipException(Messages.NoSuchShipInStarSystem); } IProjectile attack = attShip.ProduceAttack(); defShip.RespondToAttack(attack); Console.WriteLine(Messages.ShipAttacked, attShip.Name, defShip.Name); if (defShip.Shields < 0) { defShip.Shields = 0; } if (defShip.Health <= 0) { defShip.Health = 0; Console.WriteLine(Messages.ShipDestroyed, defShip.Name); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AdminPanelIntegration.Models { public class demo { String userid; String token; } }
using System; using System.Runtime.InteropServices; using System.Text; using System.Collections.Generic; namespace ArmaDotNetCore { public class ArmaExtension { //This tells the compiler to create an entrypoint named 'RVExtension'. This line should be added // to each method you want to export. Only public static are accepted. [UnmanagedCallersOnly(EntryPoint = "RVExtension")] /// <summary> /// This is the code that will get executed upon issuing a call to the extension from arma. /// </summary> /// <code> /// "dotnet_a3" callExtension "ourString"; /// </code> /// <param name="output">A pointer to the memory location of a chars array that will be read after issuing callExtension command</param> /// <param name="outputSize">An integer that determines the maximum lenght of the array</param> /// <param name="function">A pointer to the string passed from arma</param> public unsafe static void RVExtension(char* output, int outputSize, char* function) { //Let's grab the string from the pointer passed from the Arma call to our extension //Note the explicit cast string parameter = Marshal.PtrToStringAnsi((IntPtr)function); //Now we have to call the other function to reverse our string char[] strToArr = reverse(parameter); string finalString = new string(strToArr) + '\0'; /* Now that we have our reversed string terminated by the null character, we have to convert it to a byte array in order to allow the arma extension loader (Which is c/c++) to "decode" our string. We'll basically copy our string into the location pointed by the 'output' pointer. */ byte[] byteFinalString = Encoding.ASCII.GetBytes(finalString); //We're done, now that we have our properly encoded byte array, we have to 'assign' its value to the //memory location pointed by output pointer. Marshal.Copy(byteFinalString,0,(IntPtr)output,byteFinalString.Length); } [UnmanagedCallersOnly(EntryPoint = "RVExtensionArgs")] /// <summary> /// This is the code that will get executed upon issuing a call to the extension from arma. Pass back to arma a string formatted like an array. /// </summary> /// <code> /// "dotnet_a3" callExtension ["MyFunction",["arg1",2,"arg3"]]; /// </code> /// <param name="output">A pointer to the memory location of a chars array that will be read after issuing callExtension command</param> /// <param name="outputSize">An integer that determines the maximum lenght of the array</param> /// <param name="function">A pointer to the string passed from arma</param> /// <param name="argv">An array of pointers (char**). IE: A pointer to a memory location where pointers are stored(Still, can't be casted to IntPtr)</param> /// <param name="argc">Integer that points how many arguments there are in argv</param> public unsafe static void RVExtensionArgs(char* output, int outputSize, char* function, char** argv, int argc) { //Let's grab the string from the pointer passed from the Arma call to our extension //Note the explicit cast string mainParam = Marshal.PtrToStringAnsi((IntPtr)function); //Let's create a list with all the parameters inside List<String> parameters = new List<string>(); parameters.Add(mainParam); //Populate our List for (int i=0; i<argc; i++) { string curStr = Marshal.PtrToStringAnsi((IntPtr)argv[i]); parameters.Add(curStr); } //Craft an arma array string armaResult = ListToArma(parameters) + '\0'; /* Now that we have our reversed string terminated by the null character, we have to convert it to a byte array in order to allow the arma extension loader (Which is c/c++) to "decode" our string. We'll basically copy our string into the location pointed by the 'output' pointer. */ byte[] byteFinalString = Encoding.ASCII.GetBytes(armaResult); //We're done, now that we have our properly encoded byte array, we have to 'assign' its value to the //memory location pointed by output pointer. Marshal.Copy(byteFinalString,0,(IntPtr)output,byteFinalString.Length); } [UnmanagedCallersOnly(EntryPoint = "RVExtensionVersion")] /// <summary> /// This is the code that will get executed once the extension gets loaded from arma. /// The output will get printed in RPT logs /// </summary> /// <param name="output">A pointer to the memory location of a chars array that will be read after the load of the extension.</param> /// <param name="outputSize">An integer that determines the maximum lenght of the array</param> public unsafe static void RVExtensionVersion(char* output, int outputSize) { string greetingsString = "|Arma .NET Core Sample|"; string finalString = greetingsString + '\0'; byte[] byteFinalString = Encoding.ASCII.GetBytes(finalString); Marshal.Copy(byteFinalString,0,(IntPtr)output,byteFinalString.Length); } /// <summary> /// This is a function to reverse a provided string and returns a chars array /// </summary> /// <param name="parameter">A generic string to be reversed.</param> /// <returns>A chars array</returns> public static char[] reverse(string parameter) { // Convert the string to char array char[] arr = parameter.ToCharArray(); //Reverse the array Array.Reverse( arr ); //Return reversed array return arr; } public static string ListToArma(List<String> list) { { //Multiple elements var returnString = ""; foreach (var str in list) { if (String.IsNullOrEmpty(returnString)) { returnString += "[" + str + ","; } else { returnString += str + ","; } } returnString = returnString.Remove(returnString.Length - 1); returnString += "]"; return returnString; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Welic.Dominio.Models.Users.Mapeamentos; using Welic.Dominio.Patterns.Pattern.Ef6; namespace Welic.Dominio.Models.Empresa.Map { public class EmpresaMap : Entity { public int IdEmpresa { get; set; } public string RazaoSocial { get; set; } public string Cnpj { get; set; } public string Ie { get; set; } public decimal Fone { get; set; } public decimal? Fone1 { get; set; } public decimal? FoneFax { get; set; } public string Email { get; set; } public string Endereco { get; set; } public string Cep { get; set; } public byte[] Imagem { get; set; } public string ConfigMailUser { get; set; } public string ConfigMailSenha { get; set; } public string ConfigMailSmtp { get; set; } public int? ConfigMailPorta { get; set; } public string InfFaturamento { get; set; } public string Cidade { get; set; } public string Uf { get; set; } public bool? ConfigMailEnableSsl { get; set; } //public ICollection<AspNetUser> Usuarios { get; set; } } }
using Nac.Common; using Nac.Common.Control; using Nac.Wcf.Common; using System; using System.Collections.Generic; using System.Diagnostics; using System.ServiceModel; using System.Threading.Tasks; using static NacEngineGlobal; namespace Nac.Engine { public class NacEngineWcfServer : NacWcfServer<INacWcfEngine, NacEngineWcfServer>, INacWcfEngine, INacWcfEngineCallback { private const int cMaxCachedMessages = 10; INacWcfEngineCallback _callback; public NacEngineWcfServer() { _callback = OperationContext.Current?.GetCallbackChannel<INacWcfEngineCallback>(); G.NacEngineEvent += G_NacEngineEvent; } private List<string> CachedMessages = new List<string>(); private DateTime _lastBroadcast = DateTime.Now; private void G_NacEngineEvent(object sender, NacEngineEventArgs args) { if (args.OriginalArgs is NacEngineLogger.NacEngineLogEventArgs) { var orgArgs = args.OriginalArgs as NacEngineLogger.NacEngineLogEventArgs; if (CachedMessages.Count >= cMaxCachedMessages) CachedMessages.RemoveAt(cMaxCachedMessages - 1); CachedMessages.Add(orgArgs.message); if (CachedMessages.Count > 0 && (DateTime.Now - _lastBroadcast).TotalSeconds >= 1) { Broadcast(CachedMessages.ToArray()); CachedMessages.Clear(); } } } public void Dispose() { G.NacEngineEvent -= G_NacEngineEvent; } private NacEngine Engine { get { return G.Engine; } } public void Update(string[] paths, string property, NacWcfObject[] values) { Engine.Update(paths, property, values); } public void Add(IEnumerable<NacObject> list) { Engine.Add(list); } public NacCatalog<NacObject> GetCatalog() { return Engine.GetCatalog(); } public Dictionary<string, NacTagValue> GetValues(string[] tagPaths) { return Engine.GetValues(tagPaths); } public Dictionary<string, NacTagValue> GetRDTBValues(string rtdbPath) { return Engine.GetRTDBValues(rtdbPath); } public Dictionary<string, NacExecutionStatus> GetSectionStates(string sectionPath) { return Engine.GetSectionStates(sectionPath); } public void Delete(string[] paths) { Engine.Delete(paths); } public void Connect(string blockPathSource, string blockPathDestination, string sourceConnector, string destinationConnector) { Engine.Connect(blockPathSource, blockPathDestination, sourceConnector, destinationConnector); } public void Disconnect(string blockPathSource, string blockPathDestination, string sourceConnector, string destinationConnector) { Engine.Disconnect(blockPathSource, blockPathDestination, sourceConnector, destinationConnector); } private Task _broadcastTask; public void Broadcast(string[] messages) { NacUtils.Decouple(() =>_callback.Broadcast(messages), ref _broadcastTask); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Dog : Singleton<Dog> { [HideInInspector] public Transform target; public float range_vision = 8; public float range_interact = 4; public float stat_hungry = 1000; float stat_hungry_current; public float stat_happiness = 1000; float stat_happiness_current; public float speed = 3; public Animator animator; public Transform gfx; public Vector2 randomBarkInterval; GameObject carryingObject; public Transform carryPos; List<Transform> objectList; enum DogStatus { idle, busy } DogStatus status; void Start() { stat_hungry_current = stat_hungry * 0.7f; stat_happiness_current = stat_happiness * 0.4f; if (randomBarkInterval != Vector2.zero) StartCoroutine(BarkSometimes()); } void Update() { ChangeStat(Stat.hungry, -1); if (stat_hungry_current / stat_hungry < 0.5) { ChangeStat(Stat.happiness, -1); } else { ChangeStat(Stat.happiness, 1); } if (status != DogStatus.idle) return; //无目标就搜索目标 if (target == null) target = SearchTarget(); if (target != null) { status = DogStatus.busy; //有目标向其移动 StartCoroutine(MoveToTarget(target.transform)); } } float HorizontalDistance(Vector3 _origin, Vector3 _target) { _target.y = _origin.y; return Vector3.Distance(_origin, _target); } Transform SearchTarget() { objectList = new List<Transform>(); //去除离玩家太近的物体 for (int i = 0; i < GameManager.instance.interactableobjects.Count; i++) { if (!(GameManager.instance.interactableobjects[i].gameObject.GetComponent<InteractableObject>().type == ObjectType.toy && HorizontalDistance(GameManager.instance.interactableobjects[i].position, Camera.main.transform.position) < 1)) { objectList.Add(GameManager.instance.interactableobjects[i]); } } if (objectList.Count == 0) return null; Transform nearest = objectList[0]; for (int i = 1; i < objectList.Count; i++) { if (Vector3.Distance(transform.position, objectList[i].position) < Vector3.Distance(transform.position, objectList[i - 1].position)) { nearest = objectList[i]; } } return nearest; } IEnumerator MoveToTarget(Transform _target) { animator.SetBool("walking", true); bool speedUp = false; //目标是玩具则加速 if (_target.gameObject.GetComponent<InteractableObject>().type == ObjectType.toy) { speedUp = true; speed *= 2; } //目标在交互范围外 while (Vector3.Distance(transform.position, _target.position) > range_interact) { Vector3 dir = _target.position - transform.position; //设置朝向 if (Mathf.Abs(Vector3.Dot(transform.right, dir.normalized)) > 0.05f) { if (Vector3.Dot(transform.right, dir.normalized) > 0) { transform.localScale = new Vector3(-1, 1, 1); } else { transform.localScale = new Vector3(1, 1, 1); } } if (HorizontalDistance(transform.position, _target.position) > range_interact / 2) { //移动 dir.y = 0; transform.Translate(dir.normalized * speed * Time.deltaTime, Space.World); } yield return null; } if (speedUp) speed /= 2; animator.SetBool("walking", false); Interact(target.gameObject); } //交互 void Interact(GameObject _target) { if (_target.GetComponent<InteractableObject>().type == ObjectType.food) { Eat(_target); } else if (_target.GetComponent<InteractableObject>().type == ObjectType.toy) { Carry(_target); } } //吃掉 void Eat(GameObject _target) { SoundManager.instance.Play("Eat"); ChangeStat(Stat.hungry, 200); target = null; GameManager.instance.interactableobjects.Remove(_target.transform); Destroy(_target); status = DogStatus.idle; } //叼起 void Carry(GameObject _target) { carryingObject = _target; _target.transform.parent = carryPos; _target.transform.localPosition = Vector3.zero; _target.GetComponent<InteractableObject>().Drag(); StartCoroutine(ReturnToy()); } IEnumerator ReturnToy() { animator.SetBool("walking", true); //朝玩家走,小于范围则放下球 while (HorizontalDistance(transform.position, Camera.main.transform.position) > 0.5f) { Vector3 dir = Camera.main.transform.position - transform.position; dir.y = 0; transform.Translate(dir.normalized * speed * Time.deltaTime, Space.World); yield return null; } animator.SetBool("walking", false); Discard(); target = null; status = DogStatus.idle; } //放下 void Discard() { GameObject obj = carryingObject; carryingObject = null; obj.transform.parent = null; obj.GetComponent<InteractableObject>().Left(); } IEnumerator BarkSometimes() { while (true) { yield return new WaitForSeconds(Random.Range(randomBarkInterval.x, randomBarkInterval.y)); SoundManager.instance.Play("Bark"); } } enum Stat { hungry, happiness } void ChangeStat(Stat _stat, int _amount) { if (_stat == Stat.hungry) { stat_hungry_current += _amount; GameManager.instance.slider_hungry.value = stat_hungry_current / stat_hungry; } else if (_stat == Stat.happiness) { stat_happiness_current += _amount; GameManager.instance.slider_happiness.value = stat_happiness_current / stat_happiness; } } }
using System; using System.ComponentModel.DataAnnotations; namespace com.Sconit.Entity.BIL { [Serializable] public partial class BillTransaction : EntityBase { #region O/R Mapping Properties public Int32 Id { get; set; } public string OrderNo { get; set; } public string IpNo { get; set; } public string ExternalIpNo { get; set; } public string ReceiptNo { get; set; } public string ExternalReceiptNo { get; set; } public Boolean IsIncludeTax { get; set; } public string Item { get; set; } public string ItemDescription { get; set; } public string Uom { get; set; } public Decimal UnitCount { get; set; } //public string HuId { get; set; } public com.Sconit.CodeMaster.BillTransactionType TransactionType { get; set; } public string Party { get; set; } public string PartyName { get; set; } public string PriceList { get; set; } public string Currency { get; set; } public Decimal UnitPrice { get; set; } public Boolean IsProvisionalEstimate { get; set; } public string Tax { get; set; } public Decimal BillQty { get; set; } public Decimal BillAmount { get; set; } public string LocationFrom { get; set; } public string SettleLocation { get; set; } public DateTime EffectiveDate { get; set; } //public Int32 PlanBill { get; set; } public Int32 ActingBill { get; set; } public Int32 BillDetail { get; set; } public Int32 CreateUserId { get; set; } public string CreateUserName { get; set; } public DateTime CreateDate { get; set; } public Decimal UnitQty { get; set; } #endregion public override int GetHashCode() { if (Id != 0) { return Id.GetHashCode(); } else { return base.GetHashCode(); } } public override bool Equals(object obj) { BillTransaction another = obj as BillTransaction; if (another == null) { return false; } else { return (this.Id == another.Id); } } } }
/*using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Verse; using RimWorld; namespace D9Framework { class ResearchRequirements : DefModExtension { #pragma warning disable CS0649 public List<ResearchReqProps> requirements; public int threshold; #pragma warning restore CS0649 List<ResearchReq> reqs; public bool Fulfilled => reqs.Where(x => x.Fulfilled).Count() >= threshold; public ResearchRequirements() { reqs = new List<ResearchReq>(); foreach(ResearchReqProps rrp in requirements) { // initialize req with props } } } public abstract class ResearchReqProps { public ResearchProjectDef parent; public int boostAmount = 0; public Type reqClass; public LetterProps letter; } public abstract class ResearchReq { public ResearchReqProps props; private bool fulfilled = false; public virtual bool Fulfilled => fulfilled; public void OnFulfilled() { if(props.boostAmount > 0) props.parent.AddProgress(props.boostAmount); } } }*/
using UnityEngine.SceneManagement; using System.Collections.Generic; using UnityEngine.Audio; using UnityEngine.UI; using UnityEngine; using TMPro; public class PauseSetting : MonoBehaviour { [SerializeField] GameInspector GI; [SerializeField] Player Player; public GameObject PauseMenu; [SerializeField] ItemUI IUI; [SerializeField] GameObject Item; [SerializeField] GameObject ItemUI; [SerializeField] GameObject SettingUI; [SerializeField] GameObject RestartUI; [SerializeField] GameObject MainMenu; [SerializeField] GameObject Exit; [SerializeField] GameObject CurrentActive; [SerializeField] GameObject PreviousActive; [SerializeField] Slider BGM; [SerializeField] Slider SFX; [SerializeField] Slider MouseX; [SerializeField] Slider MouseY; [SerializeField] TextMeshProUGUI BGMText; [SerializeField] TextMeshProUGUI SFXText; [SerializeField] TextMeshProUGUI MouseXText; [SerializeField] TextMeshProUGUI MouseYText; [SerializeField] AudioMixer BackgroundMusic; [SerializeField] AudioMixer SoundEffect; [SerializeField] Transform FirstInsta; [SerializeField] GameObject Click; [SerializeField] GameObject ClickLoc; [SerializeField] GameObject YesLoc; //public TextMeshProUGUI HealthMessage; private void Start() { PauseMenu.SetActive(false); ItemUI.SetActive(true); CurrentActive = ItemUI; ClickLoc = Instantiate(Click,FirstInsta); float BGMValue = (GI.BGM / SFX.minValue * -100) + 100; BGMText.text = BGMValue.ToString("N0"); float SFXValue = (GI.SFX / SFX.minValue * -100) + 100; SFXText.text = SFXValue.ToString("N0"); BGM.value = GI.BGM; SFX.value = GI.SFX; MouseX.value = GI.MouseX; MouseY.value = GI.MouseY; //for (int i = 0; i < GI.Items.Count; i++) //{ // Instantiate(Item, ItemUI.transform); // IUI = Item.GetComponent<ItemUI>(); // //IUI.IH = GI.Items[i]; // IUI.Name.text = GI.Items[i].Name; // IUI.ItemIcon.sprite = GI.Items[i].Icon; // IUI.Count.text = GI.Items.Count.ToString(); // Items.Add(Item); //} } public void Resume() { GameObject ItemDetail = GameObject.FindWithTag("ItemDetail"); if (ItemDetail != null) { Destroy(ItemDetail); } PauseMenu.SetActive(false); Player.Pause = false; Time.timeScale = 1f; Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } public void AddItem(CollectableScript CS) { Instantiate(Item, ItemUI.transform); IUI = Item.GetComponent<ItemUI>(); IUI.CS = CS; } public void DestroyItem(CollectableScript Collectable) { GI.Items.Remove(Collectable); } public void SBackgroundMusic(float Num) { BackgroundMusic.SetFloat("Background Music", Num); GI.BGM = Num; float Show = (Num / SFX.minValue * -100) + 100; BGMText.text = Show.ToString("N0"); } public void SSoundEffect(float Num) { SoundEffect.SetFloat("Sound Effect", Num); GI.SFX = Num; float Show = (Num / SFX.minValue * -100) + 100; SFXText.text = Show.ToString("N0"); } public void MouseSensitivityX(float X) { GI.MouseX = X; Player.MouseSX = X; MouseXText.text = X.ToString("N0"); } public void MouseSensitivityY(float Y) { GI.MouseY = Y; Player.MouseSY = Y; MouseYText.text = Y.ToString("N0"); } public void ItemDisplay() { ItemUI.SetActive(true); SettingUI.SetActive(false); } public void SettingDisplay() { SettingUI.SetActive(true); ItemUI.SetActive(false); } public void HoverUI(Transform Loc) { Loc.localScale = new Vector3(1.2f, 1.2f, 1f); } public void ClickIt(Transform Loc) { if (ClickLoc != null) { Destroy(ClickLoc); } ClickLoc = Instantiate(Click, Loc); } public void CloseOther(GameObject Sketch) { CurrentActive.SetActive(false); CurrentActive = Sketch; CurrentActive.SetActive(true); } public void QuitHover(Transform Loc) { Loc.transform.localScale = new Vector3( 1 , 1f, 1f); } public void YesHover(Transform Loc) { YesLoc = Instantiate(Click, Loc); } public void YesExit() { Destroy(YesLoc); } public void Restart() { SceneManager.LoadScene("Level Scene"); CleanData(); } public void ToMainMenu() { SceneManager.LoadScene("Main Menu"); CleanData(); } public void CleanData() { GI.Items.Clear(); } public void ExitGame() { Application.Quit(); } public void CreditScene() { SceneManager.LoadScene("Credit Scene"); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Omega.Lib.APNG.Chunks { public class Iend : APngChunk { public Iend() : base(ChunkType.IEND) { } #region Overrides of APngChunk public override MemoryStream Data { get { return new MemoryStream(); } } #endregion } }
using System; using System.Collections.Generic; namespace POSServices.PosMsgModels { public partial class JobTabletoSynchDetailUpload { public long SynchDetail { get; set; } public long JobId { get; set; } public string StoreId { get; set; } public string TableName { get; set; } public string UploadPath { get; set; } public DateTime Synchdate { get; set; } public string CreateTable { get; set; } public int? RowFatch { get; set; } } public class syncUploadDetail { public int syncDetailsId { get; set; } public int JobId { get; set; } public string StoreId { get; set; } public string TableName { get; set; } public string UploadPath { get; set; } public DateTime Synchdate { get; set; } public string CreateTable { get; set; } public int RowFatch { get; set; } public int MinId { get; set; } public int MaxId { get; set; } public string TablePrimaryKey { get; set; } public string identityColumn { get; set; } } public class bracketSyncUploadDetail { public List<syncUploadDetail> uploadDetails { get; set; } } }