The full dataset viewer is not available (click to read why). Only showing a preview of the rows.
Job manager crashed while running this job (missing heartbeats).
Error code:   JobManagerCrashedError

Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.

text
string
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This class defines behaviors specific to a writing system. // A writing system is the collection of scripts and // orthographic rules required to represent a language as text. // // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { using System; using System.Runtime.Serialization; using System.Security.Permissions; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public class StringInfo { [OptionalField(VersionAdded = 2)] private String m_str; // We allow this class to be serialized but there is no conceivable reason // for them to do so. Thus, we do not serialize the instance variables. [NonSerialized] private int[] m_indexes; // Legacy constructor public StringInfo() : this(""){} // Primary, useful constructor public StringInfo(String value) { this.String = value; } #region Serialization [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { m_str = String.Empty; } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { if (m_str.Length == 0) { m_indexes = null; } } #endregion Serialization [System.Runtime.InteropServices.ComVisible(false)] public override bool Equals(Object value) { StringInfo that = value as StringInfo; if (that != null) { return (this.m_str.Equals(that.m_str)); } return (false); } [System.Runtime.InteropServices.ComVisible(false)] public override int GetHashCode() { return this.m_str.GetHashCode(); } // Our zero-based array of index values into the string. Initialize if // our private array is not yet, in fact, initialized. private int[] Indexes { get { if((null == this.m_indexes) && (0 < this.String.Length)) { this.m_indexes = StringInfo.ParseCombiningCharacters(this.String); } return(this.m_indexes); } } public String String { get { return(this.m_str); } set { if (null == value) { throw new ArgumentNullException(nameof(String), Environment.GetResourceString("ArgumentNull_String")); } Contract.EndContractBlock(); this.m_str = value; this.m_indexes = null; } } public int LengthInTextElements { get { if(null == this.Indexes) { // Indexes not initialized, so assume length zero return(0); } return(this.Indexes.Length); } } public String SubstringByTextElements(int startingTextElement) { // If the string is empty, no sense going further. if(null == this.Indexes) { // Just decide which error to give depending on the param they gave us.... if(startingTextElement < 0) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } else { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } } return (this.SubstringByTextElements(startingTextElement, this.Indexes.Length - startingTextElement)); } public String SubstringByTextElements(int startingTextElement, int lengthInTextElements) { // // Parameter checking // if(startingTextElement < 0) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } if(this.String.Length == 0 || startingTextElement >= this.Indexes.Length) { throw new ArgumentOutOfRangeException(nameof(startingTextElement), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } if(lengthInTextElements < 0) { throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } if(startingTextElement > this.Indexes.Length - lengthInTextElements) { throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), Environment.GetResourceString("Arg_ArgumentOutOfRangeException")); } int start = this.Indexes[startingTextElement]; if(startingTextElement + lengthInTextElements == this.Indexes.Length) { // We are at the last text element in the string and because of that // must handle the call differently. return(this.String.Substring(start)); } else { return(this.String.Substring(start, (this.Indexes[lengthInTextElements + startingTextElement] - start))); } } public static String GetNextTextElement(String str) { return (GetNextTextElement(str, 0)); } //////////////////////////////////////////////////////////////////////// // // Get the code point count of the current text element. // // A combining class is defined as: // A character/surrogate that has the following Unicode category: // * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT) // * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA) // * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE) // // In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as: // // 1. If a character/surrogate is in the following category, it is a text element. // It can NOT further combine with characters in the combinging class to form a text element. // * one of the Unicode category in the combinging class // * UnicodeCategory.Format // * UnicodeCateogry.Control // * UnicodeCategory.OtherNotAssigned // 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element. // // Return: // The length of the current text element // // Parameters: // String str // index The starting index // len The total length of str (to define the upper boundary) // ucCurrent The Unicode category pointed by Index. It will be updated to the uc of next character if this is not the last text element. // currentCharCount The char count of an abstract char pointed by Index. It will be updated to the char count of next abstract character if this is not the last text element. // //////////////////////////////////////////////////////////////////////// internal static int GetCurrentTextElementLen(String str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount) { Contract.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); Contract.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len); if (index + currentCharCount == len) { // This is the last character/surrogate in the string. return (currentCharCount); } // Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not. int nextCharCount; UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount); if (CharUnicodeInfo.IsCombiningCategory(ucNext)) { // The next element is a combining class. // Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category, // not a format character, and not a control character). if (CharUnicodeInfo.IsCombiningCategory(ucCurrent) || (ucCurrent == UnicodeCategory.Format) || (ucCurrent == UnicodeCategory.Control) || (ucCurrent == UnicodeCategory.OtherNotAssigned) || (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate { // Will fall thru and return the currentCharCount } else { int startIndex = index; // Remember the current index. // We have a valid base characters, and we have a character (or surrogate) that is combining. // Check if there are more combining characters to follow. // Check if the next character is a nonspacing character. index += currentCharCount + nextCharCount; while (index < len) { ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount); if (!CharUnicodeInfo.IsCombiningCategory(ucNext)) { ucCurrent = ucNext; currentCharCount = nextCharCount; break; } index += nextCharCount; } return (index - startIndex); } } // The return value will be the currentCharCount. int ret = currentCharCount; ucCurrent = ucNext; // Update currentCharCount. currentCharCount = nextCharCount; return (ret); } // Returns the str containing the next text element in str starting at // index index. If index is not supplied, then it will start at the beginning // of str. It recognizes a base character plus one or more combining // characters or a properly formed surrogate pair as a text element. See also // the ParseCombiningCharacters() and the ParseSurrogates() methods. public static String GetNextTextElement(String str, int index) { // // Validate parameters. // if (str==null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; if (index < 0 || index >= len) { if (index == len) { return (String.Empty); } throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } int charLen; UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen); return (str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen))); } public static TextElementEnumerator GetTextElementEnumerator(String str) { return (GetTextElementEnumerator(str, 0)); } public static TextElementEnumerator GetTextElementEnumerator(String str, int index) { // // Validate parameters. // if (str==null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; if (index < 0 || (index > len)) { throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_Index")); } return (new TextElementEnumerator(str, index, len)); } /* * Returns the indices of each base character or properly formed surrogate pair * within the str. It recognizes a base character plus one or more combining * characters or a properly formed surrogate pair as a text element and returns * the index of the base character or high surrogate. Each index is the * beginning of a text element within a str. The length of each element is * easily computed as the difference between successive indices. The length of * the array will always be less than or equal to the length of the str. For * example, given the str \u4f00\u302a\ud800\udc00\u4f01, this method would * return the indices: 0, 2, 4. */ public static int[] ParseCombiningCharacters(String str) { if (str == null) { throw new ArgumentNullException(nameof(str)); } Contract.EndContractBlock(); int len = str.Length; int[] result = new int[len]; if (len == 0) { return (result); } int resultCount = 0; int i = 0; int currentCharLen; UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen); while (i < len) { result[resultCount++] = i; i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen); } if (resultCount < len) { int[] returnArray = new int[resultCount]; Array.Copy(result, returnArray, resultCount); return (returnArray); } return (result); } } }
using System.Collections.Generic; using UnityEngine; using System; namespace AI { public class GreedyAIController : PlayerController { enum NextState { Wait, Draw, Play } private NextState nextState; Dictionary<DominoController, List<DominoController>> placesToPlay = null; private void Update() { switch (nextState) { case NextState.Wait: return; case NextState.Draw: if (history.horizontalDominoes.Count > 0) { placesToPlay = PlacesToPlay(); if (placesToPlay.Count == 0) { base.DrawDomino(); placesToPlay = PlacesToPlay(); if (placesToPlay.Count == 0) { nextState = NextState.Wait; gameController.PlayerIsBlocked(this); return; } } } nextState = NextState.Play; break; case NextState.Play: List<ChosenWayToPlay> waysToPlay = new List<ChosenWayToPlay>(); if (history.horizontalDominoes.Count == 0) { foreach (DominoController domino in dominoControllers) { waysToPlay.Add(new ChosenWayToPlay(domino, null)); } } else { foreach (KeyValuePair<DominoController, List<DominoController>> entry in placesToPlay) { List<DominoController> list = entry.Value; foreach (DominoController chosenPlace in list) { ChosenWayToPlay chosenWayToPlay = new ChosenWayToPlay(entry.Key, chosenPlace); waysToPlay.Add(chosenWayToPlay); } } } // From small to large waysToPlay.Sort(delegate (ChosenWayToPlay x, ChosenWayToPlay y) { int xScore = GetScoreOfChosenWay(x); int yScore = GetScoreOfChosenWay(y); return xScore - yScore; }); ChosenWayToPlay bestWayToPlay = waysToPlay[waysToPlay.Count - 1]; PlaceDomino(bestWayToPlay.chosenDomino, bestWayToPlay.chosenPlace, history); dominoControllers.Remove(bestWayToPlay.chosenDomino); // Debug Debug.Log("Chosen Domino: " + bestWayToPlay.chosenDomino.leftValue + ", " + bestWayToPlay.chosenDomino.rightValue + ", " + bestWayToPlay.chosenDomino.upperValue + ", " + bestWayToPlay.chosenDomino.lowerValue); if (bestWayToPlay.chosenPlace != null) { Debug.Log("Chosen Place: " + bestWayToPlay.chosenPlace.leftValue + ", " + bestWayToPlay.chosenPlace.rightValue + ", " + bestWayToPlay.chosenPlace.upperValue + ", " + bestWayToPlay.chosenPlace.lowerValue); } Debug.Log(Environment.StackTrace); nextState = NextState.Wait; gameController.PlayerPlayDomino(this, bestWayToPlay.chosenDomino, bestWayToPlay.chosenPlace); break; } } public override void PlayDomino() { nextState = NextState.Draw; } private Dictionary<DominoController, List<DominoController>> PlacesToPlay() { Dictionary<DominoController, List<DominoController>> placesToPlay = new Dictionary<DominoController, List<DominoController>>(dominoControllers.Count * 4); foreach (DominoController domino in dominoControllers) { // Add places can be played for each domino List<DominoController> places = base.ListOfValidPlaces(domino); if (places == null) { continue; } placesToPlay.Add(domino, places); } return placesToPlay; } private int GetScoreOfChosenWay(ChosenWayToPlay wayToPlay) { int score = 0; // If history has no domino if (history.horizontalDominoes.Count == 0) { if (wayToPlay.chosenDomino.direction == DominoController.Direction.Horizontal) { int value = wayToPlay.chosenDomino.leftValue + wayToPlay.chosenDomino.rightValue; score = (value % 5 == 0) ? value : 0; } else { int value = wayToPlay.chosenDomino.upperValue + wayToPlay.chosenDomino.lowerValue; score = (value % 5 == 0) ? value : 0; } return score; } // Else that history has at least 1 domino DominoController copiedDomino = Instantiate<DominoController>(wayToPlay.chosenDomino); HistoryController copiedHistory = Instantiate<HistoryController>(history); // Simulate to place a domino and then calculate the sum PlaceDomino(copiedDomino, wayToPlay.chosenPlace, copiedHistory); copiedHistory.Add(copiedDomino, wayToPlay.chosenPlace); score = Utility.GetSumOfHistoryDominoes(copiedHistory.horizontalDominoes, copiedHistory.verticalDominoes, copiedHistory.spinner); score = score % 5 == 0 ? score : 0; Destroy(copiedDomino.gameObject); Destroy(copiedHistory.gameObject); return score; } private void PlaceDomino(DominoController chosenDomino, DominoController chosenPlace, HistoryController history) { DominoController clickedDomino = chosenPlace; int horizontalLen = history.horizontalDominoes.Count; int verticalLen = history.verticalDominoes.Count; if (chosenDomino != null) { if (chosenPlace != null) { if (chosenPlace == history.horizontalDominoes[0]) { if (clickedDomino.leftValue == -1) { if (chosenDomino.upperValue == clickedDomino.upperValue || chosenDomino.lowerValue == clickedDomino.upperValue) { chosenPlace = clickedDomino; if (chosenDomino.upperValue == clickedDomino.upperValue) chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue); else chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue); return; } } else { if (chosenDomino.upperValue == clickedDomino.leftValue && chosenDomino.upperValue == chosenDomino.lowerValue) { chosenPlace = clickedDomino; return; } else if (chosenDomino.upperValue == clickedDomino.leftValue || chosenDomino.lowerValue == clickedDomino.leftValue) { chosenPlace = clickedDomino; if (chosenDomino.upperValue == clickedDomino.leftValue) chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue); else chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue); return; } } } if (clickedDomino == history.horizontalDominoes[horizontalLen - 1]) { if (clickedDomino.leftValue == -1) { if (chosenDomino.upperValue == clickedDomino.upperValue || chosenDomino.lowerValue == clickedDomino.upperValue) { chosenPlace = clickedDomino; if (chosenDomino.upperValue == clickedDomino.upperValue) chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue); else chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue); return; } } else { if (chosenDomino.upperValue == clickedDomino.rightValue && chosenDomino.upperValue == chosenDomino.lowerValue) { chosenPlace = clickedDomino; return; } else if (chosenDomino.upperValue == clickedDomino.rightValue || chosenDomino.lowerValue == clickedDomino.rightValue) { chosenPlace = clickedDomino; if (chosenDomino.upperValue == clickedDomino.rightValue) chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue); else chosenDomino.SetLeftRightValues(chosenDomino.lowerValue, chosenDomino.upperValue); return; } } } if (verticalLen > 0 && clickedDomino == history.verticalDominoes[0]) { if (clickedDomino.leftValue == -1) { if (chosenDomino.upperValue == clickedDomino.upperValue && chosenDomino.upperValue == chosenDomino.lowerValue) { chosenPlace = clickedDomino; chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue); return; } else if (chosenDomino.upperValue == clickedDomino.upperValue || chosenDomino.lowerValue == clickedDomino.upperValue) { chosenPlace = clickedDomino; if (chosenDomino.upperValue == clickedDomino.upperValue) chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue); return; } } else { if (chosenDomino.upperValue == clickedDomino.leftValue || chosenDomino.lowerValue == clickedDomino.leftValue) { chosenPlace = clickedDomino; if (chosenDomino.upperValue == clickedDomino.leftValue) chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue); return; } } } if (verticalLen > 0 && clickedDomino == history.verticalDominoes[verticalLen - 1]) { if (clickedDomino.leftValue == -1) { if (chosenDomino.upperValue == clickedDomino.lowerValue && chosenDomino.upperValue == chosenDomino.lowerValue) { chosenPlace = clickedDomino; chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue); return; } else if (chosenDomino.upperValue == clickedDomino.lowerValue || chosenDomino.lowerValue == clickedDomino.lowerValue) { chosenPlace = clickedDomino; if (chosenDomino.lowerValue == clickedDomino.lowerValue) chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue); return; } } else { if (chosenDomino.upperValue == clickedDomino.leftValue || chosenDomino.lowerValue == clickedDomino.leftValue) { chosenPlace = clickedDomino; if (chosenDomino.lowerValue == clickedDomino.leftValue) chosenDomino.SetUpperLowerValues(chosenDomino.lowerValue, chosenDomino.upperValue); return; } } } } else { if (chosenDomino.upperValue != chosenDomino.lowerValue) chosenDomino.SetLeftRightValues(chosenDomino.upperValue, chosenDomino.lowerValue); } } } } }
using Portal.CMS.Entities.Enumerators; using Portal.CMS.Services.Generic; using Portal.CMS.Services.PageBuilder; using Portal.CMS.Web.Architecture.ActionFilters; using Portal.CMS.Web.Architecture.Extensions; using Portal.CMS.Web.Areas.PageBuilder.ViewModels.Component; using Portal.CMS.Web.ViewModels.Shared; using System; using System.Linq; using System.Threading.Tasks; using System.Web.Mvc; using System.Web.SessionState; namespace Portal.CMS.Web.Areas.PageBuilder.Controllers { [AdminFilter(ActionFilterResponseType.Modal)] [SessionState(SessionStateBehavior.ReadOnly)] public class ComponentController : Controller { private readonly IPageSectionService _pageSectionService; private readonly IPageComponentService _pageComponentService; private readonly IImageService _imageService; public ComponentController(IPageSectionService pageSectionService, IPageComponentService pageComponentService, IImageService imageService) { _pageSectionService = pageSectionService; _pageComponentService = pageComponentService; _imageService = imageService; } [HttpGet] [OutputCache(Duration = 86400)] public async Task<ActionResult> Add() { var model = new AddViewModel { PageComponentTypeList = await _pageComponentService.GetComponentTypesAsync() }; return View("_Add", model); } [HttpPost] [ValidateInput(false)] public async Task<JsonResult> Add(int pageSectionId, string containerElementId, string elementBody) { elementBody = elementBody.Replace("animated bounce", string.Empty); await _pageComponentService.AddAsync(pageSectionId, containerElementId, elementBody); return Json(new { State = true }); } [HttpPost] public async Task<ActionResult> Delete(int pageSectionId, string elementId) { try { await _pageComponentService.DeleteAsync(pageSectionId, elementId); return Json(new { State = true }); } catch (Exception ex) { return Json(new { State = false, Message = ex.InnerException }); } } [HttpPost] [ValidateInput(false)] public async Task<ActionResult> Edit(int pageSectionId, string elementId, string elementHtml) { await _pageComponentService.EditElementAsync(pageSectionId, elementId, elementHtml); return Content("Refresh"); } [HttpGet] public async Task<ActionResult> EditImage(int pageSectionId, string elementId, string elementType) { var imageList = await _imageService.GetAsync(); var model = new ImageViewModel { SectionId = pageSectionId, ElementType = elementType, ElementId = elementId, GeneralImages = new PaginationViewModel { PaginationType = "general", TargetInputField = "SelectedImageId", ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.General) }, IconImages = new PaginationViewModel { PaginationType = "icon", TargetInputField = "SelectedImageId", ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.Icon) }, ScreenshotImages = new PaginationViewModel { PaginationType = "screenshot", TargetInputField = "SelectedImageId", ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.Screenshot) }, TextureImages = new PaginationViewModel { PaginationType = "texture", TargetInputField = "SelectedImageId", ImageList = imageList.Where(x => x.ImageCategory == ImageCategory.Texture) } }; return View("_EditImage", model); } [HttpPost] public async Task<JsonResult> EditImage(ImageViewModel model) { try { var selectedImage = await _imageService.GetAsync(model.SelectedImageId); await _pageComponentService.EditImageAsync(model.SectionId, model.ElementType, model.ElementId, selectedImage.CDNImagePath()); return Json(new { State = true, Source = selectedImage.CDNImagePath() }); } catch (Exception) { return Json(new { State = false }); } } [HttpGet] public ActionResult EditVideo(int pageSectionId, string widgetWrapperElementId, string videoPlayerElementId) { var model = new VideoViewModel { SectionId = pageSectionId, WidgetWrapperElementId = widgetWrapperElementId, VideoPlayerElementId = videoPlayerElementId, VideoUrl = string.Empty }; return View("_EditVideo", model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> EditVideo(VideoViewModel model) { try { await _pageComponentService.EditSourceAsync(model.SectionId, model.VideoPlayerElementId, model.VideoUrl); return Json(new { State = true }); } catch (Exception) { return Json(new { State = false }); } } [HttpGet] public ActionResult EditContainer(int pageSectionId, string elementId) { var model = new ContainerViewModel { SectionId = pageSectionId, ElementId = elementId }; return View("_EditContainer", model); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> EditContainer(ContainerViewModel model) { await _pageSectionService.EditAnimationAsync(model.SectionId, model.ElementId, model.Animation.ToString()); return Content("Refresh"); } [HttpPost] [ValidateInput(false)] public async Task<ActionResult> Link(int pageSectionId, string elementId, string elementHtml, string elementHref, string elementTarget) { await _pageComponentService.EditAnchorAsync(pageSectionId, elementId, elementHtml, elementHref, elementTarget); return Content("Refresh"); } [HttpPost] public async Task<JsonResult> Clone(int pageSectionId, string elementId, string componentStamp) { await _pageComponentService.CloneElementAsync(pageSectionId, elementId, componentStamp); return Json(new { State = true }); } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web; namespace Umbraco.Core { ///<summary> /// Extension methods for dictionary & concurrentdictionary ///</summary> internal static class DictionaryExtensions { /// <summary> /// Method to Get a value by the key. If the key doesn't exist it will create a new TVal object for the key and return it. /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TVal"></typeparam> /// <param name="dict"></param> /// <param name="key"></param> /// <returns></returns> public static TVal GetOrCreate<TKey, TVal>(this IDictionary<TKey, TVal> dict, TKey key) where TVal : class, new() { if (dict.ContainsKey(key) == false) { dict.Add(key, new TVal()); } return dict[key]; } /// <summary> /// Updates an item with the specified key with the specified value /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="dict"></param> /// <param name="key"></param> /// <param name="updateFactory"></param> /// <returns></returns> /// <remarks> /// Taken from: http://stackoverflow.com/questions/12240219/is-there-a-way-to-use-concurrentdictionary-tryupdate-with-a-lambda-expression /// /// If there is an item in the dictionary with the key, it will keep trying to update it until it can /// </remarks> public static bool TryUpdate<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key, Func<TValue, TValue> updateFactory) { TValue curValue; while (dict.TryGetValue(key, out curValue)) { if (dict.TryUpdate(key, updateFactory(curValue), curValue)) return true; //if we're looping either the key was removed by another thread, or another thread //changed the value, so we start again. } return false; } /// <summary> /// Updates an item with the specified key with the specified value /// </summary> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <param name="dict"></param> /// <param name="key"></param> /// <param name="updateFactory"></param> /// <returns></returns> /// <remarks> /// Taken from: http://stackoverflow.com/questions/12240219/is-there-a-way-to-use-concurrentdictionary-tryupdate-with-a-lambda-expression /// /// WARNING: If the value changes after we've retreived it, then the item will not be updated /// </remarks> public static bool TryUpdateOptimisitic<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> dict, TKey key, Func<TValue, TValue> updateFactory) { TValue curValue; if (!dict.TryGetValue(key, out curValue)) return false; dict.TryUpdate(key, updateFactory(curValue), curValue); return true;//note we return true whether we succeed or not, see explanation below. } /// <summary> /// Converts a dictionary to another type by only using direct casting /// </summary> /// <typeparam name="TKeyOut"></typeparam> /// <typeparam name="TValOut"></typeparam> /// <param name="d"></param> /// <returns></returns> public static IDictionary<TKeyOut, TValOut> ConvertTo<TKeyOut, TValOut>(this IDictionary d) { var result = new Dictionary<TKeyOut, TValOut>(); foreach (DictionaryEntry v in d) { result.Add((TKeyOut)v.Key, (TValOut)v.Value); } return result; } /// <summary> /// Converts a dictionary to another type using the specified converters /// </summary> /// <typeparam name="TKeyOut"></typeparam> /// <typeparam name="TValOut"></typeparam> /// <param name="d"></param> /// <param name="keyConverter"></param> /// <param name="valConverter"></param> /// <returns></returns> public static IDictionary<TKeyOut, TValOut> ConvertTo<TKeyOut, TValOut>(this IDictionary d, Func<object, TKeyOut> keyConverter, Func<object, TValOut> valConverter) { var result = new Dictionary<TKeyOut, TValOut>(); foreach (DictionaryEntry v in d) { result.Add(keyConverter(v.Key), valConverter(v.Value)); } return result; } /// <summary> /// Converts a dictionary to a NameValueCollection /// </summary> /// <param name="d"></param> /// <returns></returns> public static NameValueCollection ToNameValueCollection(this IDictionary<string, string> d) { var n = new NameValueCollection(); foreach (var i in d) { n.Add(i.Key, i.Value); } return n; } /// <summary> /// Merges all key/values from the sources dictionaries into the destination dictionary /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TK"></typeparam> /// <typeparam name="TV"></typeparam> /// <param name="destination">The source dictionary to merge other dictionaries into</param> /// <param name="overwrite"> /// By default all values will be retained in the destination if the same keys exist in the sources but /// this can changed if overwrite = true, then any key/value found in any of the sources will overwritten in the destination. Note that /// it will just use the last found key/value if this is true. /// </param> /// <param name="sources">The other dictionaries to merge values from</param> public static void MergeLeft<T, TK, TV>(this T destination, IEnumerable<IDictionary<TK, TV>> sources, bool overwrite = false) where T : IDictionary<TK, TV> { foreach (var p in sources.SelectMany(src => src).Where(p => overwrite || destination.ContainsKey(p.Key) == false)) { destination[p.Key] = p.Value; } } /// <summary> /// Merges all key/values from the sources dictionaries into the destination dictionary /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TK"></typeparam> /// <typeparam name="TV"></typeparam> /// <param name="destination">The source dictionary to merge other dictionaries into</param> /// <param name="overwrite"> /// By default all values will be retained in the destination if the same keys exist in the sources but /// this can changed if overwrite = true, then any key/value found in any of the sources will overwritten in the destination. Note that /// it will just use the last found key/value if this is true. /// </param> /// <param name="source">The other dictionary to merge values from</param> public static void MergeLeft<T, TK, TV>(this T destination, IDictionary<TK, TV> source, bool overwrite = false) where T : IDictionary<TK, TV> { destination.MergeLeft(new[] {source}, overwrite); } /// <summary> /// Returns the value of the key value based on the key, if the key is not found, a null value is returned /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TVal">The type of the val.</typeparam> /// <param name="d">The d.</param> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <returns></returns> public static TVal GetValue<TKey, TVal>(this IDictionary<TKey, TVal> d, TKey key, TVal defaultValue = default(TVal)) { if (d.ContainsKey(key)) { return d[key]; } return defaultValue; } /// <summary> /// Returns the value of the key value based on the key as it's string value, if the key is not found, then an empty string is returned /// </summary> /// <param name="d"></param> /// <param name="key"></param> /// <returns></returns> public static string GetValueAsString<TKey, TVal>(this IDictionary<TKey, TVal> d, TKey key) { if (d.ContainsKey(key)) { return d[key].ToString(); } return String.Empty; } /// <summary> /// Returns the value of the key value based on the key as it's string value, if the key is not found or is an empty string, then the provided default value is returned /// </summary> /// <param name="d"></param> /// <param name="key"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static string GetValueAsString<TKey, TVal>(this IDictionary<TKey, TVal> d, TKey key, string defaultValue) { if (d.ContainsKey(key)) { var value = d[key].ToString(); if (value != string.Empty) return value; } return defaultValue; } /// <summary>contains key ignore case.</summary> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <typeparam name="TValue">Value Type</typeparam> /// <returns>The contains key ignore case.</returns> public static bool ContainsKeyIgnoreCase<TValue>(this IDictionary<string, TValue> dictionary, string key) { return dictionary.Keys.InvariantContains(key); } /// <summary> /// Converts a dictionary object to a query string representation such as: /// firstname=shannon&lastname=deminick /// </summary> /// <param name="d"></param> /// <returns></returns> public static string ToQueryString(this IDictionary<string, object> d) { if (!d.Any()) return ""; var builder = new StringBuilder(); foreach (var i in d) { builder.Append(String.Format("{0}={1}&", HttpUtility.UrlEncode(i.Key), i.Value == null ? string.Empty : HttpUtility.UrlEncode(i.Value.ToString()))); } return builder.ToString().TrimEnd('&'); } /// <summary>The get entry ignore case.</summary> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <typeparam name="TValue">The type</typeparam> /// <returns>The entry</returns> public static TValue GetValueIgnoreCase<TValue>(this IDictionary<string, TValue> dictionary, string key) { return dictionary.GetValueIgnoreCase(key, default(TValue)); } /// <summary>The get entry ignore case.</summary> /// <param name="dictionary">The dictionary.</param> /// <param name="key">The key.</param> /// <param name="defaultValue">The default value.</param> /// <typeparam name="TValue">The type</typeparam> /// <returns>The entry</returns> public static TValue GetValueIgnoreCase<TValue>(this IDictionary<string, TValue> dictionary, string key, TValue defaultValue) { key = dictionary.Keys.FirstOrDefault(i => i.InvariantEquals(key)); return key.IsNullOrWhiteSpace() == false ? dictionary[key] : defaultValue; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VaiFundos { class Program { static void Main(string[] args) { GerenciadorCliente gerenciador = new GerenciadorCliente(); FundosEmDolar fundo_dolar1 = new FundosEmDolar("Fundos USA", "FSA"); FundosEmDolar fundo_dolar2 = new FundosEmDolar("Cambio USA", "CSA"); FundosEmReal fundo_real1 = new FundosEmReal("Fundo Deposito Interbancario", "DI"); FundosEmReal fundo_real2 = new FundosEmReal("Atmos Master", "FIA"); int opcao = 0; Console.WriteLine("*==============Vai Fundos===================*"); Console.WriteLine("*-------------------------------------------*"); Console.WriteLine("*1------Cadastro Cliente--------------------*"); Console.WriteLine("*2------Fazer Aplicacao---------------------*"); Console.WriteLine("*3------Listar Clientes---------------------*"); Console.WriteLine("*4------Relatorio Do Cliente----------------*"); Console.WriteLine("*5------Relatorio Do Fundo------------------*"); Console.WriteLine("*6------Transferir Aplicacao De Fundo-------*"); Console.WriteLine("*7------Resgatar Aplicacao------------------*"); Console.WriteLine("*8------Sair Do Sistema --------------------*"); Console.WriteLine("*===========================================*"); Console.WriteLine("Informe a opcao Desejada:"); opcao = int.Parse(Console.ReadLine()); while(opcao >= 1 && opcao < 8) { if (opcao == 1) { Console.WriteLine("Informe o nome do Cliente Que deseja Cadastrar"); gerenciador.cadastrarCliente(Console.ReadLine()); Console.WriteLine("Toque uma tecla para voltar ao menu principal:"); Console.ReadKey(); Console.Clear(); } else if (opcao == 2) { int codFundo = 0; Console.WriteLine("Cod: 1-{0}", fundo_dolar1.getInfFundo()); Console.WriteLine("Cod: 2-{0}", fundo_dolar2.getInfFundo()); Console.WriteLine("Cod: 3-{0}", fundo_real1.getInfFundo()); Console.WriteLine("Cod: 4-{0}", fundo_real2.getInfFundo()); Console.WriteLine("Informe o Codigo Do Fundo que Deseja Aplicar"); codFundo = int.Parse(Console.ReadLine()); if (codFundo == 1) { double valorAplicacao = 0; int codCliente = 0; gerenciador.listarClientes(); Console.WriteLine("Informe o Codigo do Cliente que Deseja Aplicar:"); codCliente = int.Parse(Console.ReadLine()); Console.WriteLine("Informe o valor da Aplicacao"); valorAplicacao = double.Parse(Console.ReadLine()); fundo_dolar1.Aplicar(valorAplicacao, codCliente, gerenciador); Console.WriteLine("Toque uma tecla para voltar ao menu principal:"); Console.ReadKey(); Console.Clear(); } else if (codFundo == 2) { double valorAplicacao = 0; int codCliente = 0; gerenciador.listarClientes(); Console.WriteLine("Informe o Codigo do Cliente que Deseja Aplicar:"); codCliente = int.Parse(Console.ReadLine()); Console.WriteLine("Informe o valor da Aplicacao"); valorAplicacao = double.Parse(Console.ReadLine()); fundo_dolar2.Aplicar(valorAplicacao, codCliente, gerenciador); Console.WriteLine("Toque uma tecla para voltar ao menu principal:"); Console.ReadKey(); Console.Clear(); } else if (codFundo == 3) { double valorAplicacao = 0; int codCliente = 0; gerenciador.listarClientes(); Console.WriteLine("Informe o Codigo do Cliente que Deseja Aplicar:"); codCliente = int.Parse(Console.ReadLine()); Console.WriteLine("Informe o valor da Aplicacao"); valorAplicacao = double.Parse(Console.ReadLine()); fundo_real1.Aplicar(valorAplicacao, codCliente, gerenciador); Console.WriteLine("Toque uma tecla para voltar ao menu principal:"); Console.ReadKey(); Console.Clear(); } else if (codFundo == 4) { double valorAplicacao = 0; int codCliente = 0; gerenciador.listarClientes(); Console.WriteLine("Informe o Codigo do Cliente que Deseja Aplicar:"); codCliente = int.Parse(Console.ReadLine()); Console.WriteLine("Informe o valor da Aplicacao"); valorAplicacao = double.Parse(Console.ReadLine()); fundo_real2.Aplicar(valorAplicacao, codCliente, gerenciador); Console.WriteLine("Toque uma tecla para voltar ao menu principal:"); Console.ReadKey(); Console.Clear(); } } else if (opcao == 3) { Console.Clear(); Console.WriteLine("Clientes Cadastrados:"); gerenciador.listarClientes(); Console.WriteLine("Toque uma tecla para voltar ao menu principal:"); Console.ReadKey(); } else if (opcao == 4) { int codCliente = 0; Console.WriteLine("Clientes Cadastrados"); gerenciador.listarClientes(); codCliente = int.Parse(Console.ReadLine()); gerenciador.relatorioCliente(gerenciador.buscaCliente(codCliente)); Console.WriteLine("Toque uma tecla para voltar ao menu principal:"); Console.ReadKey(); } else if (opcao == 5) { int codFundo = 0; Console.WriteLine("1-{0}", fundo_dolar1.getInfFundo()); Console.WriteLine("2-{0}", fundo_dolar2.getInfFundo()); Console.WriteLine("3-{0}", fundo_real1.getInfFundo()); Console.WriteLine("4-{0}", fundo_real2.getInfFundo()); Console.WriteLine("Informe o Codigo Do Fundo que Deseja o Relatorio"); codFundo = int.Parse(Console.ReadLine()); if (codFundo == 1) { fundo_dolar1.relatorioFundo(); Console.WriteLine("Toque uma tecla para voltar ao menu principal:"); Console.ReadKey(); Console.Clear(); } else if (codFundo == 2) { fundo_dolar2.relatorioFundo(); Console.WriteLine("Toque uma tecla para voltar ao menu principal:"); Console.ReadKey(); Console.Clear(); } else if (codFundo == 3) { fundo_real1.relatorioFundo(); Console.WriteLine("Toque uma tecla para voltar ao menu principal:"); Console.ReadKey(); Console.Clear(); } else if (codFundo == 4) { fundo_real2.relatorioFundo(); Console.WriteLine("Toque uma tecla para voltar ao menu principal:"); Console.ReadKey(); Console.Clear(); } } else if (opcao == 6) { Console.WriteLine("Fundos De Investimentos Disponiveis"); Console.WriteLine("1-{0}", fundo_dolar1.getInfFundo()); Console.WriteLine("2-{0}", fundo_dolar2.getInfFundo()); Console.WriteLine("3-{0}", fundo_real1.getInfFundo()); Console.WriteLine("4-{0}", fundo_real2.getInfFundo()); int codFundoOrigem = 0; int codDestino = 0; int codCliente = 0; double valor = 0; Console.WriteLine("Informe o Codigo do fundo que deseja transferir"); codFundoOrigem = int.Parse(Console.ReadLine()); gerenciador.listarClientes(); Console.WriteLine("Informe o codigo do cliente que deseja realizar a transferencia"); codCliente = int.Parse(Console.ReadLine()); Console.WriteLine("Informe o valor da aplicacao que deseja transferir"); valor = double.Parse(Console.ReadLine()); if(codFundoOrigem == 1) { Console.WriteLine("Fundos De Investimentos Disponiveis Para Troca"); Console.WriteLine("2-{0}", fundo_dolar2.getInfFundo()); Console.WriteLine("Informe o Codigo do fundo que recebera a aplicacao"); codDestino = int.Parse(Console.ReadLine()); if (codDestino == 2) { fundo_dolar1.TrocarFundo(codCliente,valor,fundo_dolar2,'D'); } } else if(codFundoOrigem == 2) { Console.WriteLine("Fundos De Investimentos Disponiveis Para Troca"); Console.WriteLine("1-{0}", fundo_dolar1.getInfFundo()); Console.WriteLine("Informe o Codigo do fundo que recebera a aplicacao"); codDestino = int.Parse(Console.ReadLine()); if (codDestino == 1) { fundo_dolar2.TrocarFundo(codCliente, valor, fundo_dolar1,'D'); } } else if(codFundoOrigem == 3) { Console.WriteLine("Fundos De Investimentos Disponiveis Para Troca"); Console.WriteLine("4-{0}", fundo_real2.getInfFundo()); Console.WriteLine("Informe o Codigo do fundo que recebera a aplicacao"); codDestino = int.Parse(Console.ReadLine()); if (codDestino == 4) { fundo_real1.TrocarFundo(codCliente, valor, fundo_real2,'R'); } } else if(codFundoOrigem == 4) { Console.WriteLine("Fundos De Investimentos Disponiveis Para Troca"); Console.WriteLine("3-{0}", fundo_real1.getInfFundo()); Console.WriteLine("Informe o Codigo do fundo que recebera a aplicacao"); codDestino = int.Parse(Console.ReadLine()); if (codDestino == 3) { fundo_real2.TrocarFundo(codCliente, valor, fundo_real1,'R'); } } Console.WriteLine("Troca Efetuada"); Console.WriteLine("Toque uma tecla para voltar ao menu principal:"); Console.ReadKey(); Console.Clear(); } else if(opcao == 7) { Console.WriteLine("Fundos De Investimentos Disponiveis"); Console.WriteLine("1-{0}", fundo_dolar1.getInfFundo()); Console.WriteLine("2-{0}", fundo_dolar2.getInfFundo()); Console.WriteLine("3-{0}", fundo_real1.getInfFundo()); Console.WriteLine("4-{0}", fundo_real2.getInfFundo()); int codFundo = 0; int codCliente = 0; double valor = 0; Console.WriteLine("Informe o Codigo do Fundo Que Deseja Sacar"); codFundo = int.Parse(Console.ReadLine()); gerenciador.listarClientes(); Console.WriteLine("Informe o codigo do cliente que deseja realizar o saque"); codCliente = int.Parse(Console.ReadLine()); Console.WriteLine("Informe o valor da aplicacao que deseja sacar"); valor = double.Parse(Console.ReadLine()); if(codFundo == 1) { fundo_dolar1.resgate(valor,codCliente,gerenciador); } else if(codFundo == 2) { fundo_dolar2.resgate(valor, codCliente, gerenciador); } else if(codFundo == 3) { fundo_real1.resgate(valor, codCliente, gerenciador); } else if(codFundo == 4) { fundo_real2.resgate(valor, codCliente, gerenciador); } Console.WriteLine("Toque uma tecla para voltar ao menu principal:"); Console.ReadKey(); Console.Clear(); } Console.WriteLine("*==============Vai Fundos===================*"); Console.WriteLine("*-------------------------------------------*"); Console.WriteLine("*1------Cadastro Cliente--------------------*"); Console.WriteLine("*2------Fazer Aplicacao---------------------*"); Console.WriteLine("*3------Listar Clientes---------------------*"); Console.WriteLine("*4------Relatorio Do Cliente----------------*"); Console.WriteLine("*5------Relatorio Do Fundo------------------*"); Console.WriteLine("*6------Transferir Aplicacao De Fundo-------*"); Console.WriteLine("*7------Resgatar Aplicacao------------------*"); Console.WriteLine("*8------Sair Do Sistema --------------------*"); Console.WriteLine("*===========================================*"); Console.WriteLine("Informe a opcao Desejada:"); opcao = int.Parse(Console.ReadLine()); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Julas.Utils; using Julas.Utils.Collections; using Julas.Utils.Extensions; using TheArtOfDev.HtmlRenderer.WinForms; using Ozeki.VoIP; using VoipClient; namespace Client { public partial class ConversationForm : Form { private volatile bool _isInCall = false; private readonly string _thisUserId; private readonly string _otherUserId; private readonly HtmlPanel _htmlPanel; private readonly Color _textColor = Color.Black; private readonly Color _timestampColor = Color.DarkGray; private readonly Color _thisUserColor = Color.DodgerBlue; private readonly Color _otherUserColor = Color.DarkOrange; private readonly Color _enabledBtnColor = Color.FromArgb(255, 255, 255); private readonly Color _disabledBtnColor = Color.FromArgb(226, 226, 226); private readonly int _fontSize = 1; private readonly VoipClientModule _voipClient; public event Action<string> MessageSent; public event Action Call; public event Action HangUp; public ConversationForm(string thisUserId, string otherUserId, string hash_pass, VoipClientModule voipClient) { _thisUserId = thisUserId; _otherUserId = otherUserId; _voipClient = voipClient; InitializeComponent(); this.Text = $"Conversation with {otherUserId}"; _htmlPanel = new HtmlPanel(); panel1.Controls.Add(_htmlPanel); _htmlPanel.Dock = DockStyle.Fill; _voipClient.PhoneStateChanged += VoipClientOnPhoneStateChanged; } public new void Dispose() { _voipClient.PhoneStateChanged -= VoipClientOnPhoneStateChanged; base.Dispose(true); } private void VoipClientOnPhoneStateChanged(PhoneState phoneState) { Invoke(() => { if (!phoneState.OtherUserId.IsOneOf(null, _otherUserId) || phoneState.Status.IsOneOf(PhoneStatus.Registering)) { btnCall.Enabled = false; btnHangUp.Enabled = false; btnCall.BackColor = _disabledBtnColor; btnHangUp.BackColor = _disabledBtnColor; return; } else { switch (phoneState.Status) { case PhoneStatus.Calling: { btnCall.Enabled = false; btnHangUp.Enabled = true; btnCall.BackColor = _disabledBtnColor; btnHangUp.BackColor = _enabledBtnColor; break; } case PhoneStatus.InCall: { btnCall.Enabled = false; btnHangUp.Enabled = true; btnCall.BackColor = _disabledBtnColor; btnHangUp.BackColor = _enabledBtnColor; break; } case PhoneStatus.IncomingCall: { btnCall.Enabled = true; btnHangUp.Enabled = true; btnCall.BackColor = _enabledBtnColor; btnHangUp.BackColor = _enabledBtnColor; break; } case PhoneStatus.Registered: { btnCall.Enabled = true; btnHangUp.Enabled = false; btnCall.BackColor = _enabledBtnColor; btnHangUp.BackColor = _disabledBtnColor; break; } } } }); } public void AppendMessageFromOtherUser(string message) { AppendMessage(message, _otherUserId, _otherUserColor); } private void AppendMessageFromThisUser(string message) { AppendMessage(message, _thisUserId, _thisUserColor); } private void AppendMessage(string msg, string from, Color nameColor) { StringBuilder sb = new StringBuilder(); sb.Append("<p>"); sb.Append($"<b><font color=\"{GetHexColor(nameColor)}\" size=\"{_fontSize}\">{from}</font></b> "); sb.Append($"<font color=\"{GetHexColor(_timestampColor)}\" size=\"{_fontSize}\">{DateTime.Now.ToString("HH:mm:ss")}</font>"); sb.Append("<br/>"); sb.Append($"<font color=\"{GetHexColor(_textColor)}\" size=\"{_fontSize}\">{msg}</font>"); sb.Append("</p>"); _htmlPanel.Text += sb.ToString(); _htmlPanel.VerticalScroll.Value = _htmlPanel.VerticalScroll.Maximum; } private string GetHexColor(Color color) { return $"#{color.R.ToString("x2").ToUpper()}{color.G.ToString("x2").ToUpper()}{color.B.ToString("x2").ToUpper()}"; } private void SendMessage() { if (!tbInput.Text.IsNullOrWhitespace()) { MessageSent?.Invoke(tbInput.Text.Trim()); AppendMessageFromThisUser(tbInput.Text.Trim()); tbInput.Text = ""; tbInput.SelectionStart = 0; } } private void tbInput_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == '\r' || e.KeyChar == '\n') { e.Handled = true; SendMessage(); } } private void btnSend_Click(object sender, EventArgs e) { SendMessage(); } private void ConversationForm_Load(object sender, EventArgs e) { VoipClientOnPhoneStateChanged(_voipClient.PhoneState); } private void Invoke(Action action) { if(this.InvokeRequired) { this.Invoke(new MethodInvoker(action)); } else { action(); } } private void btnCall_Click(object sender, EventArgs e) { btnCall.Enabled = false; btnHangUp.Enabled = false; btnCall.BackColor = _disabledBtnColor; btnHangUp.BackColor = _disabledBtnColor; switch (_voipClient.PhoneState.Status) { case PhoneStatus.IncomingCall: { _voipClient.AnswerCall(); break; } case PhoneStatus.Registered: { _voipClient.StartCall(_otherUserId); break; } } } private void btnHangUp_Click(object sender, EventArgs e) { btnCall.Enabled = false; btnHangUp.Enabled = false; btnCall.BackColor = _disabledBtnColor; btnHangUp.BackColor = _disabledBtnColor; switch (_voipClient.PhoneState.Status) { case PhoneStatus.IncomingCall: { _voipClient.RejectCall(); break; } case PhoneStatus.InCall: { _voipClient.EndCall(); break; } case PhoneStatus.Calling: { _voipClient.EndCall(); break; } } } } }
/* * Copyright 2016 Christoph Brill <egore911@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using libldt3.attributes; using libldt3.model.enums; using libldt3.model.regel; using libldt3.model.regel.kontext; using libldt3.model.saetze; using NodaTime; namespace libldt3 { /** * Simple, reflection and annotation based reader for LDT 3.0. * * @author Christoph Brill &lt;egore911@gmail.com&gt; */ public class LdtReader { readonly IDictionary<Type, Regel> regelCache = new Dictionary<Type, Regel>(); readonly LdtConstants.Mode mode; public LdtReader(LdtConstants.Mode mode) { this.mode = mode; } /** * Read the LDT found on a given path. * * @param path * the path of the LDT file (any format handled by NIO * {@link Path}) * @return the list of Satz elements found in the LDT file * @throws IOException * thrown if reading the file failed */ public IList<Satz> Read(string path) { using (var f = File.Open(path, FileMode.Open)) { return Read(f); } } /** * Read the LDT found on a given path. * * @param path * the path of the LDT file * @return the list of Satz elements found in the LDT file * @throws IOException * thrown if reading the file failed */ public IList<Satz> Read(FileStream path) { var stream = new StreamReader(path, Encoding.GetEncoding("ISO-8859-1")); return Read(stream); } /** * Read the LDT from a given string stream. * * @param stream * the LDT lines as string stream * @return the list of Satz elements found in the LDT file */ public IList<Satz> Read(StreamReader stream) { Stack<object> stack = new Stack<object>(); IList<Satz> data = new List<Satz>(); string line; int integer = 0; while ((line = stream.ReadLine()) != null) { HandleInput(line, stack, data, integer++); } return data; } void HandleInput(string line, Stack<object> stack, IList<Satz> data, int lineNo) { Trace.TraceInformation("Reading line {0}", line); // Check if the line meets the minimum requirements (3 digits for // length, 4 digits for the identifier) if (line.Length < 7) { if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException("Line '" + line + "' (" + lineNo + ") was less than 7 characters, aborting"); } else { Trace.TraceInformation("Line '{0}' ({1}) was less than 7 characters, continuing anyway", line, lineNo); } } // Read the length and check whether it had the correct length int length = int.Parse(line.Substring(0, 3)); if (length != line.Length + 2) { if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException( "Line '" + line + "' (" + lineNo + ") should have length " + (line.Length + 2) + ", but was " + length); } else { Trace.TraceInformation("Line '{0}' ({1}) should have length {2}, but was {3}. Ignoring specified length", line, lineNo, (line.Length + 2), length); length = line.Length + 2; } } // Read identifier and payload string identifier = line.Substring(3, 7 - 3); string payload = line.Substring(7, length - 2 - 7); switch (identifier) { case "8000": { // Start: Satz AssureLength(line, length, 13); if (stack.Count > 0) { if (mode == LdtConstants.Mode.STRICT) { throw new InvalidOperationException( "Stack must be empty when starting a new Satz, but was " + stack.Count + " long"); } else { Trace.TraceInformation("Stack must be empty when starting a new Satz, but was {0}. Clearing and continuing", stack); stack.Clear(); } } // Extract Satzart from payload and create Satz matching it Satzart satzart = GetSatzart(payload); switch (satzart) { case Satzart.Befund: stack.Push(new Befund()); break; case Satzart.Auftrag: stack.Push(new Auftrag()); break; case Satzart.LaborDatenpaketHeader: stack.Push(new LaborDatenpaketHeader()); break; case Satzart.LaborDatenpaketAbschluss: stack.Push(new LaborDatenpaketAbschluss()); break; case Satzart.PraxisDatenpaketHeader: stack.Push(new PraxisDatenpaketHeader()); break; case Satzart.PraxisDatenpaketAbschluss: stack.Push(new PraxisDatenpaketAbschluss()); break; default: throw new ArgumentException("Unsupported Satzart '" + payload + "' found"); } break; } case "8001": { // End: Satz AssureLength(line, length, 13); object o = stack.Pop(); Datenpaket datenpaket = o.GetType().GetCustomAttribute<Datenpaket>(); if (datenpaket != null) { EvaluateContextRules(o, datenpaket.Kontextregeln); } if (stack.Count == 0) { data.Add((Satz)o); } break; } case "8002": { // Start: Objekt AssureLength(line, length, 17); object currentObject1 = PeekCurrentObject(stack); Objekt annotation1 = currentObject1.GetType().GetCustomAttribute<Objekt>(); if (annotation1 != null) { if (annotation1.Value.Length == 0) { // If annotation is empty, the parent object would actually // be the one to deal with } else { // Match found, everything is fine if (payload.Equals("Obj_" + annotation1.Value)) { break; } // No match found, abort or inform the developer if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException( "In line '" + line + "' (" + lineNo + ") expected Obj_" + annotation1.Value + ", got " + payload); } else { Trace.TraceError("In line {0} ({1}) expected Obj_{2}, got {3}", line, lineNo, annotation1.Value, payload); break; } } } if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException("Line '" + line + "' (" + lineNo + ") started an unexpeted object, stack was " + stack.ToArray()); } else { Trace.TraceWarning("Line '{0}' ({1}) started an unexpeted object, stack was {2}", line, lineNo, stack); } break; } case "8003": { // End: Objekt AssureLength(line, length, 17); object o; Objekt annotation1; do { o = stack.Pop(); annotation1 = o.GetType().GetCustomAttribute<Objekt>(); if (annotation1 != null) { if (annotation1.Value.Length != 0 && !("Obj_" + annotation1.Value).Equals(payload)) { Trace.TraceWarning("Line: {0} ({1}), annotation {2}, payload {3}", line, lineNo, annotation1.Value, payload); } EvaluateContextRules(o, annotation1.Kontextregeln); } } while (annotation1 != null && annotation1.Value.Length == 0); if (stack.Count == 0) { data.Add((Satz)o); } break; } default: // Any line not starting or completing a Satz or Objekt object currentObject = PeekCurrentObject(stack); if (currentObject == null) { throw new InvalidOperationException("No object when appplying line " + line + " (" + lineNo + ")"); } // XXX iterating the fields could be replaced by a map to be a bit // faster when dealing with the same class foreach (FieldInfo info in currentObject.GetType().GetFields()) { // Check if we found a Feld annotation, if not this is not our // field Feld annotation2 = info.GetCustomAttribute<Feld>(); if (annotation2 == null) { continue; } // Check if the annotation matches the identifier, if not, this // is not our field if (!identifier.Equals(annotation2.Value)) { continue; } try { // Check if there is currently a value set object o = info.GetValue(currentObject); if (o != null && GetGenericList(info.FieldType) == null) { if (mode == LdtConstants.Mode.STRICT) { throw new InvalidOperationException( "Line '" + line + "' (" + lineNo + ") would overwrite existing value " + o + " of " + currentObject + "." + info.Name); } else { Trace.TraceWarning("Line '{0}' ({1}) would overwrite existing value {2} in object {3}.{4}", line, lineNo, o, currentObject, info); } } ValidateFieldPayload(info, payload); // Convert the value to its target type ... object value = ConvertType(info, info.FieldType, payload, stack); // .. and set the value on the target object info.SetValue(currentObject, value); } catch (Exception e) { if (mode == LdtConstants.Mode.STRICT) { throw new InvalidOperationException(e.Message, e); } else { Trace.TraceError(e.Message); } } // We are done with this line return; } // No field with a matching Feld annotation found, check if we are // an Objekt with an empty value (anonymous object), if so try our // parent Objekt annotation = currentObject.GetType().GetCustomAttribute<Objekt>(); if (annotation != null && annotation.Value.Length == 0) { stack.Pop(); HandleInput(line, stack, data, lineNo); return; } // Neither we nor our parent could deal with this line if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException("Failed reading line " + line + " (" + lineNo + "), current stack: " + string.Join(" ", stack.ToArray())); } else { Trace.TraceWarning("Failed reading line {0} ({1}), current stack: {2}, skipping line", line, lineNo, string.Join(" ", stack.ToArray())); } break; } } private void EvaluateContextRules(object o, Type[] kontextRegeln) { foreach (Type kontextregel in kontextRegeln) { try { if (!((Kontextregel)Activator.CreateInstance(kontextregel)).IsValid(o)) { if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException("Context rule " + kontextregel.Name + " failed on object " + o); } else { Trace.TraceWarning("Context rule {} failed on object {}", kontextregel.Name, o); } } } catch (Exception e) { if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException("Context rule " + kontextregel.Name + " failed on object " + o, e); } else { Trace.TraceWarning("Context rule {} failed on object {}", kontextregel.Name, o, e); } } } } void ValidateFieldPayload(FieldInfo field, string payload) { foreach (Regelsatz regelsatz in field.GetCustomAttributes<Regelsatz>()) { if (regelsatz.Laenge >= 0) { if (payload.Length != regelsatz.Laenge) { ValidationFailed(field.DeclaringType.Name + "." + field.Name + ": Value " + payload + " did not match expected length " + regelsatz.Laenge + ", was " + payload.Length); } } if (regelsatz.MinLaenge >= 0) { if (payload.Length < regelsatz.MinLaenge) { ValidationFailed(field.DeclaringType.Name + "." + field.Name + ": Value " + payload + " did not match expected minimum length " + regelsatz.MinLaenge + ", was " + payload.Length); } } if (regelsatz.MaxLaenge >= 0) { if (payload.Length > regelsatz.MaxLaenge) { ValidationFailed(field.DeclaringType.Name + "." + field.Name + ": Value " + payload + " did not match expected maximum length " + regelsatz.MaxLaenge + ", was " + payload.Length); } } // No specific rules given, likely only length checks if (regelsatz.Value.Length == 0) { continue; } bool found = false; foreach (Type regel in regelsatz.Value) { if (GetRegel(regel).IsValid(payload)) { found = true; break; } } if (!found) { ValidationFailed(field.DeclaringType.Name + "." + field.Name + ": Value " + payload + " did not confirm to any rule of " + ToString(regelsatz.Value)); } } } void ValidationFailed(string message) { if (mode == LdtConstants.Mode.STRICT) { throw new InvalidOperationException(message); } else { Trace.TraceWarning(message); } } string ToString(Type[] regeln) { StringBuilder buffer = new StringBuilder(); foreach (Type regel in regeln) { if (buffer.Length > 0) { buffer.Append(" or "); } buffer.Append(regel.Name); } return buffer.ToString(); } Regel GetRegel(Type regel) { Regel instance; regelCache.TryGetValue(regel, out instance); if (instance == null) { instance = (Regel)Activator.CreateInstance(regel); regelCache[regel] = instance; } return instance; } /** * Extract the Satzart form a given payload * * @param payload * the payload of the line * @return the Satzart or {@code null} */ Satzart GetSatzart(string payload) { foreach (Satzart sa in Enum.GetValues(typeof(Satzart)).Cast<Satzart>()) { if (sa.GetCode().Equals(payload)) { return sa; } } throw new ArgumentException("Unsupported Satzart '" + payload + "' found"); } /** * Peek the current objekt from the stack, if any. * * @param stack * the stack to peek the object from * @return the current top level element of the stack or {@code null} */ static object PeekCurrentObject(Stack<object> stack) { if (stack.Count == 0) { return null; } return stack.Peek(); } /** * Check if the line matches the expected length. * * @param line * the line to check * @param length * the actual length * @param target * the length specified by the line */ void AssureLength(string line, int length, int target) { if (length != target) { if (mode == LdtConstants.Mode.STRICT) { throw new ArgumentException( "Line '" + line + "' must have length " + target + ", was " + length); } else { Trace.TraceInformation("Line '{0}' must have length {1}, was {2}", line, target, length); } } } /** * Convert the string payload into a target class. (Note: There are * certainly better options out there but this one is simple enough for our * needs.) */ static object ConvertType(FieldInfo field, Type type, string payload, Stack<object> stack) { if (type == typeof(string)) { return payload; } if (type == typeof(float) || type == typeof(float?)) { return float.Parse(payload); } if (type == typeof(int) || type == typeof(int?)) { return int.Parse(payload); } if (type == typeof(long) || type == typeof(long?)) { return long.Parse(payload); } if (type == typeof(bool) || type == typeof(bool?)) { return "1".Equals(payload); } if (type == typeof(LocalDate?)) { return LdtConstants.FORMAT_DATE.Parse(payload).Value; } if (type == typeof(LocalTime?)) { return LdtConstants.FORMAT_TIME.Parse(payload).Value; } if (IsNullableEnum(type)) { Type enumType = Nullable.GetUnderlyingType(type); MethodInfo method = Type.GetType(enumType.FullName + "Extensions").GetMethod("GetCode"); if (method != null) { foreach (object e in Enum.GetValues(enumType)) { string code = (string)method.Invoke(e, new object[] { e }); if (payload.Equals(code)) { return e; } } return null; } } if (type.IsEnum) { MethodInfo method = Type.GetType(type.FullName + "Extensions").GetMethod("GetCode"); if (method != null) { foreach (object e in Enum.GetValues(type)) { string code = (string)method.Invoke(e, new object[] { e }); if (payload.Equals(code)) { return e; } } return null; } } Type genericType = GetGenericList(type); if (genericType != null) { object currentObject = PeekCurrentObject(stack); var o = (System.Collections.IList) field.GetValue(currentObject); if (o == null) { o = (System.Collections.IList) Activator.CreateInstance(typeof(List<>).MakeGenericType(genericType.GetGenericArguments()[0])); field.SetValue(currentObject, o); } o.Add(ConvertType(field, type.GenericTypeArguments[0], payload, stack)); return o; } if (type.GetCustomAttribute<Objekt>() != null) { object instance = Activator.CreateInstance(type); stack.Push(instance); FieldInfo declaredField = type.GetField("Value"); if (declaredField != null) { declaredField.SetValue(instance, ConvertType(declaredField, declaredField.FieldType, payload, stack)); } return instance; } throw new ArgumentException("Don't know how to handle type " + type); } static bool IsNullableEnum(Type t) { Type u = Nullable.GetUnderlyingType(t); return (u != null) && u.IsEnum; } static Type GetGenericList(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>)) { return type; } foreach (Type interfaceType in type.GetInterfaces()) { if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IList<>)) { return interfaceType; } } return null; } } }
using System; using System.Text; namespace ExifLibrary { /// <summary> /// Represents an enumerated value. /// </summary> public class ExifEnumProperty<T> : ExifProperty { protected T mValue; protected bool mIsBitField; protected override object _Value { get { return Value; } set { Value = (T)value; } } public new T Value { get { return mValue; } set { mValue = value; } } public bool IsBitField { get { return mIsBitField; } } static public implicit operator T(ExifEnumProperty<T> obj) { return (T)obj.mValue; } public override string ToString() { return mValue.ToString(); } public ExifEnumProperty(ExifTag tag, T value, bool isbitfield) : base(tag) { mValue = value; mIsBitField = isbitfield; } public ExifEnumProperty(ExifTag tag, T value) : this(tag, value, false) { ; } public override ExifInterOperability Interoperability { get { ushort tagid = ExifTagFactory.GetTagID(mTag); Type type = typeof(T); Type basetype = Enum.GetUnderlyingType(type); if (type == typeof(FileSource) || type == typeof(SceneType)) { // UNDEFINED return new ExifInterOperability(tagid, 7, 1, new byte[] { (byte)((object)mValue) }); } else if (type == typeof(GPSLatitudeRef) || type == typeof(GPSLongitudeRef) || type == typeof(GPSStatus) || type == typeof(GPSMeasureMode) || type == typeof(GPSSpeedRef) || type == typeof(GPSDirectionRef) || type == typeof(GPSDistanceRef)) { // ASCII return new ExifInterOperability(tagid, 2, 2, new byte[] { (byte)((object)mValue), 0 }); } else if (basetype == typeof(byte)) { // BYTE return new ExifInterOperability(tagid, 1, 1, new byte[] { (byte)((object)mValue) }); } else if (basetype == typeof(ushort)) { // SHORT return new ExifInterOperability(tagid, 3, 1, ExifBitConverter.GetBytes((ushort)((object)mValue), BitConverterEx.SystemByteOrder, BitConverterEx.SystemByteOrder)); } else throw new UnknownEnumTypeException(); } } } /// <summary> /// Represents an ASCII string. (EXIF Specification: UNDEFINED) Used for the UserComment field. /// </summary> public class ExifEncodedString : ExifProperty { protected string mValue; private Encoding mEncoding; protected override object _Value { get { return Value; } set { Value = (string)value; } } public new string Value { get { return mValue; } set { mValue = value; } } public Encoding Encoding { get { return mEncoding; } set { mEncoding = value; } } static public implicit operator string(ExifEncodedString obj) { return obj.mValue; } public override string ToString() { return mValue; } public ExifEncodedString(ExifTag tag, string value, Encoding encoding) : base(tag) { mValue = value; mEncoding = encoding; } public override ExifInterOperability Interoperability { get { string enc = ""; if (mEncoding == null) enc = "\0\0\0\0\0\0\0\0"; else if (mEncoding.EncodingName == "US-ASCII") enc = "ASCII\0\0\0"; else if (mEncoding.EncodingName == "Japanese (JIS 0208-1990 and 0212-1990)") enc = "JIS\0\0\0\0\0"; else if (mEncoding.EncodingName == "Unicode") enc = "Unicode\0"; else enc = "\0\0\0\0\0\0\0\0"; byte[] benc = Encoding.ASCII.GetBytes(enc); byte[] bstr = (mEncoding == null ? Encoding.ASCII.GetBytes(mValue) : mEncoding.GetBytes(mValue)); byte[] data = new byte[benc.Length + bstr.Length]; Array.Copy(benc, 0, data, 0, benc.Length); Array.Copy(bstr, 0, data, benc.Length, bstr.Length); return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 7, (uint)data.Length, data); } } } /// <summary> /// Represents an ASCII string formatted as DateTime. (EXIF Specification: ASCII) Used for the date time fields. /// </summary> public class ExifDateTime : ExifProperty { protected DateTime mValue; protected override object _Value { get { return Value; } set { Value = (DateTime)value; } } public new DateTime Value { get { return mValue; } set { mValue = value; } } static public implicit operator DateTime(ExifDateTime obj) { return obj.mValue; } public override string ToString() { return mValue.ToString("yyyy.MM.dd HH:mm:ss"); } public ExifDateTime(ExifTag tag, DateTime value) : base(tag) { mValue = value; } public override ExifInterOperability Interoperability { get { return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 2, (uint)20, ExifBitConverter.GetBytes(mValue, true)); } } } /// <summary> /// Represents the exif version as a 4 byte ASCII string. (EXIF Specification: UNDEFINED) /// Used for the ExifVersion, FlashpixVersion, InteroperabilityVersion and GPSVersionID fields. /// </summary> public class ExifVersion : ExifProperty { protected string mValue; protected override object _Value { get { return Value; } set { Value = (string)value; } } public new string Value { get { return mValue; } set { mValue = value.Substring(0, 4); } } public ExifVersion(ExifTag tag, string value) : base(tag) { if (value.Length > 4) mValue = value.Substring(0, 4); else if (value.Length < 4) mValue = value + new string(' ', 4 - value.Length); else mValue = value; } public override string ToString() { return mValue; } public override ExifInterOperability Interoperability { get { if (mTag == ExifTag.ExifVersion || mTag == ExifTag.FlashpixVersion || mTag == ExifTag.InteroperabilityVersion) return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 7, 4, Encoding.ASCII.GetBytes(mValue)); else { byte[] data = new byte[4]; for (int i = 0; i < 4; i++) data[i] = byte.Parse(mValue[0].ToString()); return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 7, 4, data); } } } } /// <summary> /// Represents the location and area of the subject (EXIF Specification: 2xSHORT) /// The coordinate values, width, and height are expressed in relation to the /// upper left as origin, prior to rotation processing as per the Rotation tag. /// </summary> public class ExifPointSubjectArea : ExifUShortArray { protected new ushort[] Value { get { return mValue; } set { mValue = value; } } public ushort X { get { return mValue[0]; } set { mValue[0] = value; } } public ushort Y { get { return mValue[1]; } set { mValue[1] = value; } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("({0:d}, {1:d})", mValue[0], mValue[1]); return sb.ToString(); } public ExifPointSubjectArea(ExifTag tag, ushort[] value) : base(tag, value) { ; } public ExifPointSubjectArea(ExifTag tag, ushort x, ushort y) : base(tag, new ushort[] { x, y }) { ; } } /// <summary> /// Represents the location and area of the subject (EXIF Specification: 3xSHORT) /// The coordinate values, width, and height are expressed in relation to the /// upper left as origin, prior to rotation processing as per the Rotation tag. /// </summary> public class ExifCircularSubjectArea : ExifPointSubjectArea { public ushort Diamater { get { return mValue[2]; } set { mValue[2] = value; } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("({0:d}, {1:d}) {2:d}", mValue[0], mValue[1], mValue[2]); return sb.ToString(); } public ExifCircularSubjectArea(ExifTag tag, ushort[] value) : base(tag, value) { ; } public ExifCircularSubjectArea(ExifTag tag, ushort x, ushort y, ushort d) : base(tag, new ushort[] { x, y, d }) { ; } } /// <summary> /// Represents the location and area of the subject (EXIF Specification: 4xSHORT) /// The coordinate values, width, and height are expressed in relation to the /// upper left as origin, prior to rotation processing as per the Rotation tag. /// </summary> public class ExifRectangularSubjectArea : ExifPointSubjectArea { public ushort Width { get { return mValue[2]; } set { mValue[2] = value; } } public ushort Height { get { return mValue[3]; } set { mValue[3] = value; } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendFormat("({0:d}, {1:d}) ({2:d} x {3:d})", mValue[0], mValue[1], mValue[2], mValue[3]); return sb.ToString(); } public ExifRectangularSubjectArea(ExifTag tag, ushort[] value) : base(tag, value) { ; } public ExifRectangularSubjectArea(ExifTag tag, ushort x, ushort y, ushort w, ushort h) : base(tag, new ushort[] { x, y, w, h }) { ; } } /// <summary> /// Represents GPS latitudes and longitudes (EXIF Specification: 3xRATIONAL) /// </summary> public class GPSLatitudeLongitude : ExifURationalArray { protected new MathEx.UFraction32[] Value { get { return mValue; } set { mValue = value; } } public MathEx.UFraction32 Degrees { get { return mValue[0]; } set { mValue[0] = value; } } public MathEx.UFraction32 Minutes { get { return mValue[1]; } set { mValue[1] = value; } } public MathEx.UFraction32 Seconds { get { return mValue[2]; } set { mValue[2] = value; } } public static explicit operator float(GPSLatitudeLongitude obj) { return obj.ToFloat(); } public float ToFloat() { return (float)Degrees + ((float)Minutes) / 60.0f + ((float)Seconds) / 3600.0f; } public override string ToString() { return string.Format("{0:F2}°{1:F2}'{2:F2}\"", (float)Degrees, (float)Minutes, (float)Seconds); } public GPSLatitudeLongitude(ExifTag tag, MathEx.UFraction32[] value) : base(tag, value) { ; } public GPSLatitudeLongitude(ExifTag tag, float d, float m, float s) : base(tag, new MathEx.UFraction32[] { new MathEx.UFraction32(d), new MathEx.UFraction32(m), new MathEx.UFraction32(s) }) { ; } } /// <summary> /// Represents a GPS time stamp as UTC (EXIF Specification: 3xRATIONAL) /// </summary> public class GPSTimeStamp : ExifURationalArray { protected new MathEx.UFraction32[] Value { get { return mValue; } set { mValue = value; } } public MathEx.UFraction32 Hour { get { return mValue[0]; } set { mValue[0] = value; } } public MathEx.UFraction32 Minute { get { return mValue[1]; } set { mValue[1] = value; } } public MathEx.UFraction32 Second { get { return mValue[2]; } set { mValue[2] = value; } } public override string ToString() { return string.Format("{0:F2}:{1:F2}:{2:F2}\"", (float)Hour, (float)Minute, (float)Second); } public GPSTimeStamp(ExifTag tag, MathEx.UFraction32[] value) : base(tag, value) { ; } public GPSTimeStamp(ExifTag tag, float h, float m, float s) : base(tag, new MathEx.UFraction32[] { new MathEx.UFraction32(h), new MathEx.UFraction32(m), new MathEx.UFraction32(s) }) { ; } } /// <summary> /// Represents an ASCII string. (EXIF Specification: BYTE) /// Used by Windows XP. /// </summary> public class WindowsByteString : ExifProperty { protected string mValue; protected override object _Value { get { return Value; } set { Value = (string)value; } } public new string Value { get { return mValue; } set { mValue = value; } } static public implicit operator string(WindowsByteString obj) { return obj.mValue; } public override string ToString() { return mValue; } public WindowsByteString(ExifTag tag, string value) : base(tag) { mValue = value; } public override ExifInterOperability Interoperability { get { byte[] data = Encoding.Unicode.GetBytes(mValue); return new ExifInterOperability(ExifTagFactory.GetTagID(mTag), 1, (uint)data.Length, data); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Transport.Channels.Sockets { using System; using System.Diagnostics.Contracts; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; public class DefaultDatagramChannelConfig : DefaultChannelConfiguration, IDatagramChannelConfig { const int DefaultFixedBufferSize = 2048; readonly Socket socket; public DefaultDatagramChannelConfig(IDatagramChannel channel, Socket socket) : base(channel, new FixedRecvByteBufAllocator(DefaultFixedBufferSize)) { Contract.Requires(socket != null); this.socket = socket; } public override T GetOption<T>(ChannelOption<T> option) { if (ChannelOption.SoBroadcast.Equals(option)) { return (T)(object)this.Broadcast; } if (ChannelOption.SoRcvbuf.Equals(option)) { return (T)(object)this.ReceiveBufferSize; } if (ChannelOption.SoSndbuf.Equals(option)) { return (T)(object)this.SendBufferSize; } if (ChannelOption.SoReuseaddr.Equals(option)) { return (T)(object)this.ReuseAddress; } if (ChannelOption.IpMulticastLoopDisabled.Equals(option)) { return (T)(object)this.LoopbackModeDisabled; } if (ChannelOption.IpMulticastTtl.Equals(option)) { return (T)(object)this.TimeToLive; } if (ChannelOption.IpMulticastAddr.Equals(option)) { return (T)(object)this.Interface; } if (ChannelOption.IpMulticastIf.Equals(option)) { return (T)(object)this.NetworkInterface; } if (ChannelOption.IpTos.Equals(option)) { return (T)(object)this.TrafficClass; } return base.GetOption(option); } public override bool SetOption<T>(ChannelOption<T> option, T value) { if (base.SetOption(option, value)) { return true; } if (ChannelOption.SoBroadcast.Equals(option)) { this.Broadcast = (bool)(object)value; } else if (ChannelOption.SoRcvbuf.Equals(option)) { this.ReceiveBufferSize = (int)(object)value; } else if (ChannelOption.SoSndbuf.Equals(option)) { this.SendBufferSize = (int)(object)value; } else if (ChannelOption.SoReuseaddr.Equals(option)) { this.ReuseAddress = (bool)(object)value; } else if (ChannelOption.IpMulticastLoopDisabled.Equals(option)) { this.LoopbackModeDisabled = (bool)(object)value; } else if (ChannelOption.IpMulticastTtl.Equals(option)) { this.TimeToLive = (short)(object)value; } else if (ChannelOption.IpMulticastAddr.Equals(option)) { this.Interface = (EndPoint)(object)value; } else if (ChannelOption.IpMulticastIf.Equals(option)) { this.NetworkInterface = (NetworkInterface)(object)value; } else if (ChannelOption.IpTos.Equals(option)) { this.TrafficClass = (int)(object)value; } else { return false; } return true; } public int SendBufferSize { get { try { return this.socket.SendBufferSize; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SendBufferSize = value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public int ReceiveBufferSize { get { try { return this.socket.ReceiveBufferSize; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.ReceiveBufferSize = value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public int TrafficClass { get { try { return (int)this.socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.TypeOfService); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.TypeOfService, value); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public bool ReuseAddress { get { try { return (int)this.socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress) != 0; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, value ? 1 : 0); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public bool Broadcast { get { try { return this.socket.EnableBroadcast; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.EnableBroadcast = value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public bool LoopbackModeDisabled { get { try { return !this.socket.MulticastLoopback; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.MulticastLoopback = !value; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public short TimeToLive { get { try { return (short)this.socket.GetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastTimeToLive); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { try { this.socket.SetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastTimeToLive, value); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public EndPoint Interface { get { try { return this.socket.LocalEndPoint; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { Contract.Requires(value != null); try { this.socket.Bind(value); } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } public NetworkInterface NetworkInterface { get { try { NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); int value = (int)this.socket.GetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastInterface); int index = IPAddress.NetworkToHostOrder(value); if (interfaces.Length > 0 && index >= 0 && index < interfaces.Length) { return interfaces[index]; } return null; } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } set { Contract.Requires(value != null); try { int index = this.GetNetworkInterfaceIndex(value); if (index >= 0) { this.socket.SetSocketOption( this.AddressFamilyOptionLevel, SocketOptionName.MulticastInterface, index); } } catch (ObjectDisposedException ex) { throw new ChannelException(ex); } catch (SocketException ex) { throw new ChannelException(ex); } } } internal SocketOptionLevel AddressFamilyOptionLevel { get { if (this.socket.AddressFamily == AddressFamily.InterNetwork) { return SocketOptionLevel.IP; } if (this.socket.AddressFamily == AddressFamily.InterNetworkV6) { return SocketOptionLevel.IPv6; } throw new NotSupportedException($"Socket address family {this.socket.AddressFamily} not supported, expecting InterNetwork or InterNetworkV6"); } } internal int GetNetworkInterfaceIndex(NetworkInterface networkInterface) { Contract.Requires(networkInterface != null); NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); for (int index = 0; index < interfaces.Length; index++) { if (interfaces[index].Id == networkInterface.Id) { return index; } } return -1; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using Pfz.AnimationManagement; using Pfz.AnimationManagement.Abstract; using Pfz.AnimationManagement.Animations; using Pfz.AnimationManagement.Wpf; namespace WpfSample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private IAnimation[] _basicAnimations; private IAnimation[] _intermediaryAnimations; internal IAnimation _animation; private ReadOnlyCollection<BitmapFrame> _waitingCharacter; private ReadOnlyCollection<BitmapFrame> _movingForwardCharacter; public MainWindow() { InitializeComponent(); Pfz.AnimationManagement.Wpf.Initializer.Initialize(); tabItemBasic.RequestBringIntoView += (a, b) => _SetBasicAnimation(); tabItemIntermediary.RequestBringIntoView += (a, b) => _SetIntermediaryAnimation(); _basicAnimations = new IAnimation[] { // Range AnimationBuilder.Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)), // Accelerating Start AnimationBuilder. BeginAcceleratingStart(1). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). EndAcceleratingStart(), // Deaccelerating End AnimationBuilder. BeginDeacceleratingEnd(1, 3). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). EndDeacceleratingEnd(), // Multiple time multipliers AnimationBuilder. BeginProgressiveTimeMultipliers(0.1). Add(AnimationBuilder.Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value))). MultiplySpeed(1, 1). KeepSpeed(1). MultiplySpeed(0.1, 1). EndProgressiveTimeMultipliers(), // Color Range AnimationBuilder.Range(Colors.Black, Colors.Blue, 1, (value) => circle.Fill = new SolidColorBrush(value)), // Many Color Ranges AnimationBuilder. BeginRanges((value) => circle.Fill = new SolidColorBrush(value), Colors.Black). To(Colors.Blue, 1). To(Colors.Red, 1). To(Colors.Green, 1). To(Colors.Yellow, 1). To(Colors.Magenta, 1). To(Colors.Black, 1). EndRanges(), // Parallel Animation AnimationBuilder. BeginParallel(). BeginLoop(). BeginRanges((value) => circle.Fill = new SolidColorBrush(value), Colors.Black). To(Colors.Blue, 1). To(Colors.Red, 1). To(Colors.Green, 1). To(Colors.Yellow, 1). To(Colors.Magenta, 1). To(Colors.Black, 1). EndRanges(). EndLoop(). BeginLoop(). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). EndLoop(). EndParallel(), // Sequential Animation AnimationBuilder. BeginSequence(). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Black, Colors.Green, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(0, 450, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Green, Colors.Red, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Red, Colors.Blue, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Blue, Colors.Black, 1, (value) => circle.Fill = new SolidColorBrush(value)). EndSequence(), // Sequential Animation + Multiple Speeds AnimationBuilder. BeginProgressiveTimeMultipliers(). KeepSpeed(1). MultiplySpeed(2, 3). KeepSpeed(1). MultiplySpeed(0.5, 2). KeepSpeedUntilEnd(). BeginSequence(). Range(0, 450, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Black, Colors.Green, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(0, 450, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Green, Colors.Red, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetLeft(circle, value)). Range(Colors.Red, Colors.Blue, 1, (value) => circle.Fill = new SolidColorBrush(value)). Range(450, 0, 3, (value) => Canvas.SetTop(circle, value)). Range(Colors.Blue, Colors.Black, 1, (value) => circle.Fill = new SolidColorBrush(value)). EndSequence(). EndProgressiveTimeMultipliers(), // Imperative Animation new ImperativeAnimation(_ImperativeAnimation()), // Frame-by-Frame Animation new ImperativeAnimation(_FrameBasedAnimation()) }; AnimationManager.Add(new _ShowSelectedAnimation(this)); listboxBasicAnimation.SelectionChanged += listboxBasicAnimation_SelectionChanged; _SetBasicAnimation(); bool isGoing = true; _waitingCharacter = _LoadCharacter("Images\\Waiting.gif"); _movingForwardCharacter = _LoadCharacter("Images\\MoveForward.gif"); _intermediaryAnimations = new IAnimation[] { // Animate Character AnimationBuilder.RangeBySpeed(0, _waitingCharacter.Count-1, 10, (index) => imageCharacter.Source = _waitingCharacter[index]), // Move Character AnimationBuilder. BeginParallel(). BeginLoop(). RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). BeginLoop(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). EndLoop(). EndParallel(), // Move (Frame-by-Frame) new ImperativeAnimation(_MoveFrameByFrame(_movingForwardCharacter)), // Go and Return AnimationBuilder. BeginSequence(). Add(() => isGoing = true). BeginParallel(). BeginPrematureEndCondition(() => !isGoing). BeginLoop(). // we need to loop the animation or else it will do a single "full-step" and then will // only move forward without walking. But we need to end the animation sometime... we // can cound the steps (bad, as the animation does not end at an exact step) or we can // put a premature end over the entire loop (good). RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). EndPrematureEndCondition(). BeginSequence(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = false). EndSequence(). EndParallel(). BeginParallel(). BeginPrematureEndCondition(() => isGoing). BeginLoop(). RangeBySpeed(_movingForwardCharacter.Count-1, 0, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). EndPrematureEndCondition(). BeginSequence(). RangeBySpeed(400, 0, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = true). EndSequence(). EndParallel(). EndSequence(), // Go, Turn and Return AnimationBuilder. BeginSequence(). Add(() => isGoing = true). BeginParallel(). BeginPrematureEndCondition(() => !isGoing). BeginLoop(). // we need to loop the animation or else it will do a single "full-step" and then will // only move forward without walking. But we need to end the animation sometime... we // can cound the steps (bad, as the animation does not end at an exact step) or we can // put a premature end over the entire loop (good). RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). EndPrematureEndCondition(). BeginSequence(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = false). EndSequence(). EndParallel(). Range(1.0, -1.0, 1, (value) => imageCharacter.ScaleX = value). BeginParallel(). BeginPrematureEndCondition(() => isGoing). BeginLoop(). // Different from the last full-animation, we continue "going forward". RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). EndPrematureEndCondition(). BeginSequence(). RangeBySpeed(400, 0, 70, (value) => imageCharacter.Left = value). Add(() => isGoing = true). EndSequence(). EndParallel(). Range(-1.0, 1.0, 1, (value) => imageCharacter.ScaleX = value). EndSequence(), // Go, Turn and Return (* walking while turning). // This animation is similar to the previous 2, but in this case the character is always walking, even // when the animation is "turning" to the opposite side. AnimationBuilder. BeginParallel(). BeginLoop(). RangeBySpeed(0, _movingForwardCharacter.Count-1, 10, (index) => imageCharacter.Source = _movingForwardCharacter[index]). EndLoop(). BeginLoop(). BeginSequence(). RangeBySpeed(0, 400, 70, (value) => imageCharacter.Left = value). Range(1.0, -1.0, 1, (value) => imageCharacter.ScaleX = value). RangeBySpeed(400, 0, 70, (value) => imageCharacter.Left = value). Range(-1.0, 1.0, 1, (value) => imageCharacter.ScaleX = value). EndSequence(). EndLoop(). EndParallel() }; listboxIntermediaryAnimation.SelectionChanged += listboxIntermediaryAnimation_SelectionChanged; } private IEnumerable<IAnimation> _ImperativeAnimation() { Random random = new Random(); while(true) { Point origin = new Point(Canvas.GetLeft(circle), Canvas.GetTop(circle)); Point destination = new Point(random.Next(450), random.Next(450)); yield return AnimationBuilder.RangeBySpeed(origin, destination, 150, _SetLeftAndTop); } } private void _SetLeftAndTop(Point point) { Canvas.SetLeft(circle, point.X); Canvas.SetTop(circle, point.Y); } private IEnumerable<IAnimation> _FrameBasedAnimation() { var helper = FrameBasedAnimationHelper.CreateByFps(100); while(true) { double yPosition = 0; double xPosition = 0; double ySpeed = 0.5; while(yPosition < 500) { xPosition++; yPosition += ySpeed; ySpeed += 0.1; Canvas.SetLeft(circle, xPosition); Canvas.SetTop(circle, yPosition); yield return helper.WaitNextFrame(); } } } private void listboxBasicAnimation_SelectionChanged(object sender, SelectionChangedEventArgs e) { _SetBasicAnimation(); } private void _SetBasicAnimation() { Canvas.SetLeft(circle, 0); Canvas.SetTop(circle, 0); circle.Fill = Brushes.Black; if (_animation != null) _animation.Reset(); _animation = _basicAnimations[listboxBasicAnimation.SelectedIndex]; } private void listboxIntermediaryAnimation_SelectionChanged(object sender, SelectionChangedEventArgs e) { _SetIntermediaryAnimation(); } private void _SetIntermediaryAnimation() { imageCharacter.Left = 0; imageCharacter.Top = 0; imageCharacter.ScaleX = 1; if (_animation != null) _animation.Reset(); _animation = _intermediaryAnimations[listboxIntermediaryAnimation.SelectedIndex]; } private ReadOnlyCollection<BitmapFrame> _LoadCharacter(string path) { using(var stream = File.OpenRead(path)) { var decoder = GifBitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); var frames = decoder.Frames; return frames; } } private IEnumerable<IAnimation> _MoveFrameByFrame(ReadOnlyCollection<BitmapFrame> character) { var helper = FrameBasedAnimationHelper.CreateByFps(80); int frameCount = character.Count*7; int frameIndex = 0; imageCharacter.Top = canvasIntermediary.ActualHeight - character[0].Height; while(true) { for(int left=0; left<400; left++) { frameIndex++; if (frameIndex >= frameCount) frameIndex = 0; imageCharacter.Source = character[frameIndex/7]; imageCharacter.Left = left; yield return helper.WaitNextFrame(); } } } private void tabItemAdvanced_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) { if (_animation != null) _animation.Reset(); _animation = new ImperativeAnimation(_AdvancedAnimation()); } private int _direction = 0; private bool _isUpPressed; private IEnumerable<IAnimation> _AdvancedAnimation() { var helper = FrameBasedAnimationHelper.CreateByFps(80); canvasAdvanced.Focus(); var canvasChildren = canvasAdvanced.Children; double playerLeft = 0; double playerScale = 1; var playerCharacter = new ImageWithShadow(); playerCharacter.Left = playerLeft; playerCharacter.Top = 300; var otherCharacter = new ImageWithShadow(); otherCharacter.ScaleX = -1; otherCharacter.Left = 350; otherCharacter.Top = 300; var presentationAnimation = AnimationBuilder. BeginSequence(). Add(_ShowText("This is an interactive animation.\r\nPress the Left, Up and Right arrows to Move.")). Add(_ShowText("Yet this is not a game, the other character will only flee from you.")). EndSequence(); bool ending = false; bool jumping = false; try { // This animation will run in parallel to the actual imperative animaion. // It is "subordinated" and so, if this animation is ended prematurely, such // parallel animation will also end prematurely. // This is different than adding the animation to the WpfAnimationManager directly. // Also, there is an additional difference, as time modifiers that are affecting // this animation will also affect its subordinated parallel (even if this is not // happening in this sample application). ImperativeAnimation.AddSubordinatedParallel(presentationAnimation); canvasChildren.Add(playerCharacter); canvasChildren.Add(otherCharacter); canvasAdvanced.PreviewKeyDown += canvasAdvanced_PreviewKeyDown; canvasAdvanced.PreviewKeyUp += canvasAdvanced_PreviewKeyUp; int actualMovingFrame = 0; int totalMovingFrames = _movingForwardCharacter.Count * 8; int totalWaitingFrames = _waitingCharacter.Count * 8; int actualWaitingFrame = totalWaitingFrames; bool running = true; while(running) { actualWaitingFrame++; if (actualWaitingFrame >= totalWaitingFrames) actualWaitingFrame = 0; int actualRealFrame = actualWaitingFrame / 8; otherCharacter.Source = _waitingCharacter[actualRealFrame]; if (_isUpPressed && !jumping) { jumping = true; Action<double> setTop = (value) => playerCharacter.JumpingHeight = value; var animation = AnimationBuilder.BeginSequence(). Range(0, 100, 0.3, setTop). Range(100, 0, 0.3, setTop). Add(() => jumping = false). EndSequence(); ImperativeAnimation.AddSubordinatedParallel(animation); } if (_direction == 0) playerCharacter.Source = _waitingCharacter[actualRealFrame]; else { bool canMove = false; if (_direction < 0) { if (playerScale > -1) { playerScale -= 0.1; if (playerScale < -1) playerScale = -1; } else canMove = true; playerCharacter.ScaleX = playerScale; } else { if (playerScale < 1) { playerScale += 0.1; if (playerScale > 1) playerScale = 1; } else canMove = true; playerCharacter.ScaleX = playerScale; } if (canMove) { actualMovingFrame++; if (actualMovingFrame >= totalMovingFrames) actualMovingFrame = 0; playerCharacter.Source = _movingForwardCharacter[actualMovingFrame/8]; playerLeft += _direction * 1; if (playerLeft < 0) playerLeft = 0; // The typical invisible barrier in which the character // continues walking without moving. playerCharacter.Left = playerLeft; if (playerLeft > 250 && !ending) { // this is to avoid playing the ending animation more // than once. ending = true; // and this is just in case the presentation is still running, // as we don't want messages to overlap. presentationAnimation.Dispose(); Action<double> setLeft = (value) => otherCharacter.Left = value; Action<double> setTop = (value) => otherCharacter.Top = value; var finalAnimation = AnimationBuilder. BeginSequence(). BeginParallel(). Range(350, 370, 0.10, setLeft). Range(300, 280, 0.10, setTop). EndParallel(). BeginParallel(). Range(370, 390, 0.10, setLeft). Range(280, 300, 0.10, setTop). EndParallel(). Range(-1.0, 1.0, 0.5, (value) => otherCharacter.ScaleX = value). Range(390, 510, 0.5, setLeft). Add(_ShowText("The other character fled from you...")). Add(_ShowText("... he is a COWARD!!!")). Add(() => running=false). EndSequence(); ImperativeAnimation.AddSubordinatedParallel(finalAnimation); } } } yield return helper.WaitNextFrame(); } } finally { canvasAdvanced.PreviewKeyDown -= canvasAdvanced_PreviewKeyDown; canvasChildren.Remove(playerCharacter); canvasChildren.Remove(otherCharacter); } } void canvasAdvanced_PreviewKeyDown(object sender, KeyEventArgs e) { switch(e.Key) { case Key.Left: _direction = -1; e.Handled = true; break; case Key.Right: _direction = 1; e.Handled = true; break; case Key.Up: _isUpPressed = true; e.Handled = true; break; } } void canvasAdvanced_PreviewKeyUp(object sender, KeyEventArgs e) { switch(e.Key) { case Key.Left: case Key.Right: e.Handled = true; _direction = 0; break; case Key.Up: e.Handled = true; _isUpPressed = false; break; } } private IEnumerable<IAnimation> _ShowText(string message) { var textBlock = new TextBlock(); try { textBlock.Text = message; canvasAdvanced.Children.Add(textBlock); Action<double> setOpacity = (value) => textBlock.Opacity = value; yield return AnimationBuilder. BeginSequence(). Range(0.0, 1.0, 1, setOpacity). Wait(2). Range(1.0, 0.0, 1, setOpacity). EndSequence(); } finally { canvasAdvanced.Children.Remove(textBlock); } } } }
End of preview.