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 <egore911@gmail.com>
*/
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);
}
}
}
}
|
// 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.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Resources.Proprietary;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.DiaSymReader;
using Roslyn.Test.PdbUtilities;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.TestGenerators;
using Roslyn.Utilities;
using Xunit;
using Basic.Reference.Assemblies;
using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers;
using static Roslyn.Test.Utilities.SharedResourceHelpers;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.CSharp.CommandLine.UnitTests
{
public class CommandLineTests : CommandLineTestBase
{
#if NETCOREAPP
private static readonly string s_CSharpCompilerExecutable;
private static readonly string s_DotnetCscRun;
#else
private static readonly string s_CSharpCompilerExecutable = Path.Combine(
Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location),
Path.Combine("dependency", "csc.exe"));
private static readonly string s_DotnetCscRun = ExecutionConditionUtil.IsMono ? "mono" : string.Empty;
#endif
private static readonly string s_CSharpScriptExecutable;
private static readonly string s_compilerVersion = CommonCompiler.GetProductVersion(typeof(CommandLineTests));
static CommandLineTests()
{
#if NETCOREAPP
var cscDllPath = Path.Combine(
Path.GetDirectoryName(typeof(CommandLineTests).GetTypeInfo().Assembly.Location),
Path.Combine("dependency", "csc.dll"));
var dotnetExe = DotNetCoreSdk.ExePath;
var netStandardDllPath = AppDomain.CurrentDomain.GetAssemblies()
.FirstOrDefault(assembly => !assembly.IsDynamic && assembly.Location.EndsWith("netstandard.dll")).Location;
var netStandardDllDir = Path.GetDirectoryName(netStandardDllPath);
// Since we are using references based on the UnitTest's runtime, we need to use
// its runtime config when executing out program.
var runtimeConfigPath = Path.ChangeExtension(Assembly.GetExecutingAssembly().Location, "runtimeconfig.json");
s_CSharpCompilerExecutable = $@"""{dotnetExe}"" ""{cscDllPath}"" /r:""{netStandardDllPath}"" /r:""{netStandardDllDir}/System.Private.CoreLib.dll"" /r:""{netStandardDllDir}/System.Console.dll"" /r:""{netStandardDllDir}/System.Runtime.dll""";
s_DotnetCscRun = $@"""{dotnetExe}"" exec --runtimeconfig ""{runtimeConfigPath}""";
s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.dll", Path.Combine("csi", "csi.dll"));
#else
s_CSharpScriptExecutable = s_CSharpCompilerExecutable.Replace("csc.exe", Path.Combine("csi", "csi.exe"));
#endif
}
private class TestCommandLineParser : CSharpCommandLineParser
{
private readonly Dictionary<string, string> _responseFiles;
private readonly Dictionary<string, string[]> _recursivePatterns;
private readonly Dictionary<string, string[]> _patterns;
public TestCommandLineParser(
Dictionary<string, string> responseFiles = null,
Dictionary<string, string[]> patterns = null,
Dictionary<string, string[]> recursivePatterns = null,
bool isInteractive = false)
: base(isInteractive)
{
_responseFiles = responseFiles;
_recursivePatterns = recursivePatterns;
_patterns = patterns;
}
internal override IEnumerable<string> EnumerateFiles(string directory,
string fileNamePattern,
SearchOption searchOption)
{
var key = directory + "|" + fileNamePattern;
if (searchOption == SearchOption.TopDirectoryOnly)
{
return _patterns[key];
}
else
{
return _recursivePatterns[key];
}
}
internal override TextReader CreateTextFileReader(string fullPath)
{
return new StringReader(_responseFiles[fullPath]);
}
}
private CSharpCommandLineArguments ScriptParse(IEnumerable<string> args, string baseDirectory)
{
return CSharpCommandLineParser.Script.Parse(args, baseDirectory, SdkDirectory);
}
private CSharpCommandLineArguments FullParse(string commandLine, string baseDirectory, string sdkDirectory = null, string additionalReferenceDirectories = null)
{
sdkDirectory = sdkDirectory ?? SdkDirectory;
var args = CommandLineParser.SplitCommandLineIntoArguments(commandLine, removeHashComments: true);
return CSharpCommandLineParser.Default.Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories);
}
[ConditionalFact(typeof(WindowsDesktopOnly))]
[WorkItem(34101, "https://github.com/dotnet/roslyn/issues/34101")]
public void SuppressedWarnAsErrorsStillEmit()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
#pragma warning disable 1591
public class P {
public static void Main() {}
}");
const string docName = "doc.xml";
var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/errorlog:errorlog", $"/doc:{docName}", "/warnaserror", src.Path });
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString());
string exePath = Path.Combine(dir.Path, "temp.exe");
Assert.True(File.Exists(exePath));
var result = ProcessUtilities.Run(exePath, arguments: "");
Assert.Equal(0, result.ExitCode);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)]
public void XmlMemoryMapped()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText("class C {}");
const string docName = "doc.xml";
var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/t:library", "/preferreduilang:en", $"/doc:{docName}", src.Path });
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString());
var xmlPath = Path.Combine(dir.Path, docName);
using (var fileStream = new FileStream(xmlPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var mmf = MemoryMappedFile.CreateFromFile(fileStream, "xmlMap", 0, MemoryMappedFileAccess.Read, HandleInheritability.None, leaveOpen: true))
{
exitCode = cmd.Run(outWriter);
Assert.StartsWith($"error CS0016: Could not write to output file '{xmlPath}' -- ", outWriter.ToString());
Assert.Equal(1, exitCode);
}
}
[Fact]
public void SimpleAnalyzerConfig()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("test.cs").WriteAllText(@"
class C
{
int _f;
}");
var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@"
[*.cs]
dotnet_diagnostic.cs0169.severity = none");
var cmd = CreateCSharpCompiler(null, dir.Path, new[] {
"/nologo",
"/t:library",
"/preferreduilang:en",
"/analyzerconfig:" + analyzerConfig.Path,
src.Path });
Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths));
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString());
Assert.Null(cmd.AnalyzerOptions);
}
[Fact]
public void AnalyzerConfigWithOptions()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("test.cs").WriteAllText(@"
class C
{
int _f;
}");
var additionalFile = dir.CreateFile("file.txt");
var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@"
[*.cs]
dotnet_diagnostic.cs0169.severity = none
dotnet_diagnostic.Warning01.severity = none
my_option = my_val
[*.txt]
dotnet_diagnostic.cs0169.severity = none
my_option2 = my_val2");
var cmd = CreateCSharpCompiler(null, dir.Path, new[] {
"/nologo",
"/t:library",
"/analyzerconfig:" + analyzerConfig.Path,
"/analyzer:" + Assembly.GetExecutingAssembly().Location,
"/nowarn:8032",
"/additionalfile:" + additionalFile.Path,
src.Path });
Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths));
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
Assert.Equal("", outWriter.ToString());
Assert.Equal(0, exitCode);
var comp = cmd.Compilation;
var tree = comp.SyntaxTrees.Single();
var compilerTreeOptions = comp.Options.SyntaxTreeOptionsProvider;
Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "cs0169", CancellationToken.None, out var severity));
Assert.Equal(ReportDiagnostic.Suppress, severity);
Assert.True(compilerTreeOptions.TryGetDiagnosticValue(tree, "warning01", CancellationToken.None, out severity));
Assert.Equal(ReportDiagnostic.Suppress, severity);
var analyzerOptions = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider;
var options = analyzerOptions.GetOptions(tree);
Assert.NotNull(options);
Assert.True(options.TryGetValue("my_option", out string val));
Assert.Equal("my_val", val);
Assert.False(options.TryGetValue("my_option2", out _));
Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _));
options = analyzerOptions.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single());
Assert.NotNull(options);
Assert.True(options.TryGetValue("my_option2", out val));
Assert.Equal("my_val2", val);
Assert.False(options.TryGetValue("my_option", out _));
Assert.False(options.TryGetValue("dotnet_diagnostic.cs0169.severity", out _));
}
[Fact]
public void AnalyzerConfigBadSeverity()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("test.cs").WriteAllText(@"
class C
{
int _f;
}");
var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@"
[*.cs]
dotnet_diagnostic.cs0169.severity = garbage");
var cmd = CreateCSharpCompiler(null, dir.Path, new[] {
"/nologo",
"/t:library",
"/preferreduilang:en",
"/analyzerconfig:" + analyzerConfig.Path,
src.Path });
Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths));
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal(
$@"warning InvalidSeverityInAnalyzerConfig: The diagnostic 'cs0169' was given an invalid severity 'garbage' in the analyzer config file at '{analyzerConfig.Path}'.
test.cs(4,9): warning CS0169: The field 'C._f' is never used
", outWriter.ToString());
Assert.Null(cmd.AnalyzerOptions);
}
[Fact]
public void AnalyzerConfigsInSameDir()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("test.cs").WriteAllText(@"
class C
{
int _f;
}");
var configText = @"
[*.cs]
dotnet_diagnostic.cs0169.severity = suppress";
var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText);
var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText);
var cmd = CreateCSharpCompiler(null, dir.Path, new[] {
"/nologo",
"/t:library",
"/preferreduilang:en",
"/analyzerconfig:" + analyzerConfig1.Path,
"/analyzerconfig:" + analyzerConfig2.Path,
src.Path
});
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal(
$"error CS8700: Multiple analyzer config files cannot be in the same directory ('{dir.Path}').",
outWriter.ToString().TrimEnd());
}
// This test should only run when the machine's default encoding is shift-JIS
[ConditionalFact(typeof(WindowsDesktopOnly), typeof(HasShiftJisDefaultEncoding), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void CompileShiftJisOnShiftJis()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource);
var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", src.Path });
Assert.Null(cmd.Arguments.Encoding);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString());
var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path);
Assert.Equal(0, result.ExitCode);
Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932)));
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void RunWithShiftJisFile()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("sjis.cs").WriteAllBytes(TestResources.General.ShiftJisSource);
var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/codepage:932", src.Path });
Assert.Equal(932, cmd.Arguments.Encoding?.WindowsCodePage);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString());
var result = ProcessUtilities.Run(Path.Combine(dir.Path, "sjis.exe"), arguments: "", workingDirectory: dir.Path);
Assert.Equal(0, result.ExitCode);
Assert.Equal("星野 八郎太", File.ReadAllText(Path.Combine(dir.Path, "output.txt"), Encoding.GetEncoding(932)));
}
[WorkItem(946954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/946954")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void CompilerBinariesAreAnyCPU()
{
Assert.Equal(ProcessorArchitecture.MSIL, AssemblyName.GetAssemblyName(s_CSharpCompilerExecutable).ProcessorArchitecture);
}
[Fact]
public void ResponseFiles1()
{
string rsp = Temp.CreateFile().WriteAllText(@"
/r:System.dll
/nostdlib
# this is ignored
System.Console.WriteLine(""*?""); # this is error
a.cs
").Path;
var cmd = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { "b.cs" });
cmd.Arguments.Errors.Verify(
// error CS2001: Source file 'System.Console.WriteLine(*?);' could not be found
Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("System.Console.WriteLine(*?);"));
AssertEx.Equal(new[] { "System.dll" }, cmd.Arguments.MetadataReferences.Select(r => r.Reference));
AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "a.cs"), Path.Combine(WorkingDirectory, "b.cs") }, cmd.Arguments.SourceFiles.Select(file => file.Path));
CleanupAllGeneratedFiles(rsp);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)]
public void ResponseFiles_RelativePaths()
{
var parentDir = Temp.CreateDirectory();
var baseDir = parentDir.CreateDirectory("temp");
var dirX = baseDir.CreateDirectory("x");
var dirAB = baseDir.CreateDirectory("a b");
var dirSubDir = baseDir.CreateDirectory("subdir");
var dirGoo = parentDir.CreateDirectory("goo");
var dirBar = parentDir.CreateDirectory("bar");
string basePath = baseDir.Path;
Func<string, string> prependBasePath = fileName => Path.Combine(basePath, fileName);
var parser = new TestCommandLineParser(responseFiles: new Dictionary<string, string>()
{
{ prependBasePath(@"a.rsp"), @"
""@subdir\b.rsp""
/r:..\v4.0.30319\System.dll
/r:.\System.Data.dll
a.cs @""..\c.rsp"" @\d.rsp
/libpaths:..\goo;../bar;""a b""
"
},
{ Path.Combine(dirSubDir.Path, @"b.rsp"), @"
b.cs
"
},
{ prependBasePath(@"..\c.rsp"), @"
c.cs /lib:x
"
},
{ Path.Combine(Path.GetPathRoot(basePath), @"d.rsp"), @"
# comment
d.cs
"
}
}, isInteractive: false);
var args = parser.Parse(new[] { "first.cs", "second.cs", "@a.rsp", "last.cs" }, basePath, SdkDirectory);
args.Errors.Verify();
Assert.False(args.IsScriptRunner);
string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray();
string[] references = args.MetadataReferences.Select(r => r.Reference).ToArray();
AssertEx.Equal(new[] { "first.cs", "second.cs", "b.cs", "a.cs", "c.cs", "d.cs", "last.cs" }.Select(prependBasePath), resolvedSourceFiles);
AssertEx.Equal(new[] { typeof(object).Assembly.Location, @"..\v4.0.30319\System.dll", @".\System.Data.dll" }, references);
AssertEx.Equal(new[] { RuntimeEnvironment.GetRuntimeDirectory() }.Concat(new[] { @"x", @"..\goo", @"../bar", @"a b" }.Select(prependBasePath)), args.ReferencePaths.ToArray());
Assert.Equal(basePath, args.BaseDirectory);
}
#nullable enable
[ConditionalFact(typeof(WindowsOnly))]
public void NullBaseDirectoryNotAddedToKeyFileSearchPaths()
{
var parser = CSharpCommandLineParser.Default.Parse(new[] { "c:/test.cs" }, baseDirectory: null, SdkDirectory);
AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths);
Assert.Null(parser.OutputDirectory);
parser.Errors.Verify(
// error CS8762: Output directory could not be determined
Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1)
);
}
[ConditionalFact(typeof(WindowsOnly))]
public void NullBaseDirectoryWithAdditionalFiles()
{
var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:web.config", "c:/test.cs" }, baseDirectory: null, SdkDirectory);
AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths);
Assert.Null(parser.OutputDirectory);
parser.Errors.Verify(
// error CS2021: File name 'web.config' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("web.config").WithLocation(1, 1),
// error CS8762: Output directory could not be determined
Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1)
);
}
[ConditionalFact(typeof(WindowsOnly))]
public void NullBaseDirectoryWithAdditionalFiles_Wildcard()
{
var parser = CSharpCommandLineParser.Default.Parse(new[] { "/additionalfile:*", "c:/test.cs" }, baseDirectory: null, SdkDirectory);
AssertEx.Equal(ImmutableArray.Create<string>(), parser.KeyFileSearchPaths);
Assert.Null(parser.OutputDirectory);
parser.Errors.Verify(
// error CS2001: Source file '*' could not be found.
Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("*").WithLocation(1, 1),
// error CS8762: Output directory could not be determined
Diagnostic(ErrorCode.ERR_NoOutputDirectory).WithLocation(1, 1)
);
}
#nullable disable
[Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")]
public void NoSdkPath()
{
var parentDir = Temp.CreateDirectory();
var parser = CSharpCommandLineParser.Default.Parse(new[] { "file.cs", $"-out:{parentDir.Path}", "/noSdkPath" }, parentDir.Path, null);
AssertEx.Equal(ImmutableArray<string>.Empty, parser.ReferencePaths);
}
[Fact, WorkItem(29252, "https://github.com/dotnet/roslyn/issues/29252")]
public void NoSdkPathReferenceSystemDll()
{
string source = @"
class C
{
}
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/nosdkpath", "/r:System.dll", "a.cs" });
var exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS0006: Metadata file 'System.dll' could not be found", outWriter.ToString().Trim());
}
[ConditionalFact(typeof(WindowsOnly))]
public void SourceFiles_Patterns()
{
var parser = new TestCommandLineParser(
patterns: new Dictionary<string, string[]>()
{
{ @"C:\temp|*.cs", new[] { "a.cs", "b.cs", "c.cs" } }
},
recursivePatterns: new Dictionary<string, string[]>()
{
{ @"C:\temp\a|*.cs", new[] { @"a\x.cs", @"a\b\b.cs", @"a\c.cs" } },
});
var args = parser.Parse(new[] { @"*.cs", @"/recurse:a\*.cs" }, @"C:\temp", SdkDirectory);
args.Errors.Verify();
string[] resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray();
AssertEx.Equal(new[] { @"C:\temp\a.cs", @"C:\temp\b.cs", @"C:\temp\c.cs", @"C:\temp\a\x.cs", @"C:\temp\a\b\b.cs", @"C:\temp\a\c.cs" }, resolvedSourceFiles);
}
[Fact]
public void ParseQuotedMainType()
{
// Verify the main switch are unquoted when used because of the issue with
// MSBuild quoting some usages and not others. A quote character is not valid in either
// these names.
CSharpCommandLineArguments args;
var folder = Temp.CreateDirectory();
CreateFile(folder, "a.cs");
args = DefaultParse(new[] { "/main:Test", "a.cs" }, folder.Path);
args.Errors.Verify();
Assert.Equal("Test", args.CompilationOptions.MainTypeName);
args = DefaultParse(new[] { "/main:\"Test\"", "a.cs" }, folder.Path);
args.Errors.Verify();
Assert.Equal("Test", args.CompilationOptions.MainTypeName);
args = DefaultParse(new[] { "/main:\"Test.Class1\"", "a.cs" }, folder.Path);
args.Errors.Verify();
Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName);
args = DefaultParse(new[] { "/m:Test", "a.cs" }, folder.Path);
args.Errors.Verify();
Assert.Equal("Test", args.CompilationOptions.MainTypeName);
args = DefaultParse(new[] { "/m:\"Test\"", "a.cs" }, folder.Path);
args.Errors.Verify();
Assert.Equal("Test", args.CompilationOptions.MainTypeName);
args = DefaultParse(new[] { "/m:\"Test.Class1\"", "a.cs" }, folder.Path);
args.Errors.Verify();
Assert.Equal("Test.Class1", args.CompilationOptions.MainTypeName);
// Use of Cyrillic namespace
args = DefaultParse(new[] { "/m:\"решения.Class1\"", "a.cs" }, folder.Path);
args.Errors.Verify();
Assert.Equal("решения.Class1", args.CompilationOptions.MainTypeName);
}
[Fact]
[WorkItem(21508, "https://github.com/dotnet/roslyn/issues/21508")]
public void ArgumentStartWithDashAndContainingSlash()
{
CSharpCommandLineArguments args;
var folder = Temp.CreateDirectory();
args = DefaultParse(new[] { "-debug+/debug:portable" }, folder.Path);
args.Errors.Verify(
// error CS2007: Unrecognized option: '-debug+/debug:portable'
Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("-debug+/debug:portable").WithLocation(1, 1),
// warning CS2008: No source files specified.
Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
// error CS1562: Outputs without source must have the /out option specified
Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)
);
}
[WorkItem(546009, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546009")]
[WorkItem(545991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545991")]
[ConditionalFact(typeof(WindowsOnly))]
public void SourceFiles_Patterns2()
{
var folder = Temp.CreateDirectory();
CreateFile(folder, "a.cs");
CreateFile(folder, "b.vb");
CreateFile(folder, "c.cpp");
var folderA = folder.CreateDirectory("A");
CreateFile(folderA, "A_a.cs");
CreateFile(folderA, "A_b.cs");
CreateFile(folderA, "A_c.vb");
var folderB = folder.CreateDirectory("B");
CreateFile(folderB, "B_a.cs");
CreateFile(folderB, "B_b.vb");
CreateFile(folderB, "B_c.cpx");
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:.", "/out:abc.dll" }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim());
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:. ", "/out:abc.dll" }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim());
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse: . ", "/out:abc.dll" }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim());
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, folder.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", @"/recurse:././.", "/out:abc.dll" }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("warning CS2008: No source files specified.", outWriter.ToString().Trim());
CSharpCommandLineArguments args;
string[] resolvedSourceFiles;
args = DefaultParse(new[] { @"/recurse:*.cp*", @"/recurse:a\*.c*", @"/out:a.dll" }, folder.Path);
args.Errors.Verify();
resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray();
AssertEx.Equal(new[] { folder.Path + @"\c.cpp", folder.Path + @"\B\B_c.cpx", folder.Path + @"\a\A_a.cs", folder.Path + @"\a\A_b.cs", }, resolvedSourceFiles);
args = DefaultParse(new[] { @"/recurse:.\\\\\\*.cs", @"/out:a.dll" }, folder.Path);
args.Errors.Verify();
resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray();
Assert.Equal(4, resolvedSourceFiles.Length);
args = DefaultParse(new[] { @"/recurse:.////*.cs", @"/out:a.dll" }, folder.Path);
args.Errors.Verify();
resolvedSourceFiles = args.SourceFiles.Select(f => f.Path).ToArray();
Assert.Equal(4, resolvedSourceFiles.Length);
}
[ConditionalFact(typeof(WindowsOnly))]
public void SourceFile_BadPath()
{
var args = DefaultParse(new[] { @"e:c:\test\test.cs", "/t:library" }, WorkingDirectory);
Assert.Equal(3, args.Errors.Length);
Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, args.Errors[0].Code);
Assert.Equal((int)ErrorCode.WRN_NoSources, args.Errors[1].Code);
Assert.Equal((int)ErrorCode.ERR_OutputNeedsName, args.Errors[2].Code);
}
private void CreateFile(TempDirectory folder, string file)
{
var f = folder.CreateFile(file);
f.WriteAllText("");
}
[Fact, WorkItem(546023, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546023")]
public void Win32ResourceArguments()
{
string[] args = new string[]
{
@"/win32manifest:..\here\there\everywhere\nonexistent"
};
var parsedArgs = DefaultParse(args, WorkingDirectory);
var compilation = CreateCompilation(new SyntaxTree[0]);
IEnumerable<DiagnosticInfo> errors;
CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors);
Assert.Equal(1, errors.Count());
Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code);
Assert.Equal(2, errors.First().Arguments.Count());
args = new string[]
{
@"/Win32icon:\bogus"
};
parsedArgs = DefaultParse(args, WorkingDirectory);
CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors);
Assert.Equal(1, errors.Count());
Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code);
Assert.Equal(2, errors.First().Arguments.Count());
args = new string[]
{
@"/Win32Res:\bogus"
};
parsedArgs = DefaultParse(args, WorkingDirectory);
CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors);
Assert.Equal(1, errors.Count());
Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code);
Assert.Equal(2, errors.First().Arguments.Count());
args = new string[]
{
@"/Win32Res:goo.win32data:bar.win32data2"
};
parsedArgs = DefaultParse(args, WorkingDirectory);
CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors);
Assert.Equal(1, errors.Count());
Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Res, errors.First().Code);
Assert.Equal(2, errors.First().Arguments.Count());
args = new string[]
{
@"/Win32icon:goo.win32data:bar.win32data2"
};
parsedArgs = DefaultParse(args, WorkingDirectory);
CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors);
Assert.Equal(1, errors.Count());
Assert.Equal((int)ErrorCode.ERR_CantOpenIcon, errors.First().Code);
Assert.Equal(2, errors.First().Arguments.Count());
args = new string[]
{
@"/Win32manifest:goo.win32data:bar.win32data2"
};
parsedArgs = DefaultParse(args, WorkingDirectory);
CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors);
Assert.Equal(1, errors.Count());
Assert.Equal((int)ErrorCode.ERR_CantOpenWin32Manifest, errors.First().Code);
Assert.Equal(2, errors.First().Arguments.Count());
}
[Fact]
public void Win32ResConflicts()
{
var parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32icon:goob", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndIcon, parsedArgs.Errors.First().Code);
parsedArgs = DefaultParse(new[] { "/win32res:goo", "/win32manifest:goob", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_CantHaveWin32ResAndManifest, parsedArgs.Errors.First().Code);
parsedArgs = DefaultParse(new[] { "/win32res:", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code);
Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count);
parsedArgs = DefaultParse(new[] { "/win32Icon: ", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code);
Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count);
parsedArgs = DefaultParse(new[] { "/win32Manifest:", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_NoFileSpec, parsedArgs.Errors.First().Code);
Assert.Equal(1, parsedArgs.Errors.First().Arguments.Count);
parsedArgs = DefaultParse(new[] { "/win32Manifest:goo", "/noWin32Manifest", "a.cs" }, WorkingDirectory);
Assert.Equal(0, parsedArgs.Errors.Length);
Assert.True(parsedArgs.NoWin32Manifest);
Assert.Null(parsedArgs.Win32Manifest);
}
[Fact]
public void Win32ResInvalid()
{
var parsedArgs = DefaultParse(new[] { "/win32res", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32res"));
parsedArgs = DefaultParse(new[] { "/win32res+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32res+"));
parsedArgs = DefaultParse(new[] { "/win32icon", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32icon"));
parsedArgs = DefaultParse(new[] { "/win32icon+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32icon+"));
parsedArgs = DefaultParse(new[] { "/win32manifest", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/win32manifest"));
parsedArgs = DefaultParse(new[] { "/win32manifest+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/win32manifest+"));
}
[Fact]
public void Win32IconContainsGarbage()
{
string tmpFileName = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }).Path;
var parsedArgs = DefaultParse(new[] { "/win32icon:" + tmpFileName, "a.cs" }, WorkingDirectory);
var compilation = CreateCompilation(new SyntaxTree[0]);
IEnumerable<DiagnosticInfo> errors;
CSharpCompiler.GetWin32ResourcesInternal(StandardFileSystem.Instance, MessageProvider.Instance, parsedArgs, compilation, out errors);
Assert.Equal(1, errors.Count());
Assert.Equal((int)ErrorCode.ERR_ErrorBuildingWin32Resources, errors.First().Code);
Assert.Equal(1, errors.First().Arguments.Count());
CleanupAllGeneratedFiles(tmpFileName);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
public void Win32ResQuotes()
{
string[] responseFile = new string[] {
@" /win32res:d:\\""abc def""\a""b c""d\a.res",
};
CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\");
Assert.Equal(@"d:\abc def\ab cd\a.res", args.Win32ResourceFile);
responseFile = new string[] {
@" /win32icon:d:\\""abc def""\a""b c""d\a.ico",
};
args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\");
Assert.Equal(@"d:\abc def\ab cd\a.ico", args.Win32Icon);
responseFile = new string[] {
@" /win32manifest:d:\\""abc def""\a""b c""d\a.manifest",
};
args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\");
Assert.Equal(@"d:\abc def\ab cd\a.manifest", args.Win32Manifest);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
public void ParseResources()
{
var diags = new List<Diagnostic>();
ResourceDescription desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar", WorkingDirectory, diags, embedded: false);
Assert.Equal(0, diags.Count);
Assert.Equal(@"someFile.goo.bar", desc.FileName);
Assert.Equal("someFile.goo.bar", desc.ResourceName);
desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName", WorkingDirectory, diags, embedded: false);
Assert.Equal(0, diags.Count);
Assert.Equal(@"someFile.goo.bar", desc.FileName);
Assert.Equal("someName", desc.ResourceName);
desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\s""ome Fil""e.goo.bar,someName", WorkingDirectory, diags, embedded: false);
Assert.Equal(0, diags.Count);
Assert.Equal(@"some File.goo.bar", desc.FileName);
Assert.Equal("someName", desc.ResourceName);
desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,""some Name"",public", WorkingDirectory, diags, embedded: false);
Assert.Equal(0, diags.Count);
Assert.Equal(@"someFile.goo.bar", desc.FileName);
Assert.Equal("some Name", desc.ResourceName);
Assert.True(desc.IsPublic);
// Use file name in place of missing resource name.
desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false);
Assert.Equal(0, diags.Count);
Assert.Equal(@"someFile.goo.bar", desc.FileName);
Assert.Equal("someFile.goo.bar", desc.ResourceName);
Assert.False(desc.IsPublic);
// Quoted accessibility is fine.
desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,""private""", WorkingDirectory, diags, embedded: false);
Assert.Equal(0, diags.Count);
Assert.Equal(@"someFile.goo.bar", desc.FileName);
Assert.Equal("someFile.goo.bar", desc.ResourceName);
Assert.False(desc.IsPublic);
// Leading commas are not ignored...
desc = CSharpCommandLineParser.ParseResourceDescription("", @",,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false);
diags.Verify(
// error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private'
Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar"));
diags.Clear();
Assert.Null(desc);
// ...even if there's whitespace between them.
desc = CSharpCommandLineParser.ParseResourceDescription("", @", ,\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false);
diags.Verify(
// error CS1906: Invalid option '\somepath\someFile.goo.bar'; Resource visibility must be either 'public' or 'private'
Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(@"\somepath\someFile.goo.bar"));
diags.Clear();
Assert.Null(desc);
// Trailing commas are ignored...
desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private", WorkingDirectory, diags, embedded: false);
diags.Verify();
diags.Clear();
Assert.Equal("someFile.goo.bar", desc.FileName);
Assert.Equal("someFile.goo.bar", desc.ResourceName);
Assert.False(desc.IsPublic);
// ...even if there's whitespace between them.
desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,,private, ,", WorkingDirectory, diags, embedded: false);
diags.Verify();
diags.Clear();
Assert.Equal("someFile.goo.bar", desc.FileName);
Assert.Equal("someFile.goo.bar", desc.ResourceName);
Assert.False(desc.IsPublic);
desc = CSharpCommandLineParser.ParseResourceDescription("", @"\somepath\someFile.goo.bar,someName,publi", WorkingDirectory, diags, embedded: false);
diags.Verify(Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments("publi"));
Assert.Null(desc);
diags.Clear();
desc = CSharpCommandLineParser.ParseResourceDescription("", @"D:rive\relative\path,someName,public", WorkingDirectory, diags, embedded: false);
diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"D:rive\relative\path"));
Assert.Null(desc);
diags.Clear();
desc = CSharpCommandLineParser.ParseResourceDescription("", @"inva\l*d?path,someName,public", WorkingDirectory, diags, embedded: false);
diags.Verify(Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"inva\l*d?path"));
Assert.Null(desc);
diags.Clear();
desc = CSharpCommandLineParser.ParseResourceDescription("", (string)null, WorkingDirectory, diags, embedded: false);
diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments(""));
Assert.Null(desc);
diags.Clear();
desc = CSharpCommandLineParser.ParseResourceDescription("", "", WorkingDirectory, diags, embedded: false);
diags.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments(""));
Assert.Null(desc);
diags.Clear();
desc = CSharpCommandLineParser.ParseResourceDescription("", " ", WorkingDirectory, diags, embedded: false);
diags.Verify(
// error CS2005: Missing file specification for '' option
Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1));
diags.Clear();
Assert.Null(desc);
desc = CSharpCommandLineParser.ParseResourceDescription("", " , ", WorkingDirectory, diags, embedded: false);
diags.Verify(
// error CS2005: Missing file specification for '' option
Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1));
diags.Clear();
Assert.Null(desc);
desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ", WorkingDirectory, diags, embedded: false);
diags.Verify();
diags.Clear();
Assert.Equal("path", desc.FileName);
Assert.Equal("path", desc.ResourceName);
Assert.True(desc.IsPublic);
desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name", WorkingDirectory, diags, embedded: false);
diags.Verify(
// error CS2005: Missing file specification for '' option
Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1));
diags.Clear();
Assert.Null(desc);
desc = CSharpCommandLineParser.ParseResourceDescription("", " , , ", WorkingDirectory, diags, embedded: false);
diags.Verify(
// error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private'
Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" "));
diags.Clear();
Assert.Null(desc);
desc = CSharpCommandLineParser.ParseResourceDescription("", "path, , ", WorkingDirectory, diags, embedded: false);
diags.Verify(
// error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private'
Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" "));
diags.Clear();
Assert.Null(desc);
desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name, ", WorkingDirectory, diags, embedded: false);
diags.Verify(
// error CS1906: Invalid option ' '; Resource visibility must be either 'public' or 'private'
Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" "));
diags.Clear();
Assert.Null(desc);
desc = CSharpCommandLineParser.ParseResourceDescription("", " , ,private", WorkingDirectory, diags, embedded: false);
diags.Verify(
// error CS2005: Missing file specification for '' option
Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1));
diags.Clear();
Assert.Null(desc);
desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,", WorkingDirectory, diags, embedded: false);
diags.Verify(
// CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe)
// error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private'
Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(""));
diags.Clear();
Assert.Null(desc);
desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name,,", WorkingDirectory, diags, embedded: false);
diags.Verify(
// CONSIDER: Dev10 actually prints "Invalid option '|'" (note the pipe)
// error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private'
Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(""));
diags.Clear();
Assert.Null(desc);
desc = CSharpCommandLineParser.ParseResourceDescription("", "path,name, ", WorkingDirectory, diags, embedded: false);
diags.Verify(
// error CS1906: Invalid option ''; Resource visibility must be either 'public' or 'private'
Diagnostic(ErrorCode.ERR_BadResourceVis).WithArguments(" "));
diags.Clear();
Assert.Null(desc);
desc = CSharpCommandLineParser.ParseResourceDescription("", "path, ,private", WorkingDirectory, diags, embedded: false);
diags.Verify();
diags.Clear();
Assert.Equal("path", desc.FileName);
Assert.Equal("path", desc.ResourceName);
Assert.False(desc.IsPublic);
desc = CSharpCommandLineParser.ParseResourceDescription("", " ,name,private", WorkingDirectory, diags, embedded: false);
diags.Verify(
// error CS2005: Missing file specification for '' option
Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("").WithLocation(1, 1));
diags.Clear();
Assert.Null(desc);
var longE = new String('e', 1024);
desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("path,{0},private", longE), WorkingDirectory, diags, embedded: false);
diags.Verify(); // Now checked during emit.
diags.Clear();
Assert.Equal("path", desc.FileName);
Assert.Equal(longE, desc.ResourceName);
Assert.False(desc.IsPublic);
var longI = new String('i', 260);
desc = CSharpCommandLineParser.ParseResourceDescription("", String.Format("{0},e,private", longI), WorkingDirectory, diags, embedded: false);
diags.Verify(
// error CS2021: File name 'iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii").WithLocation(1, 1));
}
[Fact]
public void ManagedResourceOptions()
{
CSharpCommandLineArguments parsedArgs;
ResourceDescription resourceDescription;
parsedArgs = DefaultParse(new[] { "/resource:a", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.DisplayHelp);
resourceDescription = parsedArgs.ManifestResources.Single();
Assert.Null(resourceDescription.FileName); // since embedded
Assert.Equal("a", resourceDescription.ResourceName);
parsedArgs = DefaultParse(new[] { "/res:b", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.DisplayHelp);
resourceDescription = parsedArgs.ManifestResources.Single();
Assert.Null(resourceDescription.FileName); // since embedded
Assert.Equal("b", resourceDescription.ResourceName);
parsedArgs = DefaultParse(new[] { "/linkresource:c", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.DisplayHelp);
resourceDescription = parsedArgs.ManifestResources.Single();
Assert.Equal("c", resourceDescription.FileName);
Assert.Equal("c", resourceDescription.ResourceName);
parsedArgs = DefaultParse(new[] { "/linkres:d", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.DisplayHelp);
resourceDescription = parsedArgs.ManifestResources.Single();
Assert.Equal("d", resourceDescription.FileName);
Assert.Equal("d", resourceDescription.ResourceName);
}
[Fact]
public void ManagedResourceOptions_SimpleErrors()
{
var parsedArgs = DefaultParse(new[] { "/resource:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:"));
parsedArgs = DefaultParse(new[] { "/resource: ", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/resource:"));
parsedArgs = DefaultParse(new[] { "/res", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res"));
parsedArgs = DefaultParse(new[] { "/RES+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/RES+"));
parsedArgs = DefaultParse(new[] { "/res-:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/res-:"));
parsedArgs = DefaultParse(new[] { "/linkresource:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:"));
parsedArgs = DefaultParse(new[] { "/linkresource: ", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/linkresource:"));
parsedArgs = DefaultParse(new[] { "/linkres", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres"));
parsedArgs = DefaultParse(new[] { "/linkRES+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkRES+"));
parsedArgs = DefaultParse(new[] { "/linkres-:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/linkres-:"));
}
[Fact]
public void Link_SimpleTests()
{
var parsedArgs = DefaultParse(new[] { "/link:a", "/link:b,,,,c", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
AssertEx.Equal(new[] { "a", "b", "c" },
parsedArgs.MetadataReferences.
Where((res) => res.Properties.EmbedInteropTypes).
Select((res) => res.Reference));
parsedArgs = DefaultParse(new[] { "/Link: ,,, b ,,", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
AssertEx.Equal(new[] { " b " },
parsedArgs.MetadataReferences.
Where((res) => res.Properties.EmbedInteropTypes).
Select((res) => res.Reference));
parsedArgs = DefaultParse(new[] { "/l:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/l:"));
parsedArgs = DefaultParse(new[] { "/L", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/L"));
parsedArgs = DefaultParse(new[] { "/l+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/l+"));
parsedArgs = DefaultParse(new[] { "/link-:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/link-:"));
}
[ConditionalFact(typeof(WindowsOnly))]
public void Recurse_SimpleTests()
{
var dir = Temp.CreateDirectory();
var file1 = dir.CreateFile("a.cs");
var file2 = dir.CreateFile("b.cs");
var file3 = dir.CreateFile("c.txt");
var file4 = dir.CreateDirectory("d1").CreateFile("d.txt");
var file5 = dir.CreateDirectory("d2").CreateFile("e.cs");
file1.WriteAllText("");
file2.WriteAllText("");
file3.WriteAllText("");
file4.WriteAllText("");
file5.WriteAllText("");
var parsedArgs = DefaultParse(new[] { "/recurse:" + dir.ToString() + "\\*.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs", "{DIR}\\d2\\e.cs" },
parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}")));
parsedArgs = DefaultParse(new[] { "*.cs" }, dir.ToString());
parsedArgs.Errors.Verify();
AssertEx.Equal(new[] { "{DIR}\\a.cs", "{DIR}\\b.cs" },
parsedArgs.SourceFiles.Select((file) => file.Path.Replace(dir.ToString(), "{DIR}")));
parsedArgs = DefaultParse(new[] { "/reCURSE:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/reCURSE:"));
parsedArgs = DefaultParse(new[] { "/RECURSE: ", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/RECURSE:"));
parsedArgs = DefaultParse(new[] { "/recurse", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse"));
parsedArgs = DefaultParse(new[] { "/recurse+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse+"));
parsedArgs = DefaultParse(new[] { "/recurse-:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/recurse-:"));
CleanupAllGeneratedFiles(file1.Path);
CleanupAllGeneratedFiles(file2.Path);
CleanupAllGeneratedFiles(file3.Path);
CleanupAllGeneratedFiles(file4.Path);
CleanupAllGeneratedFiles(file5.Path);
}
[Fact]
public void Reference_SimpleTests()
{
var parsedArgs = DefaultParse(new[] { "/nostdlib", "/r:a", "/REFERENCE:b,,,,c", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
AssertEx.Equal(new[] { "a", "b", "c" },
parsedArgs.MetadataReferences.
Where((res) => !res.Properties.EmbedInteropTypes).
Select((res) => res.Reference));
parsedArgs = DefaultParse(new[] { "/Reference: ,,, b ,,", "/nostdlib", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
AssertEx.Equal(new[] { " b " },
parsedArgs.MetadataReferences.
Where((res) => !res.Properties.EmbedInteropTypes).
Select((res) => res.Reference));
parsedArgs = DefaultParse(new[] { "/Reference:a=b,,,", "/nostdlib", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("a", parsedArgs.MetadataReferences.Single().Properties.Aliases.Single());
Assert.Equal("b", parsedArgs.MetadataReferences.Single().Reference);
parsedArgs = DefaultParse(new[] { "/r:a=b,,,c", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_OneAliasPerReference).WithArguments("b,,,c"));
parsedArgs = DefaultParse(new[] { "/r:1=b", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadExternIdentifier).WithArguments("1"));
parsedArgs = DefaultParse(new[] { "/r:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/r:"));
parsedArgs = DefaultParse(new[] { "/R", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/R"));
parsedArgs = DefaultParse(new[] { "/reference+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference+"));
parsedArgs = DefaultParse(new[] { "/reference-:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/reference-:"));
}
[Fact]
public void Target_SimpleTests()
{
var parsedArgs = DefaultParse(new[] { "/target:exe", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind);
parsedArgs = DefaultParse(new[] { "/t:module", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind);
parsedArgs = DefaultParse(new[] { "/target:library", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind);
parsedArgs = DefaultParse(new[] { "/TARGET:winexe", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind);
parsedArgs = DefaultParse(new[] { "/target:appcontainerexe", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind);
parsedArgs = DefaultParse(new[] { "/target:winmdobj", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind);
parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind);
parsedArgs = DefaultParse(new[] { "/t", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t"));
parsedArgs = DefaultParse(new[] { "/target:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget));
parsedArgs = DefaultParse(new[] { "/target:xyz", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_InvalidTarget));
parsedArgs = DefaultParse(new[] { "/T+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+"));
parsedArgs = DefaultParse(new[] { "/TARGET-:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:"));
}
[Fact]
public void Target_SimpleTestsNoSource()
{
var parsedArgs = DefaultParse(new[] { "/target:exe" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// warning CS2008: No source files specified.
Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
// error CS1562: Outputs without source must have the /out option specified
Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));
Assert.Equal(OutputKind.ConsoleApplication, parsedArgs.CompilationOptions.OutputKind);
parsedArgs = DefaultParse(new[] { "/t:module" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// warning CS2008: No source files specified.
Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
// error CS1562: Outputs without source must have the /out option specified
Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));
Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind);
parsedArgs = DefaultParse(new[] { "/target:library" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// warning CS2008: No source files specified.
Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
// error CS1562: Outputs without source must have the /out option specified
Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));
Assert.Equal(OutputKind.DynamicallyLinkedLibrary, parsedArgs.CompilationOptions.OutputKind);
parsedArgs = DefaultParse(new[] { "/TARGET:winexe" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// warning CS2008: No source files specified.
Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
// error CS1562: Outputs without source must have the /out option specified
Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));
Assert.Equal(OutputKind.WindowsApplication, parsedArgs.CompilationOptions.OutputKind);
parsedArgs = DefaultParse(new[] { "/target:appcontainerexe" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// warning CS2008: No source files specified.
Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
// error CS1562: Outputs without source must have the /out option specified
Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));
Assert.Equal(OutputKind.WindowsRuntimeApplication, parsedArgs.CompilationOptions.OutputKind);
parsedArgs = DefaultParse(new[] { "/target:winmdobj" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// warning CS2008: No source files specified.
Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
// error CS1562: Outputs without source must have the /out option specified
Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));
Assert.Equal(OutputKind.WindowsRuntimeMetadata, parsedArgs.CompilationOptions.OutputKind);
parsedArgs = DefaultParse(new[] { "/target:winexe", "/T:exe", "/target:module" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// warning CS2008: No source files specified.
Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
// error CS1562: Outputs without source must have the /out option specified
Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));
Assert.Equal(OutputKind.NetModule, parsedArgs.CompilationOptions.OutputKind);
parsedArgs = DefaultParse(new[] { "/t" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2007: Unrecognized option: '/t'
Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/t").WithLocation(1, 1),
// warning CS2008: No source files specified.
Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
// error CS1562: Outputs without source must have the /out option specified
Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));
parsedArgs = DefaultParse(new[] { "/target:" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module'
Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1),
// warning CS2008: No source files specified.
Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
// error CS1562: Outputs without source must have the /out option specified
Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));
parsedArgs = DefaultParse(new[] { "/target:xyz" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2019: Invalid target type for /target: must specify 'exe', 'winexe', 'library', or 'module'
Diagnostic(ErrorCode.FTL_InvalidTarget).WithLocation(1, 1),
// warning CS2008: No source files specified.
Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
// error CS1562: Outputs without source must have the /out option specified
Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));
parsedArgs = DefaultParse(new[] { "/T+" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2007: Unrecognized option: '/T+'
Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/T+").WithLocation(1, 1),
// warning CS2008: No source files specified.
Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
// error CS1562: Outputs without source must have the /out option specified
Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));
parsedArgs = DefaultParse(new[] { "/TARGET-:" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2007: Unrecognized option: '/TARGET-:'
Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/TARGET-:").WithLocation(1, 1),
// warning CS2008: No source files specified.
Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
// error CS1562: Outputs without source must have the /out option specified
Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1));
}
[Fact]
public void ModuleManifest()
{
CSharpCommandLineArguments args = DefaultParse(new[] { "/win32manifest:blah", "/target:module", "a.cs" }, WorkingDirectory);
args.Errors.Verify(
// warning CS1927: Ignoring /win32manifest for module because it only applies to assemblies
Diagnostic(ErrorCode.WRN_CantHaveManifestForModule));
// Illegal, but not clobbered.
Assert.Equal("blah", args.Win32Manifest);
}
// The following test is failing in the Linux Debug test leg of CI.
// This issus is being tracked by https://github.com/dotnet/roslyn/issues/58077
[ConditionalFact(typeof(WindowsOrMacOSOnly))]
public void ArgumentParsing()
{
var sdkDirectory = SdkDirectory;
var parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.DisplayHelp);
Assert.True(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "a + b; c" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.DisplayHelp);
Assert.True(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/help" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.DisplayHelp);
Assert.False(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.DisplayVersion);
Assert.False(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:?" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.DisplayLangVersions);
Assert.False(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "//langversion:?" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify(
// error CS2001: Source file '//langversion:?' could not be found.
Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments("//langversion:?").WithLocation(1, 1)
);
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version", "c.csx" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.DisplayVersion);
Assert.True(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/version:something" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.DisplayVersion);
Assert.False(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/?" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.DisplayHelp);
Assert.False(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /langversion:6" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.DisplayHelp);
Assert.True(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/langversion:-1", "c.csx", }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify(
// error CS1617: Invalid option '-1' for /langversion. Use '/langversion:?' to list supported values.
Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("-1").WithLocation(1, 1));
Assert.False(parsedArgs.DisplayHelp);
Assert.Equal(1, parsedArgs.SourceFiles.Length);
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c.csx /r:s=d /r:d.dll" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.DisplayHelp);
Assert.True(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "@roslyn_test_non_existing_file" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify(
// error CS2011: Error opening response file 'D:\R0\Main\Binaries\Debug\dd'
Diagnostic(ErrorCode.ERR_OpenResponseFile).WithArguments(Path.Combine(WorkingDirectory, @"roslyn_test_non_existing_file")));
Assert.False(parsedArgs.DisplayHelp);
Assert.False(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "c /define:DEBUG" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.DisplayHelp);
Assert.True(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\\" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.DisplayHelp);
Assert.True(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r:d.dll", "c.csx" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.DisplayHelp);
Assert.True(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/define:goo", "c.csx" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify(
// error CS2007: Unrecognized option: '/define:goo'
Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/define:goo"));
Assert.False(parsedArgs.DisplayHelp);
Assert.True(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "\"/r d.dll\"" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.DisplayHelp);
Assert.True(parsedArgs.SourceFiles.Any());
parsedArgs = CSharpCommandLineParser.Script.Parse(new[] { "/r: d.dll", "a.cs" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.DisplayHelp);
Assert.True(parsedArgs.SourceFiles.Any());
}
[Theory]
[InlineData("iso-1", LanguageVersion.CSharp1)]
[InlineData("iso-2", LanguageVersion.CSharp2)]
[InlineData("1", LanguageVersion.CSharp1)]
[InlineData("1.0", LanguageVersion.CSharp1)]
[InlineData("2", LanguageVersion.CSharp2)]
[InlineData("2.0", LanguageVersion.CSharp2)]
[InlineData("3", LanguageVersion.CSharp3)]
[InlineData("3.0", LanguageVersion.CSharp3)]
[InlineData("4", LanguageVersion.CSharp4)]
[InlineData("4.0", LanguageVersion.CSharp4)]
[InlineData("5", LanguageVersion.CSharp5)]
[InlineData("5.0", LanguageVersion.CSharp5)]
[InlineData("6", LanguageVersion.CSharp6)]
[InlineData("6.0", LanguageVersion.CSharp6)]
[InlineData("7", LanguageVersion.CSharp7)]
[InlineData("7.0", LanguageVersion.CSharp7)]
[InlineData("7.1", LanguageVersion.CSharp7_1)]
[InlineData("7.2", LanguageVersion.CSharp7_2)]
[InlineData("7.3", LanguageVersion.CSharp7_3)]
[InlineData("8", LanguageVersion.CSharp8)]
[InlineData("8.0", LanguageVersion.CSharp8)]
[InlineData("9", LanguageVersion.CSharp9)]
[InlineData("9.0", LanguageVersion.CSharp9)]
[InlineData("preview", LanguageVersion.Preview)]
public void LangVersion_CanParseCorrectVersions(string value, LanguageVersion expectedVersion)
{
var parsedArgs = DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(expectedVersion, parsedArgs.ParseOptions.LanguageVersion);
Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion);
var scriptParsedArgs = ScriptParse(new[] { $"/langversion:{value}" }, WorkingDirectory);
scriptParsedArgs.Errors.Verify();
Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.LanguageVersion);
Assert.Equal(expectedVersion, scriptParsedArgs.ParseOptions.SpecifiedLanguageVersion);
}
[Theory]
[InlineData("6", "7", LanguageVersion.CSharp7)]
[InlineData("7", "6", LanguageVersion.CSharp6)]
[InlineData("7", "1", LanguageVersion.CSharp1)]
[InlineData("6", "iso-1", LanguageVersion.CSharp1)]
[InlineData("6", "iso-2", LanguageVersion.CSharp2)]
[InlineData("6", "default", LanguageVersion.Default)]
[InlineData("7", "default", LanguageVersion.Default)]
[InlineData("iso-2", "6", LanguageVersion.CSharp6)]
public void LangVersion_LatterVersionOverridesFormerOne(string formerValue, string latterValue, LanguageVersion expectedVersion)
{
var parsedArgs = DefaultParse(new[] { $"/langversion:{formerValue}", $"/langversion:{latterValue}", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(expectedVersion, parsedArgs.ParseOptions.SpecifiedLanguageVersion);
}
[Fact]
public void LangVersion_DefaultMapsCorrectly()
{
LanguageVersion defaultEffectiveVersion = LanguageVersion.Default.MapSpecifiedToEffectiveVersion();
Assert.NotEqual(LanguageVersion.Default, defaultEffectiveVersion);
var parsedArgs = DefaultParse(new[] { "/langversion:default", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion);
Assert.Equal(defaultEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion);
}
[Fact]
public void LangVersion_LatestMapsCorrectly()
{
LanguageVersion latestEffectiveVersion = LanguageVersion.Latest.MapSpecifiedToEffectiveVersion();
Assert.NotEqual(LanguageVersion.Latest, latestEffectiveVersion);
var parsedArgs = DefaultParse(new[] { "/langversion:latest", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(LanguageVersion.Latest, parsedArgs.ParseOptions.SpecifiedLanguageVersion);
Assert.Equal(latestEffectiveVersion, parsedArgs.ParseOptions.LanguageVersion);
}
[Fact]
public void LangVersion_NoValueSpecified()
{
var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(LanguageVersion.Default, parsedArgs.ParseOptions.SpecifiedLanguageVersion);
}
[Theory]
[InlineData("iso-3")]
[InlineData("iso1")]
[InlineData("8.1")]
[InlineData("10.1")]
[InlineData("11")]
[InlineData("1000")]
public void LangVersion_BadVersion(string value)
{
DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify(
// error CS1617: Invalid option 'XXX' for /langversion. Use '/langversion:?' to list supported values.
Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments(value).WithLocation(1, 1)
);
}
[Theory]
[InlineData("0")]
[InlineData("05")]
[InlineData("07")]
[InlineData("07.1")]
[InlineData("08")]
[InlineData("09")]
public void LangVersion_LeadingZeroes(string value)
{
DefaultParse(new[] { $"/langversion:{value}", "a.cs" }, WorkingDirectory).Errors.Verify(
// error CS8303: Specified language version 'XXX' cannot have leading zeroes
Diagnostic(ErrorCode.ERR_LanguageVersionCannotHaveLeadingZeroes).WithArguments(value).WithLocation(1, 1));
}
[Theory]
[InlineData("/langversion")]
[InlineData("/langversion:")]
[InlineData("/LANGversion:")]
public void LangVersion_NoVersion(string option)
{
DefaultParse(new[] { option, "a.cs" }, WorkingDirectory).Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for '/langversion:' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/langversion:").WithLocation(1, 1));
}
[Fact]
public void LangVersion_LangVersions()
{
var args = DefaultParse(new[] { "/langversion:?" }, WorkingDirectory);
args.Errors.Verify(
// warning CS2008: No source files specified.
Diagnostic(ErrorCode.WRN_NoSources).WithLocation(1, 1),
// error CS1562: Outputs without source must have the /out option specified
Diagnostic(ErrorCode.ERR_OutputNeedsName).WithLocation(1, 1)
);
Assert.True(args.DisplayLangVersions);
}
[Fact]
public void LanguageVersionAdded_Canary()
{
// When a new version is added, this test will break. This list must be checked:
// - update the "UpgradeProject" codefixer
// - update all the tests that call this canary
// - update MaxSupportedLangVersion (a relevant test should break when new version is introduced)
// - email release management to add to the release notes (see old example: https://github.com/dotnet/core/pull/1454)
AssertEx.SetEqual(new[] { "default", "1", "2", "3", "4", "5", "6", "7.0", "7.1", "7.2", "7.3", "8.0", "9.0", "10.0", "latest", "latestmajor", "preview" },
Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>().Select(v => v.ToDisplayString()));
// For minor versions and new major versions, the format should be "x.y", such as "7.1"
}
[Fact]
public void LanguageVersion_GetErrorCode()
{
var versions = Enum.GetValues(typeof(LanguageVersion))
.Cast<LanguageVersion>()
.Except(new[] {
LanguageVersion.Default,
LanguageVersion.Latest,
LanguageVersion.LatestMajor,
LanguageVersion.Preview
})
.Select(v => v.GetErrorCode());
var errorCodes = new[]
{
ErrorCode.ERR_FeatureNotAvailableInVersion1,
ErrorCode.ERR_FeatureNotAvailableInVersion2,
ErrorCode.ERR_FeatureNotAvailableInVersion3,
ErrorCode.ERR_FeatureNotAvailableInVersion4,
ErrorCode.ERR_FeatureNotAvailableInVersion5,
ErrorCode.ERR_FeatureNotAvailableInVersion6,
ErrorCode.ERR_FeatureNotAvailableInVersion7,
ErrorCode.ERR_FeatureNotAvailableInVersion7_1,
ErrorCode.ERR_FeatureNotAvailableInVersion7_2,
ErrorCode.ERR_FeatureNotAvailableInVersion7_3,
ErrorCode.ERR_FeatureNotAvailableInVersion8,
ErrorCode.ERR_FeatureNotAvailableInVersion9,
ErrorCode.ERR_FeatureNotAvailableInVersion10,
};
AssertEx.SetEqual(versions, errorCodes);
// The canary check is a reminder that this test needs to be updated when a language version is added
LanguageVersionAdded_Canary();
}
[Theory,
InlineData(LanguageVersion.CSharp1, LanguageVersion.CSharp1),
InlineData(LanguageVersion.CSharp2, LanguageVersion.CSharp2),
InlineData(LanguageVersion.CSharp3, LanguageVersion.CSharp3),
InlineData(LanguageVersion.CSharp4, LanguageVersion.CSharp4),
InlineData(LanguageVersion.CSharp5, LanguageVersion.CSharp5),
InlineData(LanguageVersion.CSharp6, LanguageVersion.CSharp6),
InlineData(LanguageVersion.CSharp7, LanguageVersion.CSharp7),
InlineData(LanguageVersion.CSharp7_1, LanguageVersion.CSharp7_1),
InlineData(LanguageVersion.CSharp7_2, LanguageVersion.CSharp7_2),
InlineData(LanguageVersion.CSharp7_3, LanguageVersion.CSharp7_3),
InlineData(LanguageVersion.CSharp8, LanguageVersion.CSharp8),
InlineData(LanguageVersion.CSharp9, LanguageVersion.CSharp9),
InlineData(LanguageVersion.CSharp10, LanguageVersion.CSharp10),
InlineData(LanguageVersion.CSharp10, LanguageVersion.LatestMajor),
InlineData(LanguageVersion.CSharp10, LanguageVersion.Latest),
InlineData(LanguageVersion.CSharp10, LanguageVersion.Default),
InlineData(LanguageVersion.Preview, LanguageVersion.Preview),
]
public void LanguageVersion_MapSpecifiedToEffectiveVersion(LanguageVersion expectedMappedVersion, LanguageVersion input)
{
Assert.Equal(expectedMappedVersion, input.MapSpecifiedToEffectiveVersion());
Assert.True(expectedMappedVersion.IsValid());
// The canary check is a reminder that this test needs to be updated when a language version is added
LanguageVersionAdded_Canary();
}
[Theory,
InlineData("iso-1", true, LanguageVersion.CSharp1),
InlineData("ISO-1", true, LanguageVersion.CSharp1),
InlineData("iso-2", true, LanguageVersion.CSharp2),
InlineData("1", true, LanguageVersion.CSharp1),
InlineData("1.0", true, LanguageVersion.CSharp1),
InlineData("2", true, LanguageVersion.CSharp2),
InlineData("2.0", true, LanguageVersion.CSharp2),
InlineData("3", true, LanguageVersion.CSharp3),
InlineData("3.0", true, LanguageVersion.CSharp3),
InlineData("4", true, LanguageVersion.CSharp4),
InlineData("4.0", true, LanguageVersion.CSharp4),
InlineData("5", true, LanguageVersion.CSharp5),
InlineData("5.0", true, LanguageVersion.CSharp5),
InlineData("05", false, LanguageVersion.Default),
InlineData("6", true, LanguageVersion.CSharp6),
InlineData("6.0", true, LanguageVersion.CSharp6),
InlineData("7", true, LanguageVersion.CSharp7),
InlineData("7.0", true, LanguageVersion.CSharp7),
InlineData("07", false, LanguageVersion.Default),
InlineData("7.1", true, LanguageVersion.CSharp7_1),
InlineData("7.2", true, LanguageVersion.CSharp7_2),
InlineData("7.3", true, LanguageVersion.CSharp7_3),
InlineData("8", true, LanguageVersion.CSharp8),
InlineData("8.0", true, LanguageVersion.CSharp8),
InlineData("9", true, LanguageVersion.CSharp9),
InlineData("9.0", true, LanguageVersion.CSharp9),
InlineData("10", true, LanguageVersion.CSharp10),
InlineData("10.0", true, LanguageVersion.CSharp10),
InlineData("08", false, LanguageVersion.Default),
InlineData("07.1", false, LanguageVersion.Default),
InlineData("default", true, LanguageVersion.Default),
InlineData("latest", true, LanguageVersion.Latest),
InlineData("latestmajor", true, LanguageVersion.LatestMajor),
InlineData("preview", true, LanguageVersion.Preview),
InlineData("latestpreview", false, LanguageVersion.Default),
InlineData(null, true, LanguageVersion.Default),
InlineData("bad", false, LanguageVersion.Default)]
public void LanguageVersion_TryParseDisplayString(string input, bool success, LanguageVersion expected)
{
Assert.Equal(success, LanguageVersionFacts.TryParse(input, out var version));
Assert.Equal(expected, version);
// The canary check is a reminder that this test needs to be updated when a language version is added
LanguageVersionAdded_Canary();
}
[Fact]
public void LanguageVersion_TryParseTurkishDisplayString()
{
var originalCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR", useUserOverride: false);
Assert.True(LanguageVersionFacts.TryParse("ISO-1", out var version));
Assert.Equal(LanguageVersion.CSharp1, version);
Thread.CurrentThread.CurrentCulture = originalCulture;
}
[Fact]
public void LangVersion_ListLangVersions()
{
var dir = Temp.CreateDirectory();
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/langversion:?" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
var expected = Enum.GetValues(typeof(LanguageVersion)).Cast<LanguageVersion>()
.Select(v => v.ToDisplayString());
var actual = outWriter.ToString();
var acceptableSurroundingChar = new[] { '\r', '\n', '(', ')', ' ' };
foreach (var version in expected)
{
if (version == "latest")
continue;
var foundIndex = actual.IndexOf(version);
Assert.True(foundIndex > 0, $"Missing version '{version}'");
Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex - 1]) >= 0);
Assert.True(Array.IndexOf(acceptableSurroundingChar, actual[foundIndex + version.Length]) >= 0);
}
}
[Fact]
[WorkItem(546961, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546961")]
public void Define()
{
var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
Assert.Equal(0, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count());
Assert.False(parsedArgs.Errors.Any());
parsedArgs = DefaultParse(new[] { "/d:GOO", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count());
Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames);
Assert.False(parsedArgs.Errors.Any());
parsedArgs = DefaultParse(new[] { "/d:GOO;BAR,ZIP", "a.cs" }, WorkingDirectory);
Assert.Equal(3, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count());
Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames);
Assert.Contains("BAR", parsedArgs.ParseOptions.PreprocessorSymbolNames);
Assert.Contains("ZIP", parsedArgs.ParseOptions.PreprocessorSymbolNames);
Assert.False(parsedArgs.Errors.Any());
parsedArgs = DefaultParse(new[] { "/d:GOO;4X", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.ParseOptions.PreprocessorSymbolNames.Count());
Assert.Contains("GOO", parsedArgs.ParseOptions.PreprocessorSymbolNames);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.WRN_DefineIdentifierRequired, parsedArgs.Errors.First().Code);
Assert.Equal("4X", parsedArgs.Errors.First().Arguments[0]);
IEnumerable<Diagnostic> diagnostics;
// The docs say /d:def1[;def2]
string compliant = "def1;def2;def3";
var expected = new[] { "def1", "def2", "def3" };
var parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(compliant, out diagnostics);
diagnostics.Verify();
Assert.Equal<string>(expected, parsed);
// Bug 17360: Dev11 allows for a terminating semicolon
var dev11Compliant = "def1;def2;def3;";
parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics);
diagnostics.Verify();
Assert.Equal<string>(expected, parsed);
// And comma
dev11Compliant = "def1,def2,def3,";
parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(dev11Compliant, out diagnostics);
diagnostics.Verify();
Assert.Equal<string>(expected, parsed);
// This breaks everything
var nonCompliant = "def1;;def2;";
parsed = CSharpCommandLineParser.ParseConditionalCompilationSymbols(nonCompliant, out diagnostics);
diagnostics.Verify(
// warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier
Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments(""));
Assert.Equal(new[] { "def1", "def2" }, parsed);
// Bug 17360
parsedArgs = DefaultParse(new[] { "/d:public1;public2;", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
}
[Fact]
public void Debug()
{
var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb;
var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.False(parsedArgs.EmitPdb);
Assert.False(parsedArgs.EmitPdbFile);
Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
parsedArgs = DefaultParse(new[] { "/debug-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.False(parsedArgs.EmitPdb);
Assert.False(parsedArgs.EmitPdbFile);
Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.True(parsedArgs.EmitPdb);
Assert.True(parsedArgs.EmitPdbFile);
Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
parsedArgs = DefaultParse(new[] { "/debug+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.True(parsedArgs.EmitPdb);
Assert.True(parsedArgs.EmitPdbFile);
Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
parsedArgs = DefaultParse(new[] { "/debug+", "/debug-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.False(parsedArgs.EmitPdb);
Assert.False(parsedArgs.EmitPdbFile);
Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
parsedArgs = DefaultParse(new[] { "/debug:full", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.True(parsedArgs.EmitPdb);
Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
parsedArgs = DefaultParse(new[] { "/debug:FULL", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.True(parsedArgs.EmitPdb);
Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll"));
parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.True(parsedArgs.EmitPdb);
Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
parsedArgs = DefaultParse(new[] { "/debug:portable", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.True(parsedArgs.EmitPdb);
Assert.Equal(DebugInformationFormat.PortablePdb, parsedArgs.EmitOptions.DebugInformationFormat);
Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll"));
parsedArgs = DefaultParse(new[] { "/debug:embedded", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.True(parsedArgs.EmitPdb);
Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat);
Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll"));
parsedArgs = DefaultParse(new[] { "/debug:PDBONLY", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.True(parsedArgs.EmitPdb);
Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
parsedArgs = DefaultParse(new[] { "/debug:full", "/debug:pdbonly", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.True(parsedArgs.EmitPdb);
Assert.Equal(parsedArgs.EmitOptions.DebugInformationFormat, platformPdbKind);
parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug:full", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.True(parsedArgs.EmitPdb);
Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat);
parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.False(parsedArgs.EmitPdb);
Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat);
parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.True(parsedArgs.EmitPdb);
Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat);
parsedArgs = DefaultParse(new[] { "/debug:pdbonly", "/debug-", "/debug+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.True(parsedArgs.EmitPdb);
Assert.Equal(platformPdbKind, parsedArgs.EmitOptions.DebugInformationFormat);
parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "/debug+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.True(parsedArgs.EmitPdb);
Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat);
parsedArgs = DefaultParse(new[] { "/debug:embedded", "/debug-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.DebugPlusMode);
Assert.False(parsedArgs.EmitPdb);
Assert.Equal(DebugInformationFormat.Embedded, parsedArgs.EmitOptions.DebugInformationFormat);
parsedArgs = DefaultParse(new[] { "/debug:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "debug"));
parsedArgs = DefaultParse(new[] { "/debug:+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("+"));
parsedArgs = DefaultParse(new[] { "/debug:invalid", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadDebugType).WithArguments("invalid"));
parsedArgs = DefaultParse(new[] { "/debug-:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/debug-:"));
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
public void Pdb()
{
var parsedArgs = DefaultParse(new[] { "/pdb:something", "a.cs" }, WorkingDirectory);
Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath);
Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll"));
Assert.False(parsedArgs.EmitPdbFile);
parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug:embedded", "a.cs" }, WorkingDirectory);
Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.PdbPath);
Assert.Equal(Path.Combine(WorkingDirectory, "something.pdb"), parsedArgs.GetPdbFilePath("a.dll"));
Assert.False(parsedArgs.EmitPdbFile);
parsedArgs = DefaultParse(new[] { "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Null(parsedArgs.PdbPath);
Assert.True(parsedArgs.EmitPdbFile);
Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll"));
parsedArgs = DefaultParse(new[] { "/pdb", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb"));
Assert.Equal(Path.Combine(WorkingDirectory, "a.pdb"), parsedArgs.GetPdbFilePath("a.dll"));
parsedArgs = DefaultParse(new[] { "/pdb:", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/pdb:"));
parsedArgs = DefaultParse(new[] { "/pdb:something", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
// temp: path changed
//parsedArgs = DefaultParse(new[] { "/debug", "/pdb:.x", "a.cs" }, baseDirectory);
//parsedArgs.Errors.Verify(
// // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
// Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x"));
parsedArgs = DefaultParse(new[] { @"/pdb:""""", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2005: Missing file specification for '/pdb:""' option
Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments(@"/pdb:""""").WithLocation(1, 1));
parsedArgs = DefaultParse(new[] { "/pdb:C:\\", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("C:\\"));
// Should preserve fully qualified paths
parsedArgs = DefaultParse(new[] { @"/pdb:C:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"C:\MyFolder\MyPdb.pdb", parsedArgs.PdbPath);
// Should preserve fully qualified paths
parsedArgs = DefaultParse(new[] { @"/pdb:c:\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"c:\MyPdb.pdb", parsedArgs.PdbPath);
parsedArgs = DefaultParse(new[] { @"/pdb:\MyFolder\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Path.Combine(Path.GetPathRoot(WorkingDirectory), @"MyFolder\MyPdb.pdb"), parsedArgs.PdbPath);
// Should handle quotes
parsedArgs = DefaultParse(new[] { @"/pdb:""C:\My Folder\MyPdb.pdb""", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"C:\My Folder\MyPdb.pdb", parsedArgs.PdbPath);
// Should expand partially qualified paths
parsedArgs = DefaultParse(new[] { @"/pdb:MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", WorkingDirectory), parsedArgs.PdbPath);
// Should expand partially qualified paths
parsedArgs = DefaultParse(new[] { @"/pdb:..\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
// Temp: Path info changed
// Assert.Equal(FileUtilities.ResolveRelativePath("MyPdb.pdb", "..\\", baseDirectory), parsedArgs.PdbPath);
parsedArgs = DefaultParse(new[] { @"/pdb:\\b", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b"));
Assert.Null(parsedArgs.PdbPath);
parsedArgs = DefaultParse(new[] { @"/pdb:\\b\OkFileName.pdb", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b\OkFileName.pdb"));
Assert.Null(parsedArgs.PdbPath);
parsedArgs = DefaultParse(new[] { @"/pdb:\\server\share\MyPdb.pdb", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"\\server\share\MyPdb.pdb", parsedArgs.PdbPath);
// invalid name:
parsedArgs = DefaultParse(new[] { "/pdb:a.b\0b", "/debug", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b"));
Assert.Null(parsedArgs.PdbPath);
parsedArgs = DefaultParse(new[] { "/pdb:a\uD800b.pdb", "/debug", "a.cs" }, WorkingDirectory);
//parsedArgs.Errors.Verify(
// Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.pdb"));
Assert.Null(parsedArgs.PdbPath);
// Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z'
parsedArgs = DefaultParse(new[] { @"/pdb:""a<>.pdb""", "a.vb" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name 'a<>.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.pdb"));
Assert.Null(parsedArgs.PdbPath);
parsedArgs = DefaultParse(new[] { "/pdb:.x", "/debug", "a.cs" }, WorkingDirectory);
//parsedArgs.Errors.Verify(
// // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
// Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x"));
Assert.Null(parsedArgs.PdbPath);
}
[Fact]
public void SourceLink()
{
var parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:portable", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink);
parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:embedded", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Path.Combine(WorkingDirectory, "sl.json"), parsedArgs.SourceLink);
parsedArgs = DefaultParse(new[] { @"/sourcelink:""s l.json""", "/debug:embedded", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Path.Combine(WorkingDirectory, "s l.json"), parsedArgs.SourceLink);
parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:full", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug:pdbonly", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb));
parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "/debug+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { "/sourcelink:sl.json", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SourceLinkRequiresPdb));
}
[Fact]
public void SourceLink_EndToEnd_EmbeddedPortable()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("a.cs");
src.WriteAllText(@"class C { public static void Main() {} }");
var sl = dir.CreateFile("sl.json");
sl.WriteAllText(@"{ ""documents"" : {} }");
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:embedded", "/sourcelink:sl.json", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
var peStream = File.OpenRead(Path.Combine(dir.Path, "a.exe"));
using (var peReader = new PEReader(peStream))
{
var entry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb);
using (var mdProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry))
{
var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob();
AssertEx.Equal(File.ReadAllBytes(sl.Path), blob);
}
}
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
}
[Fact]
public void SourceLink_EndToEnd_Portable()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("a.cs");
src.WriteAllText(@"class C { public static void Main() {} }");
var sl = dir.CreateFile("sl.json");
sl.WriteAllText(@"{ ""documents"" : {} }");
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:portable", "/sourcelink:sl.json", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb"));
using (var mdProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream))
{
var blob = mdProvider.GetMetadataReader().GetSourceLinkBlob();
AssertEx.Equal(File.ReadAllBytes(sl.Path), blob);
}
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
}
[Fact]
public void SourceLink_EndToEnd_Windows()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("a.cs");
src.WriteAllText(@"class C { public static void Main() {} }");
var sl = dir.CreateFile("sl.json");
byte[] slContent = Encoding.UTF8.GetBytes(@"{ ""documents"" : {} }");
sl.WriteAllBytes(slContent);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/debug:full", "/sourcelink:sl.json", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
var pdbStream = File.OpenRead(Path.Combine(dir.Path, "a.pdb"));
var actualData = PdbValidation.GetSourceLinkData(pdbStream);
AssertEx.Equal(slContent, actualData);
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
}
[Fact]
public void Embed()
{
var parsedArgs = DefaultParse(new[] { "a.cs " }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Empty(parsedArgs.EmbeddedFiles);
parsedArgs = DefaultParse(new[] { "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
AssertEx.Equal(parsedArgs.SourceFiles, parsedArgs.EmbeddedFiles);
AssertEx.Equal(
new[] { "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)),
parsedArgs.EmbeddedFiles.Select(f => f.Path));
parsedArgs = DefaultParse(new[] { "/embed:a.cs", "/embed:b.cs", "/debug:embedded", "a.cs", "b.cs", "c.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
AssertEx.Equal(
new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)),
parsedArgs.EmbeddedFiles.Select(f => f.Path));
parsedArgs = DefaultParse(new[] { "/embed:a.cs;b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
AssertEx.Equal(
new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)),
parsedArgs.EmbeddedFiles.Select(f => f.Path));
parsedArgs = DefaultParse(new[] { "/embed:a.cs,b.cs", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
AssertEx.Equal(
new[] { "a.cs", "b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)),
parsedArgs.EmbeddedFiles.Select(f => f.Path));
parsedArgs = DefaultParse(new[] { @"/embed:""a,b.cs""", "/debug:portable", "a,b.cs", "c.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
AssertEx.Equal(
new[] { "a,b.cs" }.Select(f => Path.Combine(WorkingDirectory, f)),
parsedArgs.EmbeddedFiles.Select(f => f.Path));
parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/embed", "/debug:portable", "a.cs", "b.cs", "c.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(); ;
AssertEx.Equal(
new[] { "a.txt", "a.cs", "b.cs", "c.cs" }.Select(f => Path.Combine(WorkingDirectory, f)),
parsedArgs.EmbeddedFiles.Select(f => f.Path));
parsedArgs = DefaultParse(new[] { "/embed", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb));
parsedArgs = DefaultParse(new[] { "/embed:a.txt", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb));
parsedArgs = DefaultParse(new[] { "/embed", "/debug-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb));
parsedArgs = DefaultParse(new[] { "/embed:a.txt", "/debug-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_CannotEmbedWithoutPdb));
parsedArgs = DefaultParse(new[] { "/embed", "/debug:full", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { "/embed", "/debug:pdbonly", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { "/embed", "/debug+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
}
[Theory]
[InlineData("/debug:portable", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })]
[InlineData("/debug:portable", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })]
[InlineData("/debug:portable", "/embed:embed2.cs", new[] { "embed2.cs" })]
[InlineData("/debug:portable", "/embed:embed.xyz", new[] { "embed.xyz" })]
[InlineData("/debug:embedded", "/embed", new[] { "embed.cs", "embed2.cs", "embed.xyz" })]
[InlineData("/debug:embedded", "/embed:embed.cs", new[] { "embed.cs", "embed.xyz" })]
[InlineData("/debug:embedded", "/embed:embed2.cs", new[] { "embed2.cs" })]
[InlineData("/debug:embedded", "/embed:embed.xyz", new[] { "embed.xyz" })]
public void Embed_EndToEnd_Portable(string debugSwitch, string embedSwitch, string[] expectedEmbedded)
{
// embed.cs: large enough to compress, has #line directives
const string embed_cs =
@"///////////////////////////////////////////////////////////////////////////////
class Program {
static void Main() {
#line 1 ""embed.xyz""
System.Console.WriteLine(""Hello, World"");
#line 3
System.Console.WriteLine(""Goodbye, World"");
}
}
///////////////////////////////////////////////////////////////////////////////";
// embed2.cs: small enough to not compress, no sequence points
const string embed2_cs =
@"class C
{
}";
// target of #line
const string embed_xyz =
@"print Hello, World
print Goodbye, World";
Assert.True(embed_cs.Length >= EmbeddedText.CompressionThreshold);
Assert.True(embed2_cs.Length < EmbeddedText.CompressionThreshold);
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("embed.cs");
var src2 = dir.CreateFile("embed2.cs");
var txt = dir.CreateFile("embed.xyz");
src.WriteAllText(embed_cs);
src2.WriteAllText(embed2_cs);
txt.WriteAllText(embed_xyz);
var expectedEmbeddedMap = new Dictionary<string, string>();
if (expectedEmbedded.Contains("embed.cs"))
{
expectedEmbeddedMap.Add(src.Path, embed_cs);
}
if (expectedEmbedded.Contains("embed2.cs"))
{
expectedEmbeddedMap.Add(src2.Path, embed2_cs);
}
if (expectedEmbedded.Contains("embed.xyz"))
{
expectedEmbeddedMap.Add(txt.Path, embed_xyz);
}
var output = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", debugSwitch, embedSwitch, "embed.cs", "embed2.cs" });
int exitCode = csc.Run(output);
Assert.Equal("", output.ToString().Trim());
Assert.Equal(0, exitCode);
switch (debugSwitch)
{
case "/debug:embedded":
ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: true);
break;
case "/debug:portable":
ValidateEmbeddedSources_Portable(expectedEmbeddedMap, dir, isEmbeddedPdb: false);
break;
case "/debug:full":
ValidateEmbeddedSources_Windows(expectedEmbeddedMap, dir);
break;
}
Assert.Empty(expectedEmbeddedMap);
CleanupAllGeneratedFiles(src.Path);
}
private static void ValidateEmbeddedSources_Portable(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir, bool isEmbeddedPdb)
{
using (var peReader = new PEReader(File.OpenRead(Path.Combine(dir.Path, "embed.exe"))))
{
var entry = peReader.ReadDebugDirectory().SingleOrDefault(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb);
Assert.Equal(isEmbeddedPdb, entry.DataSize > 0);
using (var mdProvider = isEmbeddedPdb ?
peReader.ReadEmbeddedPortablePdbDebugDirectoryData(entry) :
MetadataReaderProvider.FromPortablePdbStream(File.OpenRead(Path.Combine(dir.Path, "embed.pdb"))))
{
var mdReader = mdProvider.GetMetadataReader();
foreach (var handle in mdReader.Documents)
{
var doc = mdReader.GetDocument(handle);
var docPath = mdReader.GetString(doc.Name);
SourceText embeddedSource = mdReader.GetEmbeddedSource(handle);
if (embeddedSource == null)
{
continue;
}
Assert.Equal(expectedEmbeddedMap[docPath], embeddedSource.ToString());
Assert.True(expectedEmbeddedMap.Remove(docPath));
}
}
}
}
private static void ValidateEmbeddedSources_Windows(Dictionary<string, string> expectedEmbeddedMap, TempDirectory dir)
{
ISymUnmanagedReader5 symReader = null;
try
{
symReader = SymReaderFactory.CreateReader(File.OpenRead(Path.Combine(dir.Path, "embed.pdb")));
foreach (var doc in symReader.GetDocuments())
{
var docPath = doc.GetName();
var sourceBlob = doc.GetEmbeddedSource();
if (sourceBlob.Array == null)
{
continue;
}
var sourceStr = Encoding.UTF8.GetString(sourceBlob.Array, sourceBlob.Offset, sourceBlob.Count);
Assert.Equal(expectedEmbeddedMap[docPath], sourceStr);
Assert.True(expectedEmbeddedMap.Remove(docPath));
}
}
catch
{
symReader?.Dispose();
}
}
private static void ValidateWrittenSources(Dictionary<string, Dictionary<string, string>> expectedFilesMap, Encoding encoding = null)
{
foreach ((var dirPath, var fileMap) in expectedFilesMap.ToArray())
{
foreach (var file in Directory.GetFiles(dirPath))
{
var name = Path.GetFileName(file);
var content = File.ReadAllText(file, encoding ?? Encoding.UTF8);
Assert.Equal(fileMap[name], content);
Assert.True(fileMap.Remove(name));
}
Assert.Empty(fileMap);
Assert.True(expectedFilesMap.Remove(dirPath));
}
Assert.Empty(expectedFilesMap);
}
[Fact]
public void Optimize()
{
var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(new CSharpCompilationOptions(OutputKind.ConsoleApplication).OptimizationLevel, parsedArgs.CompilationOptions.OptimizationLevel);
parsedArgs = DefaultParse(new[] { "/optimize-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel);
parsedArgs = DefaultParse(new[] { "/optimize", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel);
parsedArgs = DefaultParse(new[] { "/optimize+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel);
parsedArgs = DefaultParse(new[] { "/optimize+", "/optimize-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel);
parsedArgs = DefaultParse(new[] { "/optimize:+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:+"));
parsedArgs = DefaultParse(new[] { "/optimize:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize:"));
parsedArgs = DefaultParse(new[] { "/optimize-:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/optimize-:"));
parsedArgs = DefaultParse(new[] { "/o-", "a.cs" }, WorkingDirectory);
Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel);
parsedArgs = DefaultParse(new string[] { "/o", "a.cs" }, WorkingDirectory);
Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel);
parsedArgs = DefaultParse(new string[] { "/o+", "a.cs" }, WorkingDirectory);
Assert.Equal(OptimizationLevel.Release, parsedArgs.CompilationOptions.OptimizationLevel);
parsedArgs = DefaultParse(new string[] { "/o+", "/optimize-", "a.cs" }, WorkingDirectory);
Assert.Equal(OptimizationLevel.Debug, parsedArgs.CompilationOptions.OptimizationLevel);
parsedArgs = DefaultParse(new string[] { "/o:+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:+"));
parsedArgs = DefaultParse(new string[] { "/o:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o:"));
parsedArgs = DefaultParse(new string[] { "/o-:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/o-:"));
}
[Fact]
public void Deterministic()
{
var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.Deterministic);
parsedArgs = DefaultParse(new[] { "/deterministic+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.CompilationOptions.Deterministic);
parsedArgs = DefaultParse(new[] { "/deterministic", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.CompilationOptions.Deterministic);
parsedArgs = DefaultParse(new[] { "/deterministic-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.Deterministic);
}
[Fact]
public void ParseReferences()
{
var parsedArgs = DefaultParse(new string[] { "/r:goo.dll", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(2, parsedArgs.MetadataReferences.Length);
parsedArgs = DefaultParse(new string[] { "/r:goo.dll;", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(2, parsedArgs.MetadataReferences.Length);
Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference);
Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties);
Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference);
Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[1].Properties);
parsedArgs = DefaultParse(new string[] { @"/l:goo.dll", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(2, parsedArgs.MetadataReferences.Length);
Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference);
Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties);
Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference);
Assert.Equal(MetadataReferenceProperties.Assembly.WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[1].Properties);
parsedArgs = DefaultParse(new string[] { @"/addmodule:goo.dll", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(2, parsedArgs.MetadataReferences.Length);
Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference);
Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties);
Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference);
Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[1].Properties);
parsedArgs = DefaultParse(new string[] { @"/r:a=goo.dll", "/l:b=bar.dll", "/addmodule:c=mod.dll", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(4, parsedArgs.MetadataReferences.Length);
Assert.Equal(MscorlibFullPath, parsedArgs.MetadataReferences[0].Reference);
Assert.Equal(MetadataReferenceProperties.Assembly, parsedArgs.MetadataReferences[0].Properties);
Assert.Equal("goo.dll", parsedArgs.MetadataReferences[1].Reference);
Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "a" }), parsedArgs.MetadataReferences[1].Properties);
Assert.Equal("bar.dll", parsedArgs.MetadataReferences[2].Reference);
Assert.Equal(MetadataReferenceProperties.Assembly.WithAliases(new[] { "b" }).WithEmbedInteropTypes(true), parsedArgs.MetadataReferences[2].Properties);
Assert.Equal("c=mod.dll", parsedArgs.MetadataReferences[3].Reference);
Assert.Equal(MetadataReferenceProperties.Module, parsedArgs.MetadataReferences[3].Properties);
// TODO: multiple files, quotes, etc.
}
[Fact]
public void ParseAnalyzers()
{
var parsedArgs = DefaultParse(new string[] { @"/a:goo.dll", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(1, parsedArgs.AnalyzerReferences.Length);
Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath);
parsedArgs = DefaultParse(new string[] { @"/analyzer:goo.dll", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(1, parsedArgs.AnalyzerReferences.Length);
Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath);
parsedArgs = DefaultParse(new string[] { "/analyzer:\"goo.dll\"", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(1, parsedArgs.AnalyzerReferences.Length);
Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath);
parsedArgs = DefaultParse(new string[] { @"/a:goo.dll;bar.dll", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(2, parsedArgs.AnalyzerReferences.Length);
Assert.Equal("goo.dll", parsedArgs.AnalyzerReferences[0].FilePath);
Assert.Equal("bar.dll", parsedArgs.AnalyzerReferences[1].FilePath);
parsedArgs = DefaultParse(new string[] { @"/a:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/a:"));
parsedArgs = DefaultParse(new string[] { "/a", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/a"));
}
[Fact]
public void Analyzers_Missing()
{
string source = @"
class C
{
}
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/a:missing.dll", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim());
// Clean up temp files
CleanupAllGeneratedFiles(file.Path);
}
[Fact]
public void Analyzers_Empty()
{
string source = @"
class C
{
}
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + typeof(object).Assembly.Location, "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.DoesNotContain("warning", outWriter.ToString());
CleanupAllGeneratedFiles(file.Path);
}
private TempFile CreateRuleSetFile(string source)
{
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.ruleset");
file.WriteAllText(source);
return file;
}
[Fact]
public void RuleSetSwitchPositive()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
<Rule Id=""CA1013"" Action=""Warning"" />
<Rule Id=""CA1014"" Action=""None"" />
</Rules>
</RuleSet>
";
var file = CreateRuleSetFile(source);
var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath);
Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1012"));
Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1012"] == ReportDiagnostic.Error);
Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1013"));
Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1013"] == ReportDiagnostic.Warn);
Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions.ContainsKey("CA1014"));
Assert.True(parsedArgs.CompilationOptions.SpecificDiagnosticOptions["CA1014"] == ReportDiagnostic.Suppress);
Assert.True(parsedArgs.CompilationOptions.GeneralDiagnosticOption == ReportDiagnostic.Warn);
}
[Fact]
public void RuleSetSwitchQuoted()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
<Rule Id=""CA1013"" Action=""Warning"" />
<Rule Id=""CA1014"" Action=""None"" />
</Rules>
</RuleSet>
";
var file = CreateRuleSetFile(source);
var parsedArgs = DefaultParse(new string[] { @"/ruleset:" + "\"" + file.Path + "\"", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath);
}
[Fact]
public void RuleSetSwitchParseErrors()
{
var parsedArgs = DefaultParse(new string[] { @"/ruleset", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset"));
Assert.Null(parsedArgs.RuleSetPath);
parsedArgs = DefaultParse(new string[] { @"/ruleset:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "ruleset"));
Assert.Null(parsedArgs.RuleSetPath);
parsedArgs = DefaultParse(new string[] { @"/ruleset:blah", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah"), "File not found."));
Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah"), actual: parsedArgs.RuleSetPath);
parsedArgs = DefaultParse(new string[] { @"/ruleset:blah;blah.ruleset", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(Path.Combine(TempRoot.Root, "blah;blah.ruleset"), "File not found."));
Assert.Equal(expected: Path.Combine(TempRoot.Root, "blah;blah.ruleset"), actual: parsedArgs.RuleSetPath);
var file = CreateRuleSetFile("Random text");
parsedArgs = DefaultParse(new string[] { @"/ruleset:" + file.Path, "a.cs" }, WorkingDirectory);
//parsedArgs.Errors.Verify(
// Diagnostic(ErrorCode.ERR_CantReadRulesetFile).WithArguments(file.Path, "Data at the root level is invalid. Line 1, position 1."));
Assert.Equal(expected: file.Path, actual: parsedArgs.RuleSetPath);
var err = parsedArgs.Errors.Single();
Assert.Equal((int)ErrorCode.ERR_CantReadRulesetFile, err.Code);
Assert.Equal(2, err.Arguments.Count);
Assert.Equal(file.Path, (string)err.Arguments[0]);
var currentUICultureName = Thread.CurrentThread.CurrentUICulture.Name;
if (currentUICultureName.Length == 0 || currentUICultureName.StartsWith("en", StringComparison.OrdinalIgnoreCase))
{
Assert.Equal("Data at the root level is invalid. Line 1, position 1.", (string)err.Arguments[1]);
}
}
[WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")]
[Fact]
public void Analyzers_Found()
{
string source = @"
class C
{
}
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
// This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation.
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
// Diagnostic thrown
Assert.True(outWriter.ToString().Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared"));
// Diagnostic cannot be instantiated
Assert.True(outWriter.ToString().Contains("warning CS8032"));
CleanupAllGeneratedFiles(file.Path);
}
[Fact]
public void Analyzers_WithRuleSet()
{
string source = @"
class C
{
int x;
}
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""Warning01"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSetFile = CreateRuleSetFile(rulesetSource);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
// This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation.
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, "a.cs", "/ruleset:" + ruleSetFile.Path });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
// Diagnostic thrown as error.
Assert.True(outWriter.ToString().Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared"));
// Clean up temp files
CleanupAllGeneratedFiles(file.Path);
}
[WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")]
[Fact]
public void Analyzers_CommandLineOverridesRuleset1()
{
string source = @"
class C
{
}
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
</RuleSet>
";
var ruleSetFile = CreateRuleSetFile(rulesetSource);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
// This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation.
var csc = CreateCSharpCompiler(null, dir.Path,
new[] {
"/nologo", "/preferreduilang:en", "/t:library",
"/a:" + Assembly.GetExecutingAssembly().Location, "a.cs",
"/ruleset:" + ruleSetFile.Path, "/warnaserror+", "/nowarn:8032" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
// Diagnostic thrown as error: command line always overrides ruleset.
Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal);
outWriter = new StringWriter(CultureInfo.InvariantCulture);
csc = CreateCSharpCompiler(null, dir.Path,
new[] {
"/nologo", "/preferreduilang:en", "/t:library",
"/a:" + Assembly.GetExecutingAssembly().Location, "a.cs",
"/warnaserror+", "/ruleset:" + ruleSetFile.Path, "/nowarn:8032" });
exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
// Diagnostic thrown as error: command line always overrides ruleset.
Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", outWriter.ToString(), StringComparison.Ordinal);
// Clean up temp files
CleanupAllGeneratedFiles(file.Path);
}
[Fact]
[WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
public void RuleSet_GeneralCommandLineOptionOverridesGeneralRuleSetOption()
{
var dir = Temp.CreateDirectory();
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
</RuleSet>
";
var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);
var arguments = DefaultParse(
new[]
{
"/nologo",
"/t:library",
"/ruleset:Rules.ruleset",
"/warnaserror+",
"a.cs"
},
dir.Path);
var errors = arguments.Errors;
Assert.Empty(errors);
Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error);
}
[Fact]
[WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
public void RuleSet_GeneralWarnAsErrorPromotesWarningFromRuleSet()
{
var dir = Temp.CreateDirectory();
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""Test001"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);
var arguments = DefaultParse(
new[]
{
"/nologo",
"/t:library",
"/ruleset:Rules.ruleset",
"/warnaserror+",
"a.cs"
},
dir.Path);
var errors = arguments.Errors;
Assert.Empty(errors);
Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error);
Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error);
}
[Fact]
[WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
public void RuleSet_GeneralWarnAsErrorDoesNotPromoteInfoFromRuleSet()
{
var dir = Temp.CreateDirectory();
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""Test001"" Action=""Info"" />
</Rules>
</RuleSet>
";
var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);
var arguments = DefaultParse(
new[]
{
"/nologo",
"/t:library",
"/ruleset:Rules.ruleset",
"/warnaserror+",
"a.cs"
},
dir.Path);
var errors = arguments.Errors;
Assert.Empty(errors);
Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error);
Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Info);
}
[Fact]
[WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
public void RuleSet_SpecificWarnAsErrorPromotesInfoFromRuleSet()
{
var dir = Temp.CreateDirectory();
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""Test001"" Action=""Info"" />
</Rules>
</RuleSet>
";
var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);
var arguments = DefaultParse(
new[]
{
"/nologo",
"/t:library",
"/ruleset:Rules.ruleset",
"/warnaserror+:Test001",
"a.cs"
},
dir.Path);
var errors = arguments.Errors;
Assert.Empty(errors);
Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default);
Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Error);
}
[Fact]
[WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
public void RuleSet_GeneralWarnAsErrorMinusResetsRules()
{
var dir = Temp.CreateDirectory();
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""Test001"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);
var arguments = DefaultParse(
new[]
{
"/nologo",
"/t:library",
"/ruleset:Rules.ruleset",
"/warnaserror+",
"/warnaserror-",
"a.cs"
},
dir.Path);
var errors = arguments.Errors;
Assert.Empty(errors);
Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default);
Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn);
}
[Fact]
[WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
public void RuleSet_SpecificWarnAsErrorMinusResetsRules()
{
var dir = Temp.CreateDirectory();
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""Test001"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);
var arguments = DefaultParse(
new[]
{
"/nologo",
"/t:library",
"/ruleset:Rules.ruleset",
"/warnaserror+",
"/warnaserror-:Test001",
"a.cs"
},
dir.Path);
var errors = arguments.Errors;
Assert.Empty(errors);
Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Error);
Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn);
}
[Fact]
[WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
public void RuleSet_SpecificWarnAsErrorMinusDefaultsRuleNotInRuleSet()
{
var dir = Temp.CreateDirectory();
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""Test001"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);
var arguments = DefaultParse(
new[]
{
"/nologo",
"/t:library",
"/ruleset:Rules.ruleset",
"/warnaserror+:Test002",
"/warnaserror-:Test002",
"a.cs"
},
dir.Path);
var errors = arguments.Errors;
Assert.Empty(errors);
Assert.Equal(actual: arguments.CompilationOptions.GeneralDiagnosticOption, expected: ReportDiagnostic.Default);
Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"], expected: ReportDiagnostic.Warn);
Assert.Equal(actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test002"], expected: ReportDiagnostic.Default);
}
[Fact]
[WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
public void NoWarn_SpecificNoWarnOverridesRuleSet()
{
var dir = Temp.CreateDirectory();
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""Test001"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);
var arguments = DefaultParse(
new[]
{
"/nologo",
"/t:library",
"/ruleset:Rules.ruleset",
"/nowarn:Test001",
"a.cs"
},
dir.Path);
var errors = arguments.Errors;
Assert.Empty(errors);
Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count);
Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]);
}
[Fact]
[WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
public void NoWarn_SpecificNoWarnOverridesGeneralWarnAsError()
{
var dir = Temp.CreateDirectory();
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""Test001"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);
var arguments = DefaultParse(
new[]
{
"/nologo",
"/t:library",
"/ruleset:Rules.ruleset",
"/warnaserror+",
"/nowarn:Test001",
"a.cs"
},
dir.Path);
var errors = arguments.Errors;
Assert.Empty(errors);
Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count);
Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]);
}
[Fact]
[WorkItem(468, "https://github.com/dotnet/roslyn/issues/468")]
public void NoWarn_SpecificNoWarnOverridesSpecificWarnAsError()
{
var dir = Temp.CreateDirectory();
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""Test001"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSetFile = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);
var arguments = DefaultParse(
new[]
{
"/nologo",
"/t:library",
"/ruleset:Rules.ruleset",
"/nowarn:Test001",
"/warnaserror+:Test001",
"a.cs"
},
dir.Path);
var errors = arguments.Errors;
Assert.Empty(errors);
Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(expected: 1, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count);
Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]);
}
[Fact]
[WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")]
public void NoWarn_Nullable()
{
var dir = Temp.CreateDirectory();
var arguments = DefaultParse(
new[]
{
"/nologo",
"/t:library",
"/nowarn:nullable",
"a.cs"
},
dir.Path);
var errors = arguments.Errors;
Assert.Empty(errors);
Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count);
foreach (string warning in ErrorFacts.NullableWarnings)
{
Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]);
}
Assert.Equal(expected: ReportDiagnostic.Suppress,
actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]);
Assert.Equal(expected: ReportDiagnostic.Suppress,
actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]);
}
[Fact]
[WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")]
public void NoWarn_Nullable_Capitalization()
{
var dir = Temp.CreateDirectory();
var arguments = DefaultParse(
new[]
{
"/nologo",
"/t:library",
"/nowarn:NullABLE",
"a.cs"
},
dir.Path);
var errors = arguments.Errors;
Assert.Empty(errors);
Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count);
foreach (string warning in ErrorFacts.NullableWarnings)
{
Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]);
}
Assert.Equal(expected: ReportDiagnostic.Suppress,
actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]);
Assert.Equal(expected: ReportDiagnostic.Suppress,
actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]);
}
[Fact]
[WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")]
public void NoWarn_Nullable_MultipleArguments()
{
var dir = Temp.CreateDirectory();
var arguments = DefaultParse(
new[]
{
"/nologo",
"/t:library",
"/nowarn:nullable,Test001",
"a.cs"
},
dir.Path);
var errors = arguments.Errors;
Assert.Empty(errors);
Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 3, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count);
foreach (string warning in ErrorFacts.NullableWarnings)
{
Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]);
}
Assert.Equal(expected: ReportDiagnostic.Suppress, actual: arguments.CompilationOptions.SpecificDiagnosticOptions["Test001"]);
Assert.Equal(expected: ReportDiagnostic.Suppress,
actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]);
Assert.Equal(expected: ReportDiagnostic.Suppress,
actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]);
}
[Fact]
[WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")]
public void WarnAsError_Nullable()
{
var dir = Temp.CreateDirectory();
var arguments = DefaultParse(
new[]
{
"/nologo",
"/t:library",
"/warnaserror:nullable",
"a.cs"
},
dir.Path);
var errors = arguments.Errors;
Assert.Empty(errors);
Assert.Equal(expected: ReportDiagnostic.Default, actual: arguments.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(expected: ErrorFacts.NullableWarnings.Count + 2, actual: arguments.CompilationOptions.SpecificDiagnosticOptions.Count);
foreach (string warning in ErrorFacts.NullableWarnings)
{
Assert.Equal(expected: ReportDiagnostic.Error, actual: arguments.CompilationOptions.SpecificDiagnosticOptions[warning]);
}
Assert.Equal(expected: ReportDiagnostic.Error,
actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation)]);
Assert.Equal(expected: ReportDiagnostic.Error,
actual: arguments.CompilationOptions.SpecificDiagnosticOptions[MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode)]);
}
[WorkItem(912906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912906")]
[Fact]
public void Analyzers_CommandLineOverridesRuleset2()
{
string source = @"
class C
{
}
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
string rulesetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""Warning01"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSetFile = CreateRuleSetFile(rulesetSource);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
// This assembly has a MockAbstractDiagnosticAnalyzer type which should get run by this compilation.
var csc = CreateCSharpCompiler(null, dir.Path,
new[] {
"/nologo", "/t:library",
"/a:" + Assembly.GetExecutingAssembly().Location, "a.cs",
"/ruleset:" + ruleSetFile.Path, "/warn:0" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
// Diagnostic suppressed: commandline always overrides ruleset.
Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal);
outWriter = new StringWriter(CultureInfo.InvariantCulture);
csc = CreateCSharpCompiler(null, dir.Path,
new[] {
"/nologo", "/t:library",
"/a:" + Assembly.GetExecutingAssembly().Location, "a.cs",
"/warn:0", "/ruleset:" + ruleSetFile.Path });
exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
// Diagnostic suppressed: commandline always overrides ruleset.
Assert.DoesNotContain("Warning01", outWriter.ToString(), StringComparison.Ordinal);
// Clean up temp files
CleanupAllGeneratedFiles(file.Path);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
public void DiagnosticFormatting()
{
string source = @"
using System;
class C
{
public static void Main()
{
Goo(0);
#line 10 ""c:\temp\a\1.cs""
Goo(1);
#line 20 ""C:\a\..\b.cs""
Goo(2);
#line 30 ""C:\a\../B.cs""
Goo(3);
#line 40 ""../b.cs""
Goo(4);
#line 50 ""..\b.cs""
Goo(5);
#line 60 ""C:\X.cs""
Goo(6);
#line 70 ""C:\x.cs""
Goo(7);
#line 90 "" ""
Goo(9);
#line 100 ""C:\*.cs""
Goo(10);
#line 110 """"
Goo(11);
#line hidden
Goo(12);
#line default
Goo(13);
#line 140 ""***""
Goo(14);
}
}
";
var dir = Temp.CreateDirectory();
dir.CreateFile("a.cs").WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
// with /fullpaths off
string expected = @"
a.cs(8,13): error CS0103: The name 'Goo' does not exist in the current context
c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context
C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context
C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context
" + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context
" + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context
C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context
C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context
(90,7): error CS0103: The name 'Goo' does not exist in the current context
C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context
(110,7): error CS0103: The name 'Goo' does not exist in the current context
(112,13): error CS0103: The name 'Goo' does not exist in the current context
a.cs(32,13): error CS0103: The name 'Goo' does not exist in the current context
***(140,13): error CS0103: The name 'Goo' does not exist in the current context";
AssertEx.Equal(
expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries),
outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries),
itemSeparator: "\r\n");
// with /fullpaths on
outWriter = new StringWriter(CultureInfo.InvariantCulture);
csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/fullpaths", "a.cs" });
exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
expected = @"
" + Path.Combine(dir.Path, @"a.cs") + @"(8,13): error CS0103: The name 'Goo' does not exist in the current context
c:\temp\a\1.cs(10,13): error CS0103: The name 'Goo' does not exist in the current context
C:\b.cs(20,13): error CS0103: The name 'Goo' does not exist in the current context
C:\B.cs(30,13): error CS0103: The name 'Goo' does not exist in the current context
" + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(40,13): error CS0103: The name 'Goo' does not exist in the current context
" + Path.GetFullPath(Path.Combine(dir.Path, @"..\b.cs")) + @"(50,13): error CS0103: The name 'Goo' does not exist in the current context
C:\X.cs(60,13): error CS0103: The name 'Goo' does not exist in the current context
C:\x.cs(70,13): error CS0103: The name 'Goo' does not exist in the current context
(90,7): error CS0103: The name 'Goo' does not exist in the current context
C:\*.cs(100,7): error CS0103: The name 'Goo' does not exist in the current context
(110,7): error CS0103: The name 'Goo' does not exist in the current context
(112,13): error CS0103: The name 'Goo' does not exist in the current context
" + Path.Combine(dir.Path, @"a.cs") + @"(32,13): error CS0103: The name 'Goo' does not exist in the current context
***(140,13): error CS0103: The name 'Goo' does not exist in the current context";
AssertEx.Equal(
expected.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries),
outWriter.ToString().Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries),
itemSeparator: "\r\n");
}
[WorkItem(540891, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540891")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
public void ParseOut()
{
const string baseDirectory = @"C:\abc\def\baz";
var parsedArgs = DefaultParse(new[] { @"/out:""""", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name '' contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(""));
parsedArgs = DefaultParse(new[] { @"/out:", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2005: Missing file specification for '/out:' option
Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out:"));
parsedArgs = DefaultParse(new[] { @"/refout:", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2005: Missing file specification for '/refout:' option
Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/refout:"));
parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/refonly", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS8301: Do not use refout when using refonly.
Diagnostic(ErrorCode.ERR_NoRefOutWhenRefOnly).WithLocation(1, 1));
parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/link:b", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { "/refonly", "/link:b", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { "/refonly:incorrect", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2007: Unrecognized option: '/refonly:incorrect'
Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/refonly:incorrect").WithLocation(1, 1)
);
parsedArgs = DefaultParse(new[] { @"/refout:ref.dll", "/target:module", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS8302: Cannot compile net modules when using /refout or /refonly.
Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1)
);
parsedArgs = DefaultParse(new[] { @"/refonly", "/target:module", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS8302: Cannot compile net modules when using /refout or /refonly.
Diagnostic(ErrorCode.ERR_NoNetModuleOutputWhenRefOutOrRefOnly).WithLocation(1, 1)
);
// Dev11 reports CS2007: Unrecognized option: '/out'
parsedArgs = DefaultParse(new[] { @"/out", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2005: Missing file specification for '/out' option
Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/out"));
parsedArgs = DefaultParse(new[] { @"/out+", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/out+"));
// Should preserve fully qualified paths
parsedArgs = DefaultParse(new[] { @"/out:C:\MyFolder\MyBinary.dll", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("MyBinary", parsedArgs.CompilationName);
Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName);
Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName);
Assert.Equal(@"C:\MyFolder", parsedArgs.OutputDirectory);
Assert.Equal(@"C:\MyFolder\MyBinary.dll", parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName));
// Should handle quotes
parsedArgs = DefaultParse(new[] { @"/out:""C:\My Folder\MyBinary.dll""", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"MyBinary", parsedArgs.CompilationName);
Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName);
Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName);
Assert.Equal(@"C:\My Folder", parsedArgs.OutputDirectory);
// Should expand partially qualified paths
parsedArgs = DefaultParse(new[] { @"/out:MyBinary.dll", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("MyBinary", parsedArgs.CompilationName);
Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName);
Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName);
Assert.Equal(baseDirectory, parsedArgs.OutputDirectory);
Assert.Equal(Path.Combine(baseDirectory, "MyBinary.dll"), parsedArgs.GetOutputFilePath(parsedArgs.OutputFileName));
// Should expand partially qualified paths
parsedArgs = DefaultParse(new[] { @"/out:..\MyBinary.dll", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("MyBinary", parsedArgs.CompilationName);
Assert.Equal("MyBinary.dll", parsedArgs.OutputFileName);
Assert.Equal("MyBinary.dll", parsedArgs.CompilationOptions.ModuleName);
Assert.Equal(@"C:\abc\def", parsedArgs.OutputDirectory);
// not specified: exe
parsedArgs = DefaultParse(new[] { @"a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
Assert.Equal(baseDirectory, parsedArgs.OutputDirectory);
// not specified: dll
parsedArgs = DefaultParse(new[] { @"/target:library", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("a", parsedArgs.CompilationName);
Assert.Equal("a.dll", parsedArgs.OutputFileName);
Assert.Equal("a.dll", parsedArgs.CompilationOptions.ModuleName);
Assert.Equal(baseDirectory, parsedArgs.OutputDirectory);
// not specified: module
parsedArgs = DefaultParse(new[] { @"/target:module", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Null(parsedArgs.CompilationName);
Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName);
Assert.Equal(baseDirectory, parsedArgs.OutputDirectory);
// not specified: appcontainerexe
parsedArgs = DefaultParse(new[] { @"/target:appcontainerexe", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
Assert.Equal(baseDirectory, parsedArgs.OutputDirectory);
// not specified: winmdobj
parsedArgs = DefaultParse(new[] { @"/target:winmdobj", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("a", parsedArgs.CompilationName);
Assert.Equal("a.winmdobj", parsedArgs.OutputFileName);
Assert.Equal("a.winmdobj", parsedArgs.CompilationOptions.ModuleName);
Assert.Equal(baseDirectory, parsedArgs.OutputDirectory);
// drive-relative path:
char currentDrive = Directory.GetCurrentDirectory()[0];
parsedArgs = DefaultParse(new[] { currentDrive + @":a.cs", "b.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name 'D:a.cs' is contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.cs"));
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
Assert.Equal(baseDirectory, parsedArgs.OutputDirectory);
// UNC
parsedArgs = DefaultParse(new[] { @"/out:\\b", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b"));
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { @"/out:\\server\share\file.exe", "a.vb" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"\\server\share", parsedArgs.OutputDirectory);
Assert.Equal("file.exe", parsedArgs.OutputFileName);
Assert.Equal("file", parsedArgs.CompilationName);
Assert.Equal("file.exe", parsedArgs.CompilationOptions.ModuleName);
// invalid name:
parsedArgs = DefaultParse(new[] { "/out:a.b\0b", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b"));
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
// Temporary skip following scenarios because of the error message changed (path)
//parsedArgs = DefaultParse(new[] { "/out:a\uD800b.dll", "a.cs" }, baseDirectory);
//parsedArgs.Errors.Verify(
// // error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
// Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.dll"));
// Dev11 reports CS0016: Could not write to output file 'd:\Temp\q\a<>.z'
parsedArgs = DefaultParse(new[] { @"/out:""a<>.dll""", "a.vb" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name 'a<>.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.dll"));
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { @"/out:.exe", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe")
);
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { @"/t:exe", @"/out:.exe", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name '.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".exe")
);
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { @"/t:library", @"/out:.dll", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll")
);
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { @"/t:module", @"/out:.netmodule", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name '.netmodule' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".netmodule")
);
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { ".cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { @"/t:exe", ".cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { @"/t:library", ".cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name '.dll' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".dll")
);
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { @"/t:module", ".cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(".netmodule", parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationName);
Assert.Equal(".netmodule", parsedArgs.CompilationOptions.ModuleName);
}
[WorkItem(546012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546012")]
[WorkItem(546007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546007")]
[Fact]
public void ParseOut2()
{
var parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x"));
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { "/out:.x", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name '.x' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(".x"));
Assert.Null(parsedArgs.OutputFileName);
Assert.Null(parsedArgs.CompilationName);
Assert.Null(parsedArgs.CompilationOptions.ModuleName);
}
[Fact]
public void ParseInstrumentTestNames()
{
var parsedArgs = DefaultParse(SpecializedCollections.EmptyEnumerable<string>(), WorkingDirectory);
Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty));
parsedArgs = DefaultParse(new[] { @"/instrument", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument"));
Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty));
parsedArgs = DefaultParse(new[] { @"/instrument:""""", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument"));
Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty));
parsedArgs = DefaultParse(new[] { @"/instrument:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument"));
Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty));
parsedArgs = DefaultParse(new[] { "/instrument:", "Test.Flag.Name", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for 'instrument' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "instrument"));
Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty));
parsedArgs = DefaultParse(new[] { "/instrument:InvalidOption", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption"));
Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty));
parsedArgs = DefaultParse(new[] { "/instrument:None", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("None"));
Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray<InstrumentationKind>.Empty));
parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,InvalidOption", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.ERR_InvalidInstrumentationKind).WithArguments("InvalidOption"));
Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
parsedArgs = DefaultParse(new[] { @"/instrument:""TestCoverage""", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
parsedArgs = DefaultParse(new[] { @"/instrument:""TESTCOVERAGE""", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage,TestCoverage", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
parsedArgs = DefaultParse(new[] { "/instrument:TestCoverage", "/instrument:TestCoverage", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.EmitOptions.InstrumentationKinds.SequenceEqual(ImmutableArray.Create(InstrumentationKind.TestCoverage)));
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
public void ParseDoc()
{
const string baseDirectory = @"C:\abc\def\baz";
var parsedArgs = DefaultParse(new[] { @"/doc:""""", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:"));
Assert.Null(parsedArgs.DocumentationPath);
parsedArgs = DefaultParse(new[] { @"/doc:", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for '/doc:' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc:"));
Assert.Null(parsedArgs.DocumentationPath);
// NOTE: no colon in error message '/doc'
parsedArgs = DefaultParse(new[] { @"/doc", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for '/doc' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/doc"));
Assert.Null(parsedArgs.DocumentationPath);
parsedArgs = DefaultParse(new[] { @"/doc+", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/doc+"));
Assert.Null(parsedArgs.DocumentationPath);
// Should preserve fully qualified paths
parsedArgs = DefaultParse(new[] { @"/doc:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.DocumentationPath);
Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode);
// Should handle quotes
parsedArgs = DefaultParse(new[] { @"/doc:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.DocumentationPath);
Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode);
// Should expand partially qualified paths
parsedArgs = DefaultParse(new[] { @"/doc:MyBinary.xml", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.DocumentationPath);
Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode);
// Should expand partially qualified paths
parsedArgs = DefaultParse(new[] { @"/doc:..\MyBinary.xml", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.DocumentationPath);
Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode);
// drive-relative path:
char currentDrive = Directory.GetCurrentDirectory()[0];
parsedArgs = DefaultParse(new[] { "/doc:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml"));
Assert.Null(parsedArgs.DocumentationPath);
Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect
// UNC
parsedArgs = DefaultParse(new[] { @"/doc:\\b", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b"));
Assert.Null(parsedArgs.DocumentationPath);
Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect
parsedArgs = DefaultParse(new[] { @"/doc:\\server\share\file.xml", "a.vb" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"\\server\share\file.xml", parsedArgs.DocumentationPath);
Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode);
// invalid name:
parsedArgs = DefaultParse(new[] { "/doc:a.b\0b", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b"));
Assert.Null(parsedArgs.DocumentationPath);
Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect
// Temp
// parsedArgs = DefaultParse(new[] { "/doc:a\uD800b.xml", "a.cs" }, baseDirectory);
// parsedArgs.Errors.Verify(
// Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a\uD800b.xml"));
// Assert.Null(parsedArgs.DocumentationPath);
// Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect
parsedArgs = DefaultParse(new[] { @"/doc:""a<>.xml""", "a.vb" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml"));
Assert.Null(parsedArgs.DocumentationPath);
Assert.Equal(DocumentationMode.Diagnose, parsedArgs.ParseOptions.DocumentationMode); //Even though the format was incorrect
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
public void ParseErrorLog()
{
const string baseDirectory = @"C:\abc\def\baz";
var parsedArgs = DefaultParse(new[] { @"/errorlog:""""", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:"));
Assert.Null(parsedArgs.ErrorLogOptions);
Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
parsedArgs = DefaultParse(new[] { @"/errorlog:", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog:' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog:"));
Assert.Null(parsedArgs.ErrorLogOptions);
Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
parsedArgs = DefaultParse(new[] { @"/errorlog", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<(error log option format>' for '/errorlog' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(CSharpCommandLineParser.ErrorLogOptionFormat, "/errorlog"));
Assert.Null(parsedArgs.ErrorLogOptions);
Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
// Should preserve fully qualified paths
parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path);
Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
// Escaped quote in the middle is an error
parsedArgs = DefaultParse(new[] { @"/errorlog:C:\""My Folder""\MyBinary.xml", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"C:""My Folder\MyBinary.xml").WithLocation(1, 1));
// Should handle quotes
parsedArgs = DefaultParse(new[] { @"/errorlog:""C:\My Folder\MyBinary.xml""", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"C:\My Folder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path);
Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
// Should expand partially qualified paths
parsedArgs = DefaultParse(new[] { @"/errorlog:MyBinary.xml", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Path.Combine(baseDirectory, "MyBinary.xml"), parsedArgs.ErrorLogOptions.Path);
Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
// Should expand partially qualified paths
parsedArgs = DefaultParse(new[] { @"/errorlog:..\MyBinary.xml", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"C:\abc\def\MyBinary.xml", parsedArgs.ErrorLogOptions.Path);
Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
// drive-relative path:
char currentDrive = Directory.GetCurrentDirectory()[0];
parsedArgs = DefaultParse(new[] { "/errorlog:" + currentDrive + @":a.xml", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name 'D:a.xml' is contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + ":a.xml"));
Assert.Null(parsedArgs.ErrorLogOptions);
Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
// UNC
parsedArgs = DefaultParse(new[] { @"/errorlog:\\b", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"\\b"));
Assert.Null(parsedArgs.ErrorLogOptions);
Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
parsedArgs = DefaultParse(new[] { @"/errorlog:\\server\share\file.xml", "a.vb" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"\\server\share\file.xml", parsedArgs.ErrorLogOptions.Path);
// invalid name:
parsedArgs = DefaultParse(new[] { "/errorlog:a.b\0b", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a.b\0b"));
Assert.Null(parsedArgs.ErrorLogOptions);
Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
parsedArgs = DefaultParse(new[] { @"/errorlog:""a<>.xml""", "a.vb" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2021: File name 'a<>.xml' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments("a<>.xml"));
Assert.Null(parsedArgs.ErrorLogOptions);
Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
// Parses SARIF version.
parsedArgs = DefaultParse(new[] { @"/errorlog:C:\MyFolder\MyBinary.xml,version=2", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"C:\MyFolder\MyBinary.xml", parsedArgs.ErrorLogOptions.Path);
Assert.Equal(SarifVersion.Sarif2, parsedArgs.ErrorLogOptions.SarifVersion);
Assert.True(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
// Invalid SARIF version.
string[] invalidSarifVersions = new string[] { @"C:\MyFolder\MyBinary.xml,version=1.0.0", @"C:\MyFolder\MyBinary.xml,version=2.1.0", @"C:\MyFolder\MyBinary.xml,version=42" };
foreach (string invalidSarifVersion in invalidSarifVersions)
{
parsedArgs = DefaultParse(new[] { $"/errorlog:{invalidSarifVersion}", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'.
Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(invalidSarifVersion, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat));
Assert.Null(parsedArgs.ErrorLogOptions);
Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
}
// Invalid errorlog qualifier.
const string InvalidErrorLogQualifier = @"C:\MyFolder\MyBinary.xml,invalid=42";
parsedArgs = DefaultParse(new[] { $"/errorlog:{InvalidErrorLogQualifier}", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,invalid=42' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'.
Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(InvalidErrorLogQualifier, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat));
Assert.Null(parsedArgs.ErrorLogOptions);
Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
// Too many errorlog qualifiers.
const string TooManyErrorLogQualifiers = @"C:\MyFolder\MyBinary.xml,version=2,version=2";
parsedArgs = DefaultParse(new[] { $"/errorlog:{TooManyErrorLogQualifiers}", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2046: Command-line syntax error: 'C:\MyFolder\MyBinary.xml,version=2,version=2' is not a valid value for the '/errorlog:' option. The value must be of the form '<file>[,version={1|1.0|2|2.1}]'.
Diagnostic(ErrorCode.ERR_BadSwitchValue).WithArguments(TooManyErrorLogQualifiers, "/errorlog:", CSharpCommandLineParser.ErrorLogOptionFormat));
Assert.Null(parsedArgs.ErrorLogOptions);
Assert.False(parsedArgs.CompilationOptions.ReportSuppressedDiagnostics);
}
[ConditionalFact(typeof(WindowsOnly))]
public void AppConfigParse()
{
const string baseDirectory = @"C:\abc\def\baz";
var parsedArgs = DefaultParse(new[] { @"/appconfig:""""", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:"));
Assert.Null(parsedArgs.AppConfigPath);
parsedArgs = DefaultParse(new[] { "/appconfig:", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig:' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig:"));
Assert.Null(parsedArgs.AppConfigPath);
parsedArgs = DefaultParse(new[] { "/appconfig", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing ':<text>' for '/appconfig' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments(":<text>", "/appconfig"));
Assert.Null(parsedArgs.AppConfigPath);
parsedArgs = DefaultParse(new[] { "/appconfig:a.exe.config", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"C:\abc\def\baz\a.exe.config", parsedArgs.AppConfigPath);
// If ParseDoc succeeds, all other possible AppConfig paths should succeed as well -- they both call ParseGenericFilePath
}
[Fact]
public void AppConfigBasic()
{
var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }");
var srcDirectory = Path.GetDirectoryName(srcFile.Path);
var appConfigFile = Temp.CreateFile().WriteAllText(
@"<?xml version=""1.0"" encoding=""utf-8"" ?>
<configuration>
<runtime>
<assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1"">
<supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/>
</assemblyBinding>
</runtime>
</configuration>");
var silverlight = Temp.CreateFile().WriteAllBytes(ProprietaryTestResources.silverlight_v5_0_5_0.System_v5_0_5_0_silverlight).Path;
var net4_0dll = Temp.CreateFile().WriteAllBytes(ResourcesNet451.System).Path;
// Test linking two appconfig dlls with simple src
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = CreateCSharpCompiler(null, srcDirectory,
new[] { "/nologo",
"/r:" + silverlight,
"/r:" + net4_0dll,
"/appconfig:" + appConfigFile.Path,
srcFile.Path }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(srcFile.Path);
CleanupAllGeneratedFiles(appConfigFile.Path);
}
[ConditionalFact(typeof(WindowsOnly))]
public void AppConfigBasicFail()
{
var srcFile = Temp.CreateFile().WriteAllText(@"class A { static void Main(string[] args) { } }");
var srcDirectory = Path.GetDirectoryName(srcFile.Path);
string root = Path.GetPathRoot(srcDirectory); // Make sure we pick a drive that exists and is plugged in to avoid 'Drive not ready'
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = CreateCSharpCompiler(null, srcDirectory,
new[] { "/nologo", "/preferreduilang:en",
$@"/appconfig:{root}DoesNotExist\NOwhere\bonobo.exe.config" ,
srcFile.Path }).Run(outWriter);
Assert.NotEqual(0, exitCode);
Assert.Equal($@"error CS7093: Cannot read config file '{root}DoesNotExist\NOwhere\bonobo.exe.config' -- 'Could not find a part of the path '{root}DoesNotExist\NOwhere\bonobo.exe.config'.'", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(srcFile.Path);
}
[ConditionalFact(typeof(WindowsOnly))]
public void ParseDocAndOut()
{
const string baseDirectory = @"C:\abc\def\baz";
// Can specify separate directories for binary and XML output.
var parsedArgs = DefaultParse(new[] { @"/doc:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.DocumentationPath);
Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory);
Assert.Equal("d.exe", parsedArgs.OutputFileName);
// XML does not fall back on output directory.
parsedArgs = DefaultParse(new[] { @"/doc:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.DocumentationPath);
Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory);
Assert.Equal("d.exe", parsedArgs.OutputFileName);
}
[ConditionalFact(typeof(WindowsOnly))]
public void ParseErrorLogAndOut()
{
const string baseDirectory = @"C:\abc\def\baz";
// Can specify separate directories for binary and error log output.
var parsedArgs = DefaultParse(new[] { @"/errorlog:a\b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"C:\abc\def\baz\a\b.xml", parsedArgs.ErrorLogOptions.Path);
Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory);
Assert.Equal("d.exe", parsedArgs.OutputFileName);
// XML does not fall back on output directory.
parsedArgs = DefaultParse(new[] { @"/errorlog:b.xml", @"/out:c\d.exe", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(@"C:\abc\def\baz\b.xml", parsedArgs.ErrorLogOptions.Path);
Assert.Equal(@"C:\abc\def\baz\c", parsedArgs.OutputDirectory);
Assert.Equal("d.exe", parsedArgs.OutputFileName);
}
[Fact]
public void ModuleAssemblyName()
{
var parsedArgs = DefaultParse(new[] { @"/target:module", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("goo", parsedArgs.CompilationName);
Assert.Equal("a.netmodule", parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { @"/target:library", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module'
Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule));
parsedArgs = DefaultParse(new[] { @"/target:exe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module'
Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule));
parsedArgs = DefaultParse(new[] { @"/target:winexe", "/moduleassemblyname:goo", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS0734: The /moduleassemblyname option may only be specified when building a target type of 'module'
Diagnostic(ErrorCode.ERR_AssemblyNameOnNonModule));
}
[Fact]
public void ModuleName()
{
var parsedArgs = DefaultParse(new[] { @"/target:module", "/modulename:goo", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { @"/target:library", "/modulename:bar", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("bar", parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:CommonLanguageRuntimeLibrary", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("CommonLanguageRuntimeLibrary", parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { @"/target:winexe", "/modulename:goo", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("goo", parsedArgs.CompilationOptions.ModuleName);
parsedArgs = DefaultParse(new[] { @"/target:exe", "/modulename:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for 'modulename' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "modulename").WithLocation(1, 1)
);
}
[Fact]
public void ModuleName001()
{
var dir = Temp.CreateDirectory();
var file1 = dir.CreateFile("a.cs");
file1.WriteAllText(@"
class c1
{
public static void Main(){}
}
");
var exeName = "aa.exe";
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/modulename:hocusPocus ", "/out:" + exeName + " ", file1.Path });
int exitCode = csc.Run(outWriter);
if (exitCode != 0)
{
Console.WriteLine(outWriter.ToString());
Assert.Equal(0, exitCode);
}
Assert.Equal(1, Directory.EnumerateFiles(dir.Path, exeName).Count());
using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, "aa.exe"))))
{
var peReader = metadata.Module.GetMetadataReader();
Assert.True(peReader.IsAssembly);
Assert.Equal("aa", peReader.GetString(peReader.GetAssemblyDefinition().Name));
Assert.Equal("hocusPocus", peReader.GetString(peReader.GetModuleDefinition().Name));
}
if (System.IO.File.Exists(exeName))
{
System.IO.File.Delete(exeName);
}
CleanupAllGeneratedFiles(file1.Path);
}
[Fact]
public void ParsePlatform()
{
var parsedArgs = DefaultParse(new[] { @"/platform:x64", "a.cs" }, WorkingDirectory);
Assert.False(parsedArgs.Errors.Any());
Assert.Equal(Platform.X64, parsedArgs.CompilationOptions.Platform);
parsedArgs = DefaultParse(new[] { @"/platform:X86", "a.cs" }, WorkingDirectory);
Assert.False(parsedArgs.Errors.Any());
Assert.Equal(Platform.X86, parsedArgs.CompilationOptions.Platform);
parsedArgs = DefaultParse(new[] { @"/platform:itanum", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_BadPlatformType, parsedArgs.Errors.First().Code);
Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform);
parsedArgs = DefaultParse(new[] { "/platform:itanium", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Platform.Itanium, parsedArgs.CompilationOptions.Platform);
parsedArgs = DefaultParse(new[] { "/platform:anycpu", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform);
parsedArgs = DefaultParse(new[] { "/platform:anycpu32bitpreferred", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Platform.AnyCpu32BitPreferred, parsedArgs.CompilationOptions.Platform);
parsedArgs = DefaultParse(new[] { "/platform:arm", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Platform.Arm, parsedArgs.CompilationOptions.Platform);
parsedArgs = DefaultParse(new[] { "/platform", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform"));
Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default
parsedArgs = DefaultParse(new[] { "/platform:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<string>' for 'platform' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<string>", "/platform:"));
Assert.Equal(Platform.AnyCpu, parsedArgs.CompilationOptions.Platform); //anycpu is default
}
[WorkItem(546016, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546016")]
[WorkItem(545997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545997")]
[WorkItem(546019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546019")]
[WorkItem(546029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546029")]
[Fact]
public void ParseBaseAddress()
{
var parsedArgs = DefaultParse(new[] { @"/baseaddress:x64", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code);
parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory);
Assert.False(parsedArgs.Errors.Any());
Assert.Equal(0x8000000000011111ul, parsedArgs.EmitOptions.BaseAddress);
parsedArgs = DefaultParse(new[] { @"/platform:x86", @"/baseaddress:0x8000000000011111", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code);
parsedArgs = DefaultParse(new[] { @"/baseaddress:", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_SwitchNeedsNumber, parsedArgs.Errors.First().Code);
parsedArgs = DefaultParse(new[] { @"/baseaddress:-23", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_BadBaseNumber, parsedArgs.Errors.First().Code);
parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:01777777777777777777777", "a.cs" }, WorkingDirectory);
Assert.Equal(ulong.MaxValue, parsedArgs.EmitOptions.BaseAddress);
parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0x0000000100000000", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { @"/platform:x64", @"/baseaddress:0xffff8000", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffffffff" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFFFFFF"));
parsedArgs = DefaultParse(new[] { "test.cs", "/platform:x86", "/baseaddress:0xffff8000" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000"));
parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xffff8000" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF8000"));
parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x86", "/baseaddress:0xffff7fff" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0xffff8000" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x100000000" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { "test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000"));
parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/platform:x64", "/baseaddress:0x10000000000000000" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0x10000000000000000"));
parsedArgs = DefaultParse(new[] { "C:\\test.cs", "/baseaddress:0xFFFF0000FFFF0000" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadBaseNumber).WithArguments("0xFFFF0000FFFF0000"));
}
[Fact]
public void ParseFileAlignment()
{
var parsedArgs = DefaultParse(new[] { @"/filealign:x64", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2024: Invalid file section alignment number 'x64'
Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("x64"));
parsedArgs = DefaultParse(new[] { @"/filealign:0x200", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(0x200, parsedArgs.EmitOptions.FileAlignment);
parsedArgs = DefaultParse(new[] { @"/filealign:512", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(512, parsedArgs.EmitOptions.FileAlignment);
parsedArgs = DefaultParse(new[] { @"/filealign:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2035: Command-line syntax error: Missing ':<number>' for 'filealign' option
Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("filealign"));
parsedArgs = DefaultParse(new[] { @"/filealign:-23", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2024: Invalid file section alignment number '-23'
Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("-23"));
parsedArgs = DefaultParse(new[] { @"/filealign:020000", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(8192, parsedArgs.EmitOptions.FileAlignment);
parsedArgs = DefaultParse(new[] { @"/filealign:0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2024: Invalid file section alignment number '0'
Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("0"));
parsedArgs = DefaultParse(new[] { @"/filealign:123", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2024: Invalid file section alignment number '123'
Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("123"));
}
[ConditionalFact(typeof(WindowsOnly))]
public void SdkPathAndLibEnvVariable()
{
var dir = Temp.CreateDirectory();
var lib1 = dir.CreateDirectory("lib1");
var lib2 = dir.CreateDirectory("lib2");
var lib3 = dir.CreateDirectory("lib3");
var sdkDirectory = SdkDirectory;
var parsedArgs = DefaultParse(new[] { @"/lib:lib1", @"/libpath:lib2", @"/libpaths:lib3", "a.cs" }, dir.Path, sdkDirectory: sdkDirectory);
AssertEx.Equal(new[]
{
sdkDirectory,
lib1.Path,
lib2.Path,
lib3.Path
}, parsedArgs.ReferencePaths);
}
[ConditionalFact(typeof(WindowsOnly))]
public void SdkPathAndLibEnvVariable_Errors()
{
var parsedArgs = DefaultParse(new[] { @"/lib:c:lib2", @"/lib:o:\sdk1", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// warning CS1668: Invalid search path 'c:lib2' specified in '/LIB option' -- 'path is too long or invalid'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"c:lib2", "/LIB option", "path is too long or invalid"),
// warning CS1668: Invalid search path 'o:\sdk1' specified in '/LIB option' -- 'directory does not exist'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\sdk1", "/LIB option", "directory does not exist"));
parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:;", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"),
// warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e:", "/LIB option", "path is too long or invalid"));
parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,.\Windows;e;", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// warning CS1668: Invalid search path '.\Windows' specified in '/LIB option' -- 'directory does not exist'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@".\Windows", "/LIB option", "directory does not exist"),
// warning CS1668: Invalid search path 'e' specified in '/LIB option' -- 'directory does not exist'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"e", "/LIB option", "directory does not exist"));
parsedArgs = DefaultParse(new[] { @"/lib:c:\Windows,o:\Windows;e:; ; ; ; ", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// warning CS1668: Invalid search path 'o:\Windows' specified in '/LIB option' -- 'directory does not exist'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(@"o:\Windows", "/LIB option", "directory does not exist"),
// warning CS1668: Invalid search path 'e:' specified in '/LIB option' -- 'path is too long or invalid'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("e:", "/LIB option", "path is too long or invalid"),
// warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"),
// warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"),
// warning CS1668: Invalid search path ' ' specified in '/LIB option' -- 'path is too long or invalid'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments(" ", "/LIB option", "path is too long or invalid"));
parsedArgs = DefaultParse(new[] { @"/lib", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib"));
parsedArgs = DefaultParse(new[] { @"/lib:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib"));
parsedArgs = DefaultParse(new[] { @"/lib+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/lib+"));
parsedArgs = DefaultParse(new[] { @"/lib: ", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<path list>", "lib"));
}
[Fact, WorkItem(546005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546005")]
public void SdkPathAndLibEnvVariable_Relative_csc()
{
var tempFolder = Temp.CreateDirectory();
var baseDirectory = tempFolder.ToString();
var subFolder = tempFolder.CreateDirectory("temp");
var subDirectory = subFolder.ToString();
var src = Temp.CreateFile("a.cs");
src.WriteAllText("public class C{}");
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, subDirectory, new[] { "/nologo", "/t:library", "/out:abc.xyz", src.ToString() }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString().Trim());
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/lib:temp", "/r:abc.xyz", "/t:library", src.ToString() }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(src.Path);
}
[Fact]
public void UnableWriteOutput()
{
var tempFolder = Temp.CreateDirectory();
var baseDirectory = tempFolder.ToString();
var subFolder = tempFolder.CreateDirectory("temp");
var src = Temp.CreateFile("a.cs");
src.WriteAllText("public class C{}");
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, baseDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", "/out:" + subFolder.ToString(), src.ToString() }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.True(outWriter.ToString().Trim().StartsWith("error CS2012: Cannot open '" + subFolder.ToString() + "' for writing -- '", StringComparison.Ordinal)); // Cannot create a file when that file already exists.
CleanupAllGeneratedFiles(src.Path);
}
[Fact]
public void ParseHighEntropyVA()
{
var parsedArgs = DefaultParse(new[] { @"/highentropyva", "a.cs" }, WorkingDirectory);
Assert.False(parsedArgs.Errors.Any());
Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace);
parsedArgs = DefaultParse(new[] { @"/highentropyva+", "a.cs" }, WorkingDirectory);
Assert.False(parsedArgs.Errors.Any());
Assert.True(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace);
parsedArgs = DefaultParse(new[] { @"/highentropyva-", "a.cs" }, WorkingDirectory);
Assert.False(parsedArgs.Errors.Any());
Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace);
parsedArgs = DefaultParse(new[] { @"/highentropyva:-", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace);
parsedArgs = DefaultParse(new[] { @"/highentropyva:", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal(EmitOptions.Default.HighEntropyVirtualAddressSpace, parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace);
//last one wins
parsedArgs = DefaultParse(new[] { @"/highenTROPyva+", @"/HIGHentropyva-", "a.cs" }, WorkingDirectory);
Assert.False(parsedArgs.Errors.Any());
Assert.False(parsedArgs.EmitOptions.HighEntropyVirtualAddressSpace);
}
[Fact]
public void Checked()
{
var parsedArgs = DefaultParse(new[] { @"/checked+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.CompilationOptions.CheckOverflow);
parsedArgs = DefaultParse(new[] { @"/checked-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.CheckOverflow);
parsedArgs = DefaultParse(new[] { @"/checked", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.CompilationOptions.CheckOverflow);
parsedArgs = DefaultParse(new[] { @"/checked-", @"/checked", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.CompilationOptions.CheckOverflow);
parsedArgs = DefaultParse(new[] { @"/checked:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checked:"));
}
[Fact]
public void Nullable()
{
var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.0. Please use language version '8.0' or greater.
Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:yes", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.0. Please use language version '8.0' or greater.
Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.0", "8.0").WithLocation(1, 1));
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1));
parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:yes", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'yes' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yes").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:eNable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:disablE", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Safeonly", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'Safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("Safeonly").WithLocation(1, 1)
);
parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)
);
parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)
);
parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1),
// error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1),
// error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", @"/nullable:safeonly", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1),
// error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:", "/langversion:7.3", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:yeS", "/langversion:7.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'yeS' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("yeS").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable+", "/langversion:7.3", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8630: Invalid 'nullable' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater.
Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable-", "/langversion:7.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable", "/langversion:7.3", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater.
Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:enable", "/langversion:7.3", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8630: Invalid 'nullable' value: 'Enabled' for C# 7.3. Please use language version '8.0' or greater.
Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Enable", "7.3", "8.0").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:disable", "/langversion:7.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:safeonly", "/langversion:7.3", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:8" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { "a.cs", "/langversion:7.3" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:""safeonly""", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonly' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonly").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:\""enable\""", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option '"enable"' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\"enable\"").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:\\disable\\", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option '\\disable\\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\\\disable\\\\").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:\\""enable\\""", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option '\enable\' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("\\enable\\").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:safeonlywarnings", "/langversion:7.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonlywarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlywarnings").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:SafeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'SafeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("SafeonlyWarnings").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:safeonlyWarnings", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'safeonlyWarnings' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("safeonlyWarnings").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:warnings", "/langversion:7.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8630: Invalid 'nullable' value: 'Warnings' for C# 7.0. Please use language version '8.0' or greater.
Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.0", "8.0").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", @"/nullable:Warnings", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Warnings", "/langversion:7.3", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater.
Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Warnings", "7.3", "8.0").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Warnings, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:annotations", "/langversion:7.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.0. Please use language version '8.0' or greater.
Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.0", "8.0").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable-", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable+", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable-", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable+", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for 'nullable' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "nullable").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:YES", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8636: Invalid option 'YES' for /nullable; must be 'disable', 'enable', 'warnings' or 'annotations'
Diagnostic(ErrorCode.ERR_BadNullableContextOption).WithArguments("YES").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:disable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Disable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:enable", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Enable, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", @"/nullable:Annotations", "/langversion:8", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions);
parsedArgs = DefaultParse(new[] { @"/nullable:Annotations", "/langversion:7.3", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS8630: Invalid 'nullable' value: 'Annotations' for C# 7.3. Please use language version '8.0' or greater.
Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("nullable", "Annotations", "7.3", "8.0").WithLocation(1, 1)
);
Assert.Equal(NullableContextOptions.Annotations, parsedArgs.CompilationOptions.NullableContextOptions);
}
[Fact]
public void Usings()
{
CSharpCommandLineArguments parsedArgs;
var sdkDirectory = SdkDirectory;
parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
AssertEx.Equal(new[] { "Goo.Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable());
parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo.Bar;Baz", "/using:System.Core;System" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
AssertEx.Equal(new[] { "Goo.Bar", "Baz", "System.Core", "System" }, parsedArgs.CompilationOptions.Usings.AsEnumerable());
parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:Goo;;Bar" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify();
AssertEx.Equal(new[] { "Goo", "Bar" }, parsedArgs.CompilationOptions.Usings.AsEnumerable());
parsedArgs = CSharpCommandLineParser.Script.Parse(new string[] { "/u:" }, WorkingDirectory, sdkDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<namespace>' for '/u:' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<namespace>", "/u:"));
}
[Fact]
public void WarningsErrors()
{
var parsedArgs = DefaultParse(new string[] { "/nowarn", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option
Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn"));
parsedArgs = DefaultParse(new string[] { "/nowarn:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2035: Command-line syntax error: Missing ':<number>' for 'nowarn' option
Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("nowarn"));
// Previous versions of the compiler used to report a warning (CS1691)
// whenever an unrecognized warning code was supplied via /nowarn or /warnaserror.
// We no longer generate a warning in such cases.
parsedArgs = DefaultParse(new string[] { "/nowarn:-1", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new string[] { "/nowarn:abc", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new string[] { "/warnaserror:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2035: Command-line syntax error: Missing ':<number>' for 'warnaserror' option
Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror"));
parsedArgs = DefaultParse(new string[] { "/warnaserror:-1", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new string[] { "/warnaserror:70000", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new string[] { "/warnaserror:abc", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new string[] { "/warnaserror+:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror+:' option
Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror+"));
parsedArgs = DefaultParse(new string[] { "/warnaserror-:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2035: Command-line syntax error: Missing ':<number>' for '/warnaserror-:' option
Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warnaserror-"));
parsedArgs = DefaultParse(new string[] { "/w", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2035: Command-line syntax error: Missing ':<number>' for '/w' option
Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w"));
parsedArgs = DefaultParse(new string[] { "/w:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2035: Command-line syntax error: Missing ':<number>' for '/w:' option
Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("w"));
parsedArgs = DefaultParse(new string[] { "/warn:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2035: Command-line syntax error: Missing ':<number>' for '/warn:' option
Diagnostic(ErrorCode.ERR_SwitchNeedsNumber).WithArguments("warn"));
parsedArgs = DefaultParse(new string[] { "/w:-1", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS1900: Warning level must be zero or greater
Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("w"));
parsedArgs = DefaultParse(new string[] { "/w:5", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new string[] { "/warn:-1", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS1900: Warning level must be zero or greater
Diagnostic(ErrorCode.ERR_BadWarningLevel).WithArguments("warn"));
parsedArgs = DefaultParse(new string[] { "/warn:5", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
// Previous versions of the compiler used to report a warning (CS1691)
// whenever an unrecognized warning code was supplied via /nowarn or /warnaserror.
// We no longer generate a warning in such cases.
parsedArgs = DefaultParse(new string[] { "/warnaserror:1,2,3", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new string[] { "/nowarn:1,2,3", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new string[] { "/nowarn:1;2;;3", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
}
private static void AssertSpecificDiagnostics(int[] expectedCodes, ReportDiagnostic[] expectedOptions, CSharpCommandLineArguments args)
{
var actualOrdered = args.CompilationOptions.SpecificDiagnosticOptions.OrderBy(entry => entry.Key);
AssertEx.Equal(
expectedCodes.Select(i => MessageProvider.Instance.GetIdForErrorCode(i)),
actualOrdered.Select(entry => entry.Key));
AssertEx.Equal(expectedOptions, actualOrdered.Select(entry => entry.Value));
}
[Fact]
public void WarningsParse()
{
var parsedArgs = DefaultParse(new string[] { "/warnaserror", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
Assert.Equal(0, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count);
parsedArgs = DefaultParse(new string[] { "/warnaserror:1062,1066,1734", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs);
parsedArgs = DefaultParse(new string[] { "/warnaserror:+1062,+1066,+1734", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs);
parsedArgs = DefaultParse(new string[] { "/warnaserror+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Error, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs);
parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs);
parsedArgs = DefaultParse(new string[] { "/warnaserror-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs);
parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Default }, parsedArgs);
parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1762,1974", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(
new[] { 1062, 1066, 1734, 1762, 1974 },
new[] { ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default },
parsedArgs);
parsedArgs = DefaultParse(new string[] { "/warnaserror+:1062,1066,1734", "/warnaserror-:1062,1974", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
Assert.Equal(4, parsedArgs.CompilationOptions.SpecificDiagnosticOptions.Count);
AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Default, ReportDiagnostic.Error, ReportDiagnostic.Error, ReportDiagnostic.Default }, parsedArgs);
parsedArgs = DefaultParse(new string[] { "/warnaserror-:1062,1066,1734", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Default, ReportDiagnostic.Default, ReportDiagnostic.Error }, parsedArgs);
parsedArgs = DefaultParse(new string[] { "/w:1", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs);
parsedArgs = DefaultParse(new string[] { "/warn:1", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(new int[0], new ReportDiagnostic[0], parsedArgs);
parsedArgs = DefaultParse(new string[] { "/warn:1", "/warnaserror+:1062,1974", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(1, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(new[] { 1062, 1974 }, new[] { ReportDiagnostic.Error, ReportDiagnostic.Error }, parsedArgs);
parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs);
parsedArgs = DefaultParse(new string[] { @"/nowarn:""1062 1066 1734""", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(new[] { 1062, 1066, 1734 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress }, parsedArgs);
parsedArgs = DefaultParse(new string[] { "/nowarn:1062,1066,1734", "/warnaserror:1066,1762", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs);
parsedArgs = DefaultParse(new string[] { "/warnaserror:1066,1762", "/nowarn:1062,1066,1734", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ReportDiagnostic.Default, parsedArgs.CompilationOptions.GeneralDiagnosticOption);
Assert.Equal(4, parsedArgs.CompilationOptions.WarningLevel);
AssertSpecificDiagnostics(new[] { 1062, 1066, 1734, 1762 }, new[] { ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Suppress, ReportDiagnostic.Error }, parsedArgs);
}
[Fact]
public void AllowUnsafe()
{
CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/unsafe", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.CompilationOptions.AllowUnsafe);
parsedArgs = DefaultParse(new[] { "/unsafe+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.CompilationOptions.AllowUnsafe);
parsedArgs = DefaultParse(new[] { "/UNSAFE-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.AllowUnsafe);
parsedArgs = DefaultParse(new[] { "/unsafe-", "/unsafe+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.CompilationOptions.AllowUnsafe);
parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory); // default
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.AllowUnsafe);
parsedArgs = DefaultParse(new[] { "/unsafe:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:"));
parsedArgs = DefaultParse(new[] { "/unsafe:+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe:+"));
parsedArgs = DefaultParse(new[] { "/unsafe-:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/unsafe-:"));
}
[Fact]
public void DelaySign()
{
CSharpCommandLineArguments parsedArgs;
parsedArgs = DefaultParse(new[] { "/delaysign", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.NotNull(parsedArgs.CompilationOptions.DelaySign);
Assert.True((bool)parsedArgs.CompilationOptions.DelaySign);
parsedArgs = DefaultParse(new[] { "/delaysign+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.NotNull(parsedArgs.CompilationOptions.DelaySign);
Assert.True((bool)parsedArgs.CompilationOptions.DelaySign);
parsedArgs = DefaultParse(new[] { "/DELAYsign-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.NotNull(parsedArgs.CompilationOptions.DelaySign);
Assert.False((bool)parsedArgs.CompilationOptions.DelaySign);
parsedArgs = DefaultParse(new[] { "/delaysign:-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2007: Unrecognized option: '/delaysign:-'
Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/delaysign:-"));
Assert.Null(parsedArgs.CompilationOptions.DelaySign);
}
[Fact]
public void PublicSign()
{
var parsedArgs = DefaultParse(new[] { "/publicsign", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.CompilationOptions.PublicSign);
parsedArgs = DefaultParse(new[] { "/publicsign+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.CompilationOptions.PublicSign);
parsedArgs = DefaultParse(new[] { "/PUBLICsign-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.CompilationOptions.PublicSign);
parsedArgs = DefaultParse(new[] { "/publicsign:-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2007: Unrecognized option: '/publicsign:-'
Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/publicsign:-").WithLocation(1, 1));
Assert.False(parsedArgs.CompilationOptions.PublicSign);
}
[WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")]
[Fact]
public void PublicSign_KeyFileRelativePath()
{
var parsedArgs = DefaultParse(new[] { "/publicsign", "/keyfile:test.snk", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Path.Combine(WorkingDirectory, "test.snk"), parsedArgs.CompilationOptions.CryptoKeyFile);
}
[Fact]
[WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")]
public void PublicSignWithEmptyKeyPath()
{
DefaultParse(new[] { "/publicsign", "/keyfile:", "a.cs" }, WorkingDirectory).Errors.Verify(
// error CS2005: Missing file specification for 'keyfile' option
Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1));
}
[Fact]
[WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")]
public void PublicSignWithEmptyKeyPath2()
{
DefaultParse(new[] { "/publicsign", "/keyfile:\"\"", "a.cs" }, WorkingDirectory).Errors.Verify(
// error CS2005: Missing file specification for 'keyfile' option
Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile").WithLocation(1, 1));
}
[WorkItem(546301, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546301")]
[Fact]
public void SubsystemVersionTests()
{
CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(SubsystemVersion.Create(4, 0), parsedArgs.EmitOptions.SubsystemVersion);
// wrongly supported subsystem version. CompilationOptions data will be faithful to the user input.
// It is normalized at the time of emit.
parsedArgs = DefaultParse(new[] { "/subsystemversion:0.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(); // no error in Dev11
Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion);
parsedArgs = DefaultParse(new[] { "/subsystemversion:0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(); // no error in Dev11
Assert.Equal(SubsystemVersion.Create(0, 0), parsedArgs.EmitOptions.SubsystemVersion);
parsedArgs = DefaultParse(new[] { "/subsystemversion:3.99", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(); // no error in Dev11
Assert.Equal(SubsystemVersion.Create(3, 99), parsedArgs.EmitOptions.SubsystemVersion);
parsedArgs = DefaultParse(new[] { "/subsystemversion:4.0", "/SUBsystemversion:5.333", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(SubsystemVersion.Create(5, 333), parsedArgs.EmitOptions.SubsystemVersion);
parsedArgs = DefaultParse(new[] { "/subsystemversion:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion"));
parsedArgs = DefaultParse(new[] { "/subsystemversion", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion"));
parsedArgs = DefaultParse(new[] { "/subsystemversion-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/subsystemversion-"));
parsedArgs = DefaultParse(new[] { "/subsystemversion: ", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "subsystemversion"));
parsedArgs = DefaultParse(new[] { "/subsystemversion: 4.1", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(" 4.1"));
parsedArgs = DefaultParse(new[] { "/subsystemversion:4 .0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4 .0"));
parsedArgs = DefaultParse(new[] { "/subsystemversion:4. 0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4. 0"));
parsedArgs = DefaultParse(new[] { "/subsystemversion:.", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("."));
parsedArgs = DefaultParse(new[] { "/subsystemversion:4.", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4."));
parsedArgs = DefaultParse(new[] { "/subsystemversion:.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments(".0"));
parsedArgs = DefaultParse(new[] { "/subsystemversion:4.2 ", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { "/subsystemversion:4.65536", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("4.65536"));
parsedArgs = DefaultParse(new[] { "/subsystemversion:65536.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("65536.0"));
parsedArgs = DefaultParse(new[] { "/subsystemversion:-4.0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("-4.0"));
// TODO: incompatibilities: versions lower than '6.2' and 'arm', 'winmdobj', 'appcontainer'
}
[Fact]
public void MainType()
{
CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/m:A.B.C", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("A.B.C", parsedArgs.CompilationOptions.MainTypeName);
parsedArgs = DefaultParse(new[] { "/m: ", "a.cs" }, WorkingDirectory); // Mimicking Dev11
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m"));
Assert.Null(parsedArgs.CompilationOptions.MainTypeName);
// overriding the value
parsedArgs = DefaultParse(new[] { "/m:A.B.C", "/MAIN:X.Y.Z", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("X.Y.Z", parsedArgs.CompilationOptions.MainTypeName);
// error
parsedArgs = DefaultParse(new[] { "/maiN:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "main"));
parsedArgs = DefaultParse(new[] { "/MAIN+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/MAIN+"));
parsedArgs = DefaultParse(new[] { "/M", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "m"));
// incompatible values /main && /target
parsedArgs = DefaultParse(new[] { "/main:a", "/t:library", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL));
parsedArgs = DefaultParse(new[] { "/main:a", "/t:module", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoMainOnDLL));
}
[Fact]
public void Codepage()
{
CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/CodePage:1200", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("Unicode", parsedArgs.Encoding.EncodingName);
parsedArgs = DefaultParse(new[] { "/CodePage:1200", "/codePAGE:65001", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("Unicode (UTF-8)", parsedArgs.Encoding.EncodingName);
// error
parsedArgs = DefaultParse(new[] { "/codepage:0", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("0"));
parsedArgs = DefaultParse(new[] { "/codepage:abc", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("abc"));
parsedArgs = DefaultParse(new[] { "/codepage:-5", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments("-5"));
parsedArgs = DefaultParse(new[] { "/codepage: ", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments(""));
parsedArgs = DefaultParse(new[] { "/codepage:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadCodepage).WithArguments(""));
parsedArgs = DefaultParse(new[] { "/codepage", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "codepage"));
parsedArgs = DefaultParse(new[] { "/codepage+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/codepage+"));
}
[Fact, WorkItem(24735, "https://github.com/dotnet/roslyn/issues/24735")]
public void ChecksumAlgorithm()
{
CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sHa1", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(SourceHashAlgorithm.Sha1, parsedArgs.ChecksumAlgorithm);
Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm);
parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha256", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm);
Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm);
parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(SourceHashAlgorithm.Sha256, parsedArgs.ChecksumAlgorithm);
Assert.Equal(HashAlgorithmName.SHA256, parsedArgs.EmitOptions.PdbChecksumAlgorithm);
// error
parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:256", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("256"));
parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha-1", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha-1"));
parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:sha", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.FTL_BadChecksumAlgorithm).WithArguments("sha"));
parsedArgs = DefaultParse(new[] { "/checksumAlgorithm: ", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm"));
parsedArgs = DefaultParse(new[] { "/checksumAlgorithm:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm"));
parsedArgs = DefaultParse(new[] { "/checksumAlgorithm", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "checksumalgorithm"));
parsedArgs = DefaultParse(new[] { "/checksumAlgorithm+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/checksumAlgorithm+"));
}
[Fact]
public void AddModule()
{
CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/addmodule:abc.netmodule", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(1, parsedArgs.MetadataReferences.Length);
Assert.Equal("abc.netmodule", parsedArgs.MetadataReferences[0].Reference);
Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind);
parsedArgs = DefaultParse(new[] { "/noconfig", "/nostdlib", "/aDDmodule:c:\\abc;c:\\abc;d:\\xyz", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(3, parsedArgs.MetadataReferences.Length);
Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[0].Reference);
Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[0].Properties.Kind);
Assert.Equal("c:\\abc", parsedArgs.MetadataReferences[1].Reference);
Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[1].Properties.Kind);
Assert.Equal("d:\\xyz", parsedArgs.MetadataReferences[2].Reference);
Assert.Equal(MetadataImageKind.Module, parsedArgs.MetadataReferences[2].Properties.Kind);
// error
parsedArgs = DefaultParse(new[] { "/ADDMODULE", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/addmodule:"));
parsedArgs = DefaultParse(new[] { "/ADDMODULE+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/ADDMODULE+"));
parsedArgs = DefaultParse(new[] { "/ADDMODULE:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("/ADDMODULE:"));
}
[Fact, WorkItem(530751, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530751")]
public void CS7061fromCS0647_ModuleWithCompilationRelaxations()
{
string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
using System.Runtime.CompilerServices;
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
public class Mod { }").Path;
string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
using System.Runtime.CompilerServices;
[assembly: CompilationRelaxations(4)]
public class Mod { }").Path;
string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
using System.Runtime.CompilerServices;
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
class Test { static void Main() {} }").Path;
var baseDir = Path.GetDirectoryName(source);
// === Scenario 1 ===
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter);
Assert.Equal(0, exitCode);
var modfile = source1.Substring(0, source1.Length - 2) + "netmodule";
outWriter = new StringWriter(CultureInfo.InvariantCulture);
var parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory);
parsedArgs.Errors.Verify();
exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source }).Run(outWriter);
Assert.Empty(outWriter.ToString());
// === Scenario 2 ===
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source2 }).Run(outWriter);
Assert.Equal(0, exitCode);
modfile = source2.Substring(0, source2.Length - 2) + "netmodule";
outWriter = new StringWriter(CultureInfo.InvariantCulture);
parsedArgs = DefaultParse(new[] { "/nologo", "/addmodule:" + modfile, source }, WorkingDirectory);
parsedArgs.Errors.Verify();
exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, source }).Run(outWriter);
Assert.Equal(1, exitCode);
// Dev11: CS0647 (Emit)
Assert.Contains("error CS7061: Duplicate 'CompilationRelaxationsAttribute' attribute in", outWriter.ToString(), StringComparison.Ordinal);
CleanupAllGeneratedFiles(source1);
CleanupAllGeneratedFiles(source2);
CleanupAllGeneratedFiles(source);
}
[Fact, WorkItem(530780, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530780")]
public void AddModuleWithExtensionMethod()
{
string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"public static class Extensions { public static bool EB(this bool b) { return b; } }").Path;
string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path;
var baseDir = Path.GetDirectoryName(source2);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter);
Assert.Equal(0, exitCode);
var modfile = source1.Substring(0, source1.Length - 2) + "netmodule";
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/addmodule:" + modfile, source2 }).Run(outWriter);
Assert.Equal(0, exitCode);
CleanupAllGeneratedFiles(source1);
CleanupAllGeneratedFiles(source2);
}
[Fact, WorkItem(546297, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546297")]
public void OLDCS0013FTL_MetadataEmitFailureSameModAndRes()
{
string source1 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Mod { }").Path;
string source2 = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class C { static void Main() {} }").Path;
var baseDir = Path.GetDirectoryName(source2);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/t:module", source1 }).Run(outWriter);
Assert.Equal(0, exitCode);
var modfile = source1.Substring(0, source1.Length - 2) + "netmodule";
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/addmodule:" + modfile, "/linkres:" + modfile, source2 }).Run(outWriter);
Assert.Equal(1, exitCode);
// Native gives CS0013 at emit stage
Assert.Equal("error CS7041: Each linked resource and module must have a unique filename. Filename '" + Path.GetFileName(modfile) + "' is specified more than once in this assembly", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(source1);
CleanupAllGeneratedFiles(source2);
}
[Fact]
public void Utf8Output()
{
CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/utf8output", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True((bool)parsedArgs.Utf8Output);
parsedArgs = DefaultParse(new[] { "/utf8output", "/utf8output", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True((bool)parsedArgs.Utf8Output);
parsedArgs = DefaultParse(new[] { "/utf8output:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/utf8output:"));
}
[Fact]
public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesRunnableProgram()
{
string tempDir = Temp.CreateDirectory().Path;
ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
ProcessUtilities.Run("cmd", $@"/C echo ^
class A ^
{{ ^
public static void Main() =^^^> ^
System.Console.WriteLine(""Hello World!""); ^
}} | {s_CSharpCompilerExecutable} /nologo /t:exe -"
.Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) :
ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \
class A \
{{ \
public static void Main\(\) =\> \
System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \
}} | {s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir,
// we are testing shell's piped/redirected stdin behavior explicitly
// instead of using Process.StandardInput.Write(), so we set
// redirectStandardInput to true, which implies that isatty of child
// process is false and thereby Console.IsInputRedirected will return
// true in csc code.
redirectStandardInput: true);
Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}");
string output = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
ProcessUtilities.RunAndGetOutput("cmd.exe", $@"/C ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir) :
ProcessUtilities.RunAndGetOutput("sh", $@"-c ""{s_DotnetCscRun} -.exe""", expectedRetCode: 0, startFolder: tempDir);
Assert.Equal("Hello World!", output.Trim());
}
[Fact]
public void CscCompile_WithSourceCodeRedirectedViaStandardInput_ProducesLibrary()
{
var name = Guid.NewGuid().ToString() + ".dll";
string tempDir = Temp.CreateDirectory().Path;
ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
ProcessUtilities.Run("cmd", $@"/C echo ^
class A ^
{{ ^
public A Get() =^^^> default; ^
}} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -"
.Replace(Environment.NewLine, string.Empty), workingDirectory: tempDir) :
ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \
class A \
{{ \
public A Get\(\) =\> default\; \
}} | {s_CSharpCompilerExecutable} /nologo /t:library /out:{name} -""", workingDirectory: tempDir,
// we are testing shell's piped/redirected stdin behavior explicitly
// instead of using Process.StandardInput.Write(), so we set
// redirectStandardInput to true, which implies that isatty of child
// process is false and thereby Console.IsInputRedirected will return
// true in csc code.
redirectStandardInput: true);
Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}");
var assemblyName = AssemblyName.GetAssemblyName(Path.Combine(tempDir, name));
Assert.Equal(name.Replace(".dll", ", Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"),
assemblyName.ToString());
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/55727")]
public void CsiScript_WithSourceCodeRedirectedViaStandardInput_ExecutesNonInteractively()
{
string tempDir = Temp.CreateDirectory().Path;
ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
ProcessUtilities.Run("cmd", $@"/C echo Console.WriteLine(""Hello World!"") | {s_CSharpScriptExecutable} -") :
ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo Console.WriteLine\(\\\""Hello World\!\\\""\) | {s_CSharpScriptExecutable} -""",
workingDirectory: tempDir,
// we are testing shell's piped/redirected stdin behavior explicitly
// instead of using Process.StandardInput.Write(), so we set
// redirectStandardInput to true, which implies that isatty of child
// process is false and thereby Console.IsInputRedirected will return
// true in csc code.
redirectStandardInput: true);
Assert.False(result.ContainsErrors, $"Compilation error(s) occurred: {result.Output} {result.Errors}");
Assert.Equal("Hello World!", result.Output.Trim());
}
[Fact]
public void CscCompile_WithRedirectedInputIndicatorAndStandardInputNotRedirected_ReportsCS8782()
{
if (Console.IsInputRedirected)
{
// [applicable to both Windows and Unix]
// if our parent (xunit) process itself has input redirected, we cannot test this
// error case because our child process will inherit it and we cannot achieve what
// we are aiming for: isatty(0):true and thereby Console.IsInputerRedirected:false in
// child. running this case will make StreamReader to hang (waiting for input, that
// we do not propagate: parent.In->child.In).
//
// note: in Unix we can "close" fd0 by appending `0>&-` in the `sh -c` command below,
// but that will also not impact the result of isatty(), and in turn causes a different
// compiler error.
return;
}
string tempDir = Temp.CreateDirectory().Path;
ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
ProcessUtilities.Run("cmd", $@"/C ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir) :
ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""{s_CSharpCompilerExecutable} /nologo /t:exe -""", workingDirectory: tempDir);
Assert.True(result.ContainsErrors);
Assert.Contains(((int)ErrorCode.ERR_StdInOptionProvidedButConsoleInputIsNotRedirected).ToString(), result.Output);
}
[Fact]
public void CscCompile_WithMultipleStdInOperators_WarnsCS2002()
{
string tempDir = Temp.CreateDirectory().Path;
ProcessResult result = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
ProcessUtilities.Run("cmd", $@"/C echo ^
class A ^
{{ ^
public static void Main() =^^^> ^
System.Console.WriteLine(""Hello World!""); ^
}} | {s_CSharpCompilerExecutable} /nologo - /t:exe -"
.Replace(Environment.NewLine, string.Empty)) :
ProcessUtilities.Run("/usr/bin/env", $@"sh -c ""echo \
class A \
{{ \
public static void Main\(\) =\> \
System.Console.WriteLine\(\\\""Hello World\!\\\""\)\; \
}} | {s_CSharpCompilerExecutable} /nologo - /t:exe -""", workingDirectory: tempDir,
// we are testing shell's piped/redirected stdin behavior explicitly
// instead of using Process.StandardInput.Write(), so we set
// redirectStandardInput to true, which implies that isatty of child
// process is false and thereby Console.IsInputRedirected will return
// true in csc code.
redirectStandardInput: true);
Assert.Contains(((int)ErrorCode.WRN_FileAlreadyIncluded).ToString(), result.Output);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void CscUtf8Output_WithRedirecting_Off()
{
var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path;
var tempOut = Temp.CreateFile();
var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1);
Assert.Equal("", output.Trim());
Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '?'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS"));
CleanupAllGeneratedFiles(srcFile);
CleanupAllGeneratedFiles(tempOut.Path);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void CscUtf8Output_WithRedirecting_On()
{
var srcFile = Temp.CreateFile().WriteAllText("\u265A").Path;
var tempOut = Temp.CreateFile();
var output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /utf8output /nologo /preferreduilang:en /t:library " + srcFile + " > " + tempOut.Path, expectedRetCode: 1);
Assert.Equal("", output.Trim());
Assert.Equal("SRC.CS(1,1): error CS1056: Unexpected character '♚'", tempOut.ReadAllText().Trim().Replace(srcFile, "SRC.CS"));
CleanupAllGeneratedFiles(srcFile);
CleanupAllGeneratedFiles(tempOut.Path);
}
[WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void NoSourcesWithModule()
{
var folder = Temp.CreateDirectory();
var aCs = folder.CreateFile("a.cs");
aCs.WriteAllText("public class C {}");
var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:module /out:a.netmodule \"{aCs}\"", startFolder: folder.ToString());
Assert.Equal("", output.Trim());
output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString());
Assert.Equal("", output.Trim());
output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /preferreduilang:en /t:module /out:b.dll /addmodule:a.netmodule ", startFolder: folder.ToString());
Assert.Equal("warning CS2008: No source files specified.", output.Trim());
CleanupAllGeneratedFiles(aCs.Path);
}
[WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void NoSourcesWithResource()
{
var folder = Temp.CreateDirectory();
var aCs = folder.CreateFile("a.cs");
aCs.WriteAllText("public class C {}");
var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /resource:a.cs", startFolder: folder.ToString());
Assert.Equal("", output.Trim());
CleanupAllGeneratedFiles(aCs.Path);
}
[WorkItem(546653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546653")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void NoSourcesWithLinkResource()
{
var folder = Temp.CreateDirectory();
var aCs = folder.CreateFile("a.cs");
aCs.WriteAllText("public class C {}");
var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, "/nologo /t:library /out:b.dll /linkresource:a.cs", startFolder: folder.ToString());
Assert.Equal("", output.Trim());
CleanupAllGeneratedFiles(aCs.Path);
}
[Fact]
public void KeyContainerAndKeyFile()
{
// KEYCONTAINER
CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/keycontainer:RIPAdamYauch", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("RIPAdamYauch", parsedArgs.CompilationOptions.CryptoKeyContainer);
parsedArgs = DefaultParse(new[] { "/keycontainer", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer"));
Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer);
parsedArgs = DefaultParse(new[] { "/keycontainer-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2007: Unrecognized option: '/keycontainer-'
Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keycontainer-"));
Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer);
parsedArgs = DefaultParse(new[] { "/keycontainer:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for 'keycontainer' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer"));
Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer);
parsedArgs = DefaultParse(new[] { "/keycontainer: ", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "keycontainer"));
Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer);
// KEYFILE
parsedArgs = DefaultParse(new[] { @"/keyfile:\somepath\s""ome Fil""e.goo.bar", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
//EDMAURER let's not set the option in the event that there was an error.
//Assert.Equal(@"\somepath\some File.goo.bar", parsedArgs.CompilationOptions.CryptoKeyFile);
parsedArgs = DefaultParse(new[] { "/keyFile", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2005: Missing file specification for 'keyfile' option
Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile"));
Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile);
parsedArgs = DefaultParse(new[] { "/keyFile: ", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(Diagnostic(ErrorCode.ERR_NoFileSpec).WithArguments("keyfile"));
Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile);
parsedArgs = DefaultParse(new[] { "/keyfile-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS2007: Unrecognized option: '/keyfile-'
Diagnostic(ErrorCode.ERR_BadSwitch).WithArguments("/keyfile-"));
Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile);
// DEFAULTS
parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Null(parsedArgs.CompilationOptions.CryptoKeyFile);
Assert.Null(parsedArgs.CompilationOptions.CryptoKeyContainer);
// KEYFILE | KEYCONTAINER conflicts
parsedArgs = DefaultParse(new[] { "/keyFile:a", "/keyContainer:b", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile);
Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer);
parsedArgs = DefaultParse(new[] { "/keyContainer:b", "/keyFile:a", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("a", parsedArgs.CompilationOptions.CryptoKeyFile);
Assert.Equal("b", parsedArgs.CompilationOptions.CryptoKeyContainer);
}
[Fact, WorkItem(554551, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554551")]
public void CS1698WRN_AssumedMatchThis()
{
// compile with: /target:library /keyfile:mykey.snk
var text1 = @"[assembly:System.Reflection.AssemblyVersion(""2"")]
public class CS1698_a {}
";
// compile with: /target:library /reference:CS1698_a.dll /keyfile:mykey.snk
var text2 = @"public class CS1698_b : CS1698_a {}
";
//compile with: /target:library /out:cs1698_a.dll /reference:cs1698_b.dll /keyfile:mykey.snk
var text = @"[assembly:System.Reflection.AssemblyVersion(""3"")]
public class CS1698_c : CS1698_b {}
public class CS1698_a {}
";
var folder = Temp.CreateDirectory();
var cs1698a = folder.CreateFile("CS1698a.cs");
cs1698a.WriteAllText(text1);
var cs1698b = folder.CreateFile("CS1698b.cs");
cs1698b.WriteAllText(text2);
var cs1698 = folder.CreateFile("CS1698.cs");
cs1698.WriteAllText(text);
var snkFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey);
var kfile = "/keyfile:" + snkFile.Path;
CSharpCommandLineArguments parsedArgs = DefaultParse(new[] { "/t:library", kfile, "CS1698a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698a.Path, "CS1698b.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
parsedArgs = DefaultParse(new[] { "/t:library", kfile, "/r:" + cs1698b.Path, "/out:" + cs1698a.Path, "CS1698.cs" }, WorkingDirectory);
// Roslyn no longer generates a warning for this...since this was only a warning, we're not really
// saving anyone...does not provide high value to implement...
// warning CS1698: Circular assembly reference 'CS1698a, Version=2.0.0.0, Culture=neutral,PublicKeyToken = 9e9d6755e7bb4c10'
// does not match the output assembly name 'CS1698a, Version = 3.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10'.
// Try adding a reference to 'CS1698a, Version = 2.0.0.0, Culture = neutral, PublicKeyToken = 9e9d6755e7bb4c10' or changing the output assembly name to match.
parsedArgs.Errors.Verify();
CleanupAllGeneratedFiles(snkFile.Path);
CleanupAllGeneratedFiles(cs1698a.Path);
CleanupAllGeneratedFiles(cs1698b.Path);
CleanupAllGeneratedFiles(cs1698.Path);
}
[ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/dotnet/roslyn/issues/30926")]
public void BinaryFileErrorTest()
{
var binaryPath = Temp.CreateFile().WriteAllBytes(ResourcesNet451.mscorlib).Path;
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", binaryPath });
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal(
"error CS2015: '" + binaryPath + "' is a binary file instead of a text file",
outWriter.ToString().Trim());
CleanupAllGeneratedFiles(binaryPath);
}
#if !NETCOREAPP
[WorkItem(530221, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530221")]
[WorkItem(5660, "https://github.com/dotnet/roslyn/issues/5660")]
[ConditionalFact(typeof(WindowsOnly), typeof(IsEnglishLocal))]
public void Bug15538()
{
// Several Jenkins VMs are still running with local systems permissions. This suite won't run properly
// in that environment. Removing this check is being tracked by issue #79.
using (var identity = System.Security.Principal.WindowsIdentity.GetCurrent())
{
if (identity.IsSystem)
{
return;
}
// The icacls command fails on our Helix machines and it appears to be related to the use of the $ in
// the username.
// https://github.com/dotnet/roslyn/issues/28836
if (StringComparer.OrdinalIgnoreCase.Equals(Environment.UserDomainName, "WORKGROUP"))
{
return;
}
}
var folder = Temp.CreateDirectory();
var source = folder.CreateFile("src.vb").WriteAllText("").Path;
var _ref = folder.CreateFile("ref.dll").WriteAllText("").Path;
try
{
var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /inheritance:r /Q");
Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim());
output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + @" /deny %USERDOMAIN%\%USERNAME%:(r,WDAC) /Q");
Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim());
output = ProcessUtilities.RunAndGetOutput("cmd", "/C \"" + s_CSharpCompilerExecutable + "\" /nologo /preferreduilang:en /r:" + _ref + " /t:library " + source, expectedRetCode: 1);
Assert.Equal("error CS0009: Metadata file '" + _ref + "' could not be opened -- Access to the path '" + _ref + "' is denied.", output.Trim());
}
finally
{
var output = ProcessUtilities.RunAndGetOutput("cmd", "/C icacls " + _ref + " /reset /Q");
Assert.Equal("Successfully processed 1 files; Failed processing 0 files", output.Trim());
File.Delete(_ref);
}
CleanupAllGeneratedFiles(source);
}
#endif
[WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")]
[Fact]
public void ResponseFilesWithEmptyAliasReference()
{
string source = Temp.CreateFile("a.cs").WriteAllText(@"
// <Area> ExternAlias - command line alias</Area>
// <Title>
// negative test cases: empty file name ("""")
// </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=error>CS1680:.*myAlias=</Expects>
// <Code>
class myClass
{
static int Main()
{
return 1;
}
}
// </Code>
").Path;
string rsp = Temp.CreateFile().WriteAllText(@"
/nologo
/r:myAlias=""""
").Path;
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
// csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp
var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(source);
CleanupAllGeneratedFiles(rsp);
}
[Fact]
public void ResponseFileOrdering()
{
var rspFilePath1 = Temp.CreateFile().WriteAllText(@"
/b
/c
").Path;
assertOrder(
new[] { "/a", "/b", "/c", "/d" },
new[] { "/a", @$"@""{rspFilePath1}""", "/d" });
var rspFilePath2 = Temp.CreateFile().WriteAllText(@"
/c
/d
").Path;
rspFilePath1 = Temp.CreateFile().WriteAllText(@$"
/b
@""{rspFilePath2}""
").Path;
assertOrder(
new[] { "/a", "/b", "/c", "/d", "/e" },
new[] { "/a", @$"@""{rspFilePath1}""", "/e" });
rspFilePath1 = Temp.CreateFile().WriteAllText(@$"
/b
").Path;
rspFilePath2 = Temp.CreateFile().WriteAllText(@"
# this will be ignored
/c
/d
").Path;
assertOrder(
new[] { "/a", "/b", "/c", "/d", "/e" },
new[] { "/a", @$"@""{rspFilePath1}""", $@"@""{rspFilePath2}""", "/e" });
void assertOrder(string[] expected, string[] args)
{
var flattenedArgs = ArrayBuilder<string>.GetInstance();
var diagnostics = new List<Diagnostic>();
CSharpCommandLineParser.Default.FlattenArgs(
args,
diagnostics,
flattenedArgs,
scriptArgsOpt: null,
baseDirectory: Path.DirectorySeparatorChar == '\\' ? @"c:\" : "/");
Assert.Empty(diagnostics);
Assert.Equal(expected, flattenedArgs);
flattenedArgs.Free();
}
}
[WorkItem(545832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545832")]
[Fact]
public void ResponseFilesWithEmptyAliasReference2()
{
string source = Temp.CreateFile("a.cs").WriteAllText(@"
// <Area> ExternAlias - command line alias</Area>
// <Title>
// negative test cases: empty file name ("""")
// </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=error>CS1680:.*myAlias=</Expects>
// <Code>
class myClass
{
static int Main()
{
return 1;
}
}
// </Code>
").Path;
string rsp = Temp.CreateFile().WriteAllText(@"
/nologo
/r:myAlias="" ""
").Path;
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
// csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp
var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS1680: Invalid reference alias option: 'myAlias=' -- missing filename", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(source);
CleanupAllGeneratedFiles(rsp);
}
[WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")]
[Fact]
public void QuotedDefineInRespFile()
{
string source = Temp.CreateFile("a.cs").WriteAllText(@"
#if NN
class myClass
{
#endif
static int Main()
#if DD
{
return 1;
#endif
#if AA
}
#endif
#if BB
}
#endif
").Path;
string rsp = Temp.CreateFile().WriteAllText(@"
/d:""DD""
/d:""AA;BB""
/d:""N""N
").Path;
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
// csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp
var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
CleanupAllGeneratedFiles(source);
CleanupAllGeneratedFiles(rsp);
}
[WorkItem(1784, "https://github.com/dotnet/roslyn/issues/1784")]
[Fact]
public void QuotedDefineInRespFileErr()
{
string source = Temp.CreateFile("a.cs").WriteAllText(@"
#if NN
class myClass
{
#endif
static int Main()
#if DD
{
return 1;
#endif
#if AA
}
#endif
#if BB
}
#endif
").Path;
string rsp = Temp.CreateFile().WriteAllText(@"
/d:""DD""""
/d:""AA;BB""
/d:""N"" ""N
").Path;
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
// csc errors_whitespace_008.cs @errors_whitespace_008.cs.rsp
var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
CleanupAllGeneratedFiles(source);
CleanupAllGeneratedFiles(rsp);
}
[Fact]
public void ResponseFileSplitting()
{
string[] responseFile;
responseFile = new string[] {
@"a.cs b.cs ""c.cs e.cs""",
@"hello world # this is a comment"
};
IEnumerable<string> args = CSharpCommandLineParser.ParseResponseLines(responseFile);
AssertEx.Equal(new[] { "a.cs", "b.cs", @"c.cs e.cs", "hello", "world" }, args);
// Check comment handling; comment character only counts at beginning of argument
responseFile = new string[] {
@" # ignore this",
@" # ignore that ""hello""",
@" a.cs #3.cs",
@" b#.cs c#d.cs #e.cs",
@" ""#f.cs""",
@" ""#g.cs #h.cs"""
};
args = CSharpCommandLineParser.ParseResponseLines(responseFile);
AssertEx.Equal(new[] { "a.cs", "b#.cs", "c#d.cs", "#f.cs", "#g.cs #h.cs" }, args);
// Check backslash escaping
responseFile = new string[] {
@"a\b\c d\\e\\f\\ \\\g\\\h\\\i \\\\ \\\\\k\\\\\",
};
args = CSharpCommandLineParser.ParseResponseLines(responseFile);
AssertEx.Equal(new[] { @"a\b\c", @"d\\e\\f\\", @"\\\g\\\h\\\i", @"\\\\", @"\\\\\k\\\\\" }, args);
// More backslash escaping and quoting
responseFile = new string[] {
@"a\""a b\\""b c\\\""c d\\\\""d e\\\\\""e f"" g""",
};
args = CSharpCommandLineParser.ParseResponseLines(responseFile);
AssertEx.Equal(new[] { @"a\""a", @"b\\""b c\\\""c d\\\\""d", @"e\\\\\""e", @"f"" g""" }, args);
// Quoting inside argument is valid.
responseFile = new string[] {
@" /o:""goo.cs"" /o:""abc def""\baz ""/o:baz bar""bing",
};
args = CSharpCommandLineParser.ParseResponseLines(responseFile);
AssertEx.Equal(new[] { @"/o:""goo.cs""", @"/o:""abc def""\baz", @"""/o:baz bar""bing" }, args);
}
[ConditionalFact(typeof(WindowsOnly))]
private void SourceFileQuoting()
{
string[] responseFile = new string[] {
@"d:\\""abc def""\baz.cs ab""c d""e.cs",
};
CSharpCommandLineArguments args = DefaultParse(CSharpCommandLineParser.ParseResponseLines(responseFile), @"c:\");
AssertEx.Equal(new[] { @"d:\abc def\baz.cs", @"c:\abc de.cs" }, args.SourceFiles.Select(file => file.Path));
}
[WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
[Fact]
public void OutputFileName1()
{
string source1 = @"
class A
{
}
";
string source2 = @"
class B
{
static void Main() { }
}
";
// Name comes from first input (file, not class) name, since DLL.
CheckOutputFileName(
source1, source2,
inputName1: "p.cs", inputName2: "q.cs",
commandLineArguments: new[] { "/target:library" },
expectedOutputName: "p.dll");
}
[WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
[Fact]
public void OutputFileName2()
{
string source1 = @"
class A
{
}
";
string source2 = @"
class B
{
static void Main() { }
}
";
// Name comes from command-line option.
CheckOutputFileName(
source1, source2,
inputName1: "p.cs", inputName2: "q.cs",
commandLineArguments: new[] { "/target:library", "/out:r.dll" },
expectedOutputName: "r.dll");
}
[WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
[Fact]
public void OutputFileName3()
{
string source1 = @"
class A
{
}
";
string source2 = @"
class B
{
static void Main() { }
}
";
// Name comes from name of file containing entrypoint, since EXE.
CheckOutputFileName(
source1, source2,
inputName1: "p.cs", inputName2: "q.cs",
commandLineArguments: new[] { "/target:exe" },
expectedOutputName: "q.exe");
}
[WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
[Fact]
public void OutputFileName4()
{
string source1 = @"
class A
{
}
";
string source2 = @"
class B
{
static void Main() { }
}
";
// Name comes from command-line option.
CheckOutputFileName(
source1, source2,
inputName1: "p.cs", inputName2: "q.cs",
commandLineArguments: new[] { "/target:exe", "/out:r.exe" },
expectedOutputName: "r.exe");
}
[WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
[Fact]
public void OutputFileName5()
{
string source1 = @"
class A
{
static void Main() { }
}
";
string source2 = @"
class B
{
static void Main() { }
}
";
// Name comes from name of file containing entrypoint - affected by /main, since EXE.
CheckOutputFileName(
source1, source2,
inputName1: "p.cs", inputName2: "q.cs",
commandLineArguments: new[] { "/target:exe", "/main:A" },
expectedOutputName: "p.exe");
}
[WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
[Fact]
public void OutputFileName6()
{
string source1 = @"
class A
{
static void Main() { }
}
";
string source2 = @"
class B
{
static void Main() { }
}
";
// Name comes from name of file containing entrypoint - affected by /main, since EXE.
CheckOutputFileName(
source1, source2,
inputName1: "p.cs", inputName2: "q.cs",
commandLineArguments: new[] { "/target:exe", "/main:B" },
expectedOutputName: "q.exe");
}
[WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
[Fact]
public void OutputFileName7()
{
string source1 = @"
partial class A
{
static partial void Main() { }
}
";
string source2 = @"
partial class A
{
static partial void Main();
}
";
// Name comes from name of file containing entrypoint, since EXE.
CheckOutputFileName(
source1, source2,
inputName1: "p.cs", inputName2: "q.cs",
commandLineArguments: new[] { "/target:exe" },
expectedOutputName: "p.exe");
}
[WorkItem(544441, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544441")]
[Fact]
public void OutputFileName8()
{
string source1 = @"
partial class A
{
static partial void Main();
}
";
string source2 = @"
partial class A
{
static partial void Main() { }
}
";
// Name comes from name of file containing entrypoint, since EXE.
CheckOutputFileName(
source1, source2,
inputName1: "p.cs", inputName2: "q.cs",
commandLineArguments: new[] { "/target:exe" },
expectedOutputName: "q.exe");
}
[Fact]
public void OutputFileName9()
{
string source1 = @"
class A
{
}
";
string source2 = @"
class B
{
static void Main() { }
}
";
// Name comes from first input (file, not class) name, since winmdobj.
CheckOutputFileName(
source1, source2,
inputName1: "p.cs", inputName2: "q.cs",
commandLineArguments: new[] { "/target:winmdobj" },
expectedOutputName: "p.winmdobj");
}
[Fact]
public void OutputFileName10()
{
string source1 = @"
class A
{
}
";
string source2 = @"
class B
{
static void Main() { }
}
";
// Name comes from name of file containing entrypoint, since appcontainerexe.
CheckOutputFileName(
source1, source2,
inputName1: "p.cs", inputName2: "q.cs",
commandLineArguments: new[] { "/target:appcontainerexe" },
expectedOutputName: "q.exe");
}
[Fact]
public void OutputFileName_Switch()
{
string source1 = @"
class A
{
}
";
string source2 = @"
class B
{
static void Main() { }
}
";
// Name comes from name of file containing entrypoint, since EXE.
CheckOutputFileName(
source1, source2,
inputName1: "p.cs", inputName2: "q.cs",
commandLineArguments: new[] { "/target:exe", "/out:r.exe" },
expectedOutputName: "r.exe");
}
[Fact]
public void OutputFileName_NoEntryPoint()
{
string source = @"
class C
{
}
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/target:exe", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.NotEqual(0, exitCode);
Assert.Equal("error CS5001: Program does not contain a static 'Main' method suitable for an entry point", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(file.Path);
}
[Fact, WorkItem(1093063, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1093063")]
public void VerifyDiagnosticSeverityNotLocalized()
{
string source = @"
class C
{
}
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:exe", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.NotEqual(0, exitCode);
// If "error" was localized, below assert will fail on PLOC builds. The output would be something like: "!pTCvB!vbc : !FLxft!error 表! CS5001:"
Assert.Contains("error CS5001:", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(file.Path);
}
[Fact]
public void NoLogo_1()
{
string source = @"
class C
{
}
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/target:library", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal(@"",
outWriter.ToString().Trim());
CleanupAllGeneratedFiles(file.Path);
}
[Fact]
public void NoLogo_2()
{
string source = @"
class C
{
}
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
var patched = Regex.Replace(outWriter.ToString().Trim(), "version \\d+\\.\\d+\\.\\d+(-[\\w\\d]+)*", "version A.B.C-d");
patched = ReplaceCommitHash(patched);
Assert.Equal(@"
Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)
Copyright (C) Microsoft Corporation. All rights reserved.".Trim(),
patched);
CleanupAllGeneratedFiles(file.Path);
}
[Theory,
InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (<developer build>)",
"Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"),
InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (ABCDEF01)",
"Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"),
InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (abcdef90)",
"Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)"),
InlineData("Microsoft (R) Visual C# Compiler version A.B.C-d (12345678)",
"Microsoft (R) Visual C# Compiler version A.B.C-d (HASH)")]
public void TestReplaceCommitHash(string orig, string expected)
{
Assert.Equal(expected, ReplaceCommitHash(orig));
}
private static string ReplaceCommitHash(string s)
{
// open paren, followed by either <developer build> or 8 hex, followed by close paren
return Regex.Replace(s, "(\\((<developer build>|[a-fA-F0-9]{8})\\))", "(HASH)");
}
[Fact]
public void ExtractShortCommitHash()
{
Assert.Null(CommonCompiler.ExtractShortCommitHash(null));
Assert.Equal("", CommonCompiler.ExtractShortCommitHash(""));
Assert.Equal("<", CommonCompiler.ExtractShortCommitHash("<"));
Assert.Equal("<developer build>", CommonCompiler.ExtractShortCommitHash("<developer build>"));
Assert.Equal("1", CommonCompiler.ExtractShortCommitHash("1"));
Assert.Equal("1234567", CommonCompiler.ExtractShortCommitHash("1234567"));
Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("12345678"));
Assert.Equal("12345678", CommonCompiler.ExtractShortCommitHash("123456789"));
}
private void CheckOutputFileName(string source1, string source2, string inputName1, string inputName2, string[] commandLineArguments, string expectedOutputName)
{
var dir = Temp.CreateDirectory();
var file1 = dir.CreateFile(inputName1);
file1.WriteAllText(source1);
var file2 = dir.CreateFile(inputName2);
file2.WriteAllText(source2);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { inputName1, inputName2 }).ToArray());
int exitCode = csc.Run(outWriter);
if (exitCode != 0)
{
Console.WriteLine(outWriter.ToString());
Assert.Equal(0, exitCode);
}
Assert.Equal(1, Directory.EnumerateFiles(dir.Path, "*" + PathUtilities.GetExtension(expectedOutputName)).Count());
Assert.Equal(1, Directory.EnumerateFiles(dir.Path, expectedOutputName).Count());
using (var metadata = ModuleMetadata.CreateFromImage(File.ReadAllBytes(Path.Combine(dir.Path, expectedOutputName))))
{
var peReader = metadata.Module.GetMetadataReader();
Assert.True(peReader.IsAssembly);
Assert.Equal(PathUtilities.RemoveExtension(expectedOutputName), peReader.GetString(peReader.GetAssemblyDefinition().Name));
Assert.Equal(expectedOutputName, peReader.GetString(peReader.GetModuleDefinition().Name));
}
if (System.IO.File.Exists(expectedOutputName))
{
System.IO.File.Delete(expectedOutputName);
}
CleanupAllGeneratedFiles(file1.Path);
CleanupAllGeneratedFiles(file2.Path);
}
[Fact]
public void MissingReference()
{
string source = @"
class C
{
}
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "/preferreduilang:en", "/r:missing.dll", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS0006: Metadata file 'missing.dll' could not be found", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(file.Path);
}
[WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")]
[ConditionalFact(typeof(WindowsOnly))]
public void CompilationWithWarnAsError_01()
{
string source = @"
public class C
{
public static void Main()
{
}
}";
// Baseline without warning options (expect success)
int exitCode = GetExitCode(source, "a.cs", new String[] { });
Assert.Equal(0, exitCode);
// The case with /warnaserror (expect to be success, since there will be no warning)
exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" });
Assert.Equal(0, exitCode);
// The case with /warnaserror and /nowarn:1 (expect success)
// Note that even though the command line option has a warning, it is not going to become an error
// in order to avoid the halt of compilation.
exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror", "/nowarn:1" });
Assert.Equal(0, exitCode);
}
[WorkItem(545025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545025")]
[ConditionalFact(typeof(WindowsOnly))]
public void CompilationWithWarnAsError_02()
{
string source = @"
public class C
{
public static void Main()
{
int x; // CS0168
}
}";
// Baseline without warning options (expect success)
int exitCode = GetExitCode(source, "a.cs", new String[] { });
Assert.Equal(0, exitCode);
// The case with /warnaserror (expect failure)
exitCode = GetExitCode(source, "b.cs", new[] { "/warnaserror" });
Assert.NotEqual(0, exitCode);
// The case with /warnaserror:168 (expect failure)
exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:168" });
Assert.NotEqual(0, exitCode);
// The case with /warnaserror:219 (expect success)
exitCode = GetExitCode(source, "c.cs", new[] { "/warnaserror:219" });
Assert.Equal(0, exitCode);
// The case with /warnaserror and /nowarn:168 (expect success)
exitCode = GetExitCode(source, "d.cs", new[] { "/warnaserror", "/nowarn:168" });
Assert.Equal(0, exitCode);
}
private int GetExitCode(string source, string fileName, string[] commandLineArguments)
{
var dir = Temp.CreateDirectory();
var file = dir.CreateFile(fileName);
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, commandLineArguments.Concat(new[] { fileName }).ToArray());
int exitCode = csc.Run(outWriter);
return exitCode;
}
[WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")]
[ConditionalFact(typeof(WindowsOnly))]
public void CompilationWithNonExistingOutPath()
{
string source = @"
public class C
{
public static void Main()
{
}
}";
var fileName = "a.cs";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile(fileName);
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\a.exe" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Contains("error CS2012: Cannot open '" + dir.Path + "\\sub\\a.exe' for writing", outWriter.ToString(), StringComparison.Ordinal);
CleanupAllGeneratedFiles(file.Path);
}
[WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")]
[Fact]
public void CompilationWithWrongOutPath_01()
{
string source = @"
public class C
{
public static void Main()
{
}
}";
var fileName = "a.cs";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile(fileName);
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
var message = outWriter.ToString();
Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal);
Assert.Contains("sub", message, StringComparison.Ordinal);
CleanupAllGeneratedFiles(file.Path);
}
[WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")]
[Fact]
public void CompilationWithWrongOutPath_02()
{
string source = @"
public class C
{
public static void Main()
{
}
}";
var fileName = "a.cs";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile(fileName);
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:sub\\ " });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
var message = outWriter.ToString();
Assert.Contains("error CS2021: File name", message, StringComparison.Ordinal);
Assert.Contains("sub", message, StringComparison.Ordinal);
CleanupAllGeneratedFiles(file.Path);
}
[WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")]
[ConditionalFact(typeof(WindowsDesktopOnly))]
public void CompilationWithWrongOutPath_03()
{
string source = @"
public class C
{
public static void Main()
{
}
}";
var fileName = "a.cs";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile(fileName);
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out:aaa:\\a.exe" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Contains(@"error CS2021: File name 'aaa:\a.exe' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal);
CleanupAllGeneratedFiles(file.Path);
}
[WorkItem(545247, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545247")]
[Fact]
public void CompilationWithWrongOutPath_04()
{
string source = @"
public class C
{
public static void Main()
{
}
}";
var fileName = "a.cs";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile(fileName);
file.WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, new[] { fileName, "/preferreduilang:en", "/target:exe", "/out: " });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Contains("error CS2005: Missing file specification for '/out:' option", outWriter.ToString(), StringComparison.Ordinal);
CleanupAllGeneratedFiles(file.Path);
}
[Fact]
public void EmittedSubsystemVersion()
{
var compilation = CSharpCompilation.Create("a.dll", references: new[] { MscorlibRef }, options: TestOptions.ReleaseDll);
var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(subsystemVersion: SubsystemVersion.Create(5, 1))));
Assert.Equal(5, peHeaders.PEHeader.MajorSubsystemVersion);
Assert.Equal(1, peHeaders.PEHeader.MinorSubsystemVersion);
}
[Fact]
public void CreateCompilationWithKeyFile()
{
string source = @"
public class C
{
public static void Main()
{
}
}";
var fileName = "a.cs";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile(fileName);
file.WriteAllText(source);
var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyfile:key.snk", });
var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance);
Assert.IsType<DesktopStrongNameProvider>(comp.Options.StrongNameProvider);
}
[Fact]
public void CreateCompilationWithKeyContainer()
{
string source = @"
public class C
{
public static void Main()
{
}
}";
var fileName = "a.cs";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile(fileName);
file.WriteAllText(source);
var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keycontainer:bbb", });
var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance);
Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType());
}
[Fact]
public void CreateCompilationFallbackCommand()
{
string source = @"
public class C
{
public static void Main()
{
}
}";
var fileName = "a.cs";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile(fileName);
file.WriteAllText(source);
var cmd = CreateCSharpCompiler(null, dir.Path, new[] { "/nologo", "a.cs", "/keyFile:key.snk", "/features:UseLegacyStrongNameProvider" });
var comp = cmd.CreateCompilation(TextWriter.Null, new TouchedFileLogger(), NullErrorLogger.Instance);
Assert.Equal(typeof(DesktopStrongNameProvider), comp.Options.StrongNameProvider.GetType());
}
[Fact]
public void CreateCompilation_MainAndTargetIncompatibilities()
{
string source = @"
public class C
{
public static void Main()
{
}
}";
var fileName = "a.cs";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile(fileName);
file.WriteAllText(source);
var compilation = CSharpCompilation.Create("a.dll", options: TestOptions.ReleaseDll);
var options = compilation.Options;
Assert.Equal(0, options.Errors.Length);
options = options.WithMainTypeName("a");
options.Errors.Verify(
// error CS2017: Cannot specify /main if building a module or library
Diagnostic(ErrorCode.ERR_NoMainOnDLL)
);
var comp = CSharpCompilation.Create("a.dll", options: options);
comp.GetDiagnostics().Verify(
// error CS2017: Cannot specify /main if building a module or library
Diagnostic(ErrorCode.ERR_NoMainOnDLL)
);
options = options.WithOutputKind(OutputKind.WindowsApplication);
options.Errors.Verify();
comp = CSharpCompilation.Create("a.dll", options: options);
comp.GetDiagnostics().Verify(
// error CS1555: Could not find 'a' specified for Main method
Diagnostic(ErrorCode.ERR_MainClassNotFound).WithArguments("a")
);
options = options.WithOutputKind(OutputKind.NetModule);
options.Errors.Verify(
// error CS2017: Cannot specify /main if building a module or library
Diagnostic(ErrorCode.ERR_NoMainOnDLL)
);
comp = CSharpCompilation.Create("a.dll", options: options);
comp.GetDiagnostics().Verify(
// error CS2017: Cannot specify /main if building a module or library
Diagnostic(ErrorCode.ERR_NoMainOnDLL)
);
options = options.WithMainTypeName(null);
options.Errors.Verify();
comp = CSharpCompilation.Create("a.dll", options: options);
comp.GetDiagnostics().Verify();
CleanupAllGeneratedFiles(file.Path);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")]
public void SpecifyProperCodePage()
{
byte[] source = {
0x63, // c
0x6c, // l
0x61, // a
0x73, // s
0x73, // s
0x20, //
0xd0, 0x96, // Utf-8 Cyrillic character
0x7b, // {
0x7d, // }
};
var fileName = "a.cs";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile(fileName);
file.WriteAllBytes(source);
var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /t:library \"{file}\"", startFolder: dir.Path);
Assert.Equal("", output); // Autodetected UTF8, NO ERROR
output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/nologo /preferreduilang:en /t:library /codepage:20127 \"{file}\"", expectedRetCode: 1, startFolder: dir.Path); // 20127: US-ASCII
// 0xd0, 0x96 ==> ERROR
Assert.Equal(@"
a.cs(1,7): error CS1001: Identifier expected
a.cs(1,7): error CS1514: { expected
a.cs(1,7): error CS1513: } expected
a.cs(1,7): error CS8803: Top-level statements must precede namespace and type declarations.
a.cs(1,7): error CS1525: Invalid expression term '??'
a.cs(1,9): error CS1525: Invalid expression term '{'
a.cs(1,9): error CS1002: ; expected
".Trim(),
Regex.Replace(output, "^.*a.cs", "a.cs", RegexOptions.Multiline).Trim());
CleanupAllGeneratedFiles(file.Path);
}
[ConditionalFact(typeof(WindowsOnly))]
public void DefaultWin32ResForExe()
{
var source = @"
class C
{
static void Main() { }
}
";
CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest: null, expectedManifest:
@"<?xml version=""1.0"" encoding=""utf-16""?>
<ManifestResource Size=""490"">
<Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
<assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/>
<trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">
<security>
<requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">
<requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>]]></Contents>
</ManifestResource>");
}
[ConditionalFact(typeof(WindowsOnly))]
public void DefaultManifestForDll()
{
var source = @"
class C
{
}
";
CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest: null, expectedManifest: null);
}
[ConditionalFact(typeof(WindowsOnly))]
public void DefaultManifestForWinExe()
{
var source = @"
class C
{
static void Main() { }
}
";
CheckManifestString(source, OutputKind.WindowsApplication, explicitManifest: null, expectedManifest:
@"<?xml version=""1.0"" encoding=""utf-16""?>
<ManifestResource Size=""490"">
<Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
<assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/>
<trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">
<security>
<requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">
<requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>]]></Contents>
</ManifestResource>");
}
[ConditionalFact(typeof(WindowsOnly))]
public void DefaultManifestForAppContainerExe()
{
var source = @"
class C
{
static void Main() { }
}
";
CheckManifestString(source, OutputKind.WindowsRuntimeApplication, explicitManifest: null, expectedManifest:
@"<?xml version=""1.0"" encoding=""utf-16""?>
<ManifestResource Size=""490"">
<Contents><![CDATA[<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
<assemblyIdentity version=""1.0.0.0"" name=""MyApplication.app""/>
<trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">
<security>
<requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">
<requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>]]></Contents>
</ManifestResource>");
}
[ConditionalFact(typeof(WindowsOnly))]
public void DefaultManifestForWinMD()
{
var source = @"
class C
{
}
";
CheckManifestString(source, OutputKind.WindowsRuntimeMetadata, explicitManifest: null, expectedManifest: null);
}
[ConditionalFact(typeof(WindowsOnly))]
public void DefaultWin32ResForModule()
{
var source = @"
class C
{
}
";
CheckManifestString(source, OutputKind.NetModule, explicitManifest: null, expectedManifest: null);
}
[ConditionalFact(typeof(WindowsOnly))]
public void ExplicitWin32ResForExe()
{
var source = @"
class C
{
static void Main() { }
}
";
var explicitManifest =
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
<assemblyIdentity version=""1.0.0.0"" name=""Test.app""/>
<trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">
<security>
<requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">
<requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>";
var explicitManifestStream = new MemoryStream(Encoding.UTF8.GetBytes(explicitManifest));
var expectedManifest =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<ManifestResource Size=""476"">
<Contents><![CDATA[" +
explicitManifest +
@"]]></Contents>
</ManifestResource>";
CheckManifestString(source, OutputKind.ConsoleApplication, explicitManifest, expectedManifest);
}
// DLLs don't get the default manifest, but they do respect explicitly set manifests.
[ConditionalFact(typeof(WindowsOnly))]
public void ExplicitWin32ResForDll()
{
var source = @"
class C
{
static void Main() { }
}
";
var explicitManifest =
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
<assemblyIdentity version=""1.0.0.0"" name=""Test.app""/>
<trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">
<security>
<requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">
<requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>";
var expectedManifest =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<ManifestResource Size=""476"">
<Contents><![CDATA[" +
explicitManifest +
@"]]></Contents>
</ManifestResource>";
CheckManifestString(source, OutputKind.DynamicallyLinkedLibrary, explicitManifest, expectedManifest);
}
// Modules don't have manifests, even if one is explicitly specified.
[ConditionalFact(typeof(WindowsOnly))]
public void ExplicitWin32ResForModule()
{
var source = @"
class C
{
}
";
var explicitManifest =
@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>
<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">
<assemblyIdentity version=""1.0.0.0"" name=""Test.app""/>
<trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">
<security>
<requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">
<requestedExecutionLevel level=""asInvoker"" uiAccess=""false""/>
</requestedPrivileges>
</security>
</trustInfo>
</assembly>";
CheckManifestString(source, OutputKind.NetModule, explicitManifest, expectedManifest: null);
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr LoadLibraryEx(string lpFileName, IntPtr hFile, uint dwFlags);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FreeLibrary([In] IntPtr hFile);
private void CheckManifestString(string source, OutputKind outputKind, string explicitManifest, string expectedManifest)
{
var dir = Temp.CreateDirectory();
var sourceFile = dir.CreateFile("Test.cs").WriteAllText(source);
string outputFileName;
string target;
switch (outputKind)
{
case OutputKind.ConsoleApplication:
outputFileName = "Test.exe";
target = "exe";
break;
case OutputKind.WindowsApplication:
outputFileName = "Test.exe";
target = "winexe";
break;
case OutputKind.DynamicallyLinkedLibrary:
outputFileName = "Test.dll";
target = "library";
break;
case OutputKind.NetModule:
outputFileName = "Test.netmodule";
target = "module";
break;
case OutputKind.WindowsRuntimeMetadata:
outputFileName = "Test.winmdobj";
target = "winmdobj";
break;
case OutputKind.WindowsRuntimeApplication:
outputFileName = "Test.exe";
target = "appcontainerexe";
break;
default:
throw TestExceptionUtilities.UnexpectedValue(outputKind);
}
MockCSharpCompiler csc;
if (explicitManifest == null)
{
csc = CreateCSharpCompiler(null, dir.Path, new[]
{
string.Format("/target:{0}", target),
string.Format("/out:{0}", outputFileName),
Path.GetFileName(sourceFile.Path),
});
}
else
{
var manifestFile = dir.CreateFile("Test.config").WriteAllText(explicitManifest);
csc = CreateCSharpCompiler(null, dir.Path, new[]
{
string.Format("/target:{0}", target),
string.Format("/out:{0}", outputFileName),
string.Format("/win32manifest:{0}", Path.GetFileName(manifestFile.Path)),
Path.GetFileName(sourceFile.Path),
});
}
int actualExitCode = csc.Run(new StringWriter(CultureInfo.InvariantCulture));
Assert.Equal(0, actualExitCode);
//Open as data
IntPtr lib = LoadLibraryEx(Path.Combine(dir.Path, outputFileName), IntPtr.Zero, 0x00000002);
if (lib == IntPtr.Zero)
throw new Win32Exception(Marshal.GetLastWin32Error());
const string resourceType = "#24";
var resourceId = outputKind == OutputKind.DynamicallyLinkedLibrary ? "#2" : "#1";
uint manifestSize;
if (expectedManifest == null)
{
Assert.Throws<Win32Exception>(() => Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize));
}
else
{
IntPtr manifestResourcePointer = Win32Res.GetResource(lib, resourceId, resourceType, out manifestSize);
string actualManifest = Win32Res.ManifestResourceToXml(manifestResourcePointer, manifestSize);
Assert.Equal(expectedManifest, actualManifest);
}
FreeLibrary(lib);
}
[WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")]
[ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
public void ResponseFilesWithNoconfig_01()
{
string source = Temp.CreateFile("a.cs").WriteAllText(@"
public class C
{
public static void Main()
{
int x; // CS0168
}
}").Path;
string rsp = Temp.CreateFile().WriteAllText(@"
/warnaserror
").Path;
// Checks the base case without /noconfig (expect to see error)
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Contains("error CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal);
// Checks the case with /noconfig (expect to see warning, instead of error)
outWriter = new StringWriter(CultureInfo.InvariantCulture);
csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/noconfig", "/preferreduilang:en" });
exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal);
// Checks the case with /NOCONFIG (expect to see warning, instead of error)
outWriter = new StringWriter(CultureInfo.InvariantCulture);
csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/NOCONFIG", "/preferreduilang:en" });
exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal);
// Checks the case with -noconfig (expect to see warning, instead of error)
outWriter = new StringWriter(CultureInfo.InvariantCulture);
csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "-noconfig", "/preferreduilang:en" });
exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains("warning CS0168: The variable 'x' is declared but never used\r\n", outWriter.ToString(), StringComparison.Ordinal);
CleanupAllGeneratedFiles(source);
CleanupAllGeneratedFiles(rsp);
}
[WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")]
[ConditionalFact(typeof(WindowsOnly))]
public void ResponseFilesWithNoconfig_02()
{
string source = Temp.CreateFile("a.cs").WriteAllText(@"
public class C
{
public static void Main()
{
}
}").Path;
string rsp = Temp.CreateFile().WriteAllText(@"
/noconfig
").Path;
// Checks the case with /noconfig inside the response file (expect to see warning)
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal);
// Checks the case with /noconfig inside the response file as along with /nowarn (expect to see warning)
// to verify that this warning is not suppressed by the /nowarn option (See MSDN).
outWriter = new StringWriter(CultureInfo.InvariantCulture);
csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" });
exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal);
CleanupAllGeneratedFiles(source);
CleanupAllGeneratedFiles(rsp);
}
[WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")]
[ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
public void ResponseFilesWithNoconfig_03()
{
string source = Temp.CreateFile("a.cs").WriteAllText(@"
public class C
{
public static void Main()
{
}
}").Path;
string rsp = Temp.CreateFile().WriteAllText(@"
/NOCONFIG
").Path;
// Checks the case with /noconfig inside the response file (expect to see warning)
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal);
// Checks the case with /NOCONFIG inside the response file as along with /nowarn (expect to see warning)
// to verify that this warning is not suppressed by the /nowarn option (See MSDN).
outWriter = new StringWriter(CultureInfo.InvariantCulture);
csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" });
exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal);
CleanupAllGeneratedFiles(source);
CleanupAllGeneratedFiles(rsp);
}
[WorkItem(544926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544926")]
[ConditionalFact(typeof(WindowsOnly))]
public void ResponseFilesWithNoconfig_04()
{
string source = Temp.CreateFile("a.cs").WriteAllText(@"
public class C
{
public static void Main()
{
}
}").Path;
string rsp = Temp.CreateFile().WriteAllText(@"
-noconfig
").Path;
// Checks the case with /noconfig inside the response file (expect to see warning)
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal);
// Checks the case with -noconfig inside the response file as along with /nowarn (expect to see warning)
// to verify that this warning is not suppressed by the /nowarn option (See MSDN).
outWriter = new StringWriter(CultureInfo.InvariantCulture);
csc = CreateCSharpCompiler(rsp, WorkingDirectory, new[] { source, "/preferreduilang:en", "/nowarn:2023" });
exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains("warning CS2023: Ignoring /noconfig option because it was specified in a response file\r\n", outWriter.ToString(), StringComparison.Ordinal);
CleanupAllGeneratedFiles(source);
CleanupAllGeneratedFiles(rsp);
}
[Fact, WorkItem(530024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530024")]
public void NoStdLib()
{
var src = Temp.CreateFile("a.cs");
src.WriteAllText("public class C{}");
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/t:library", src.ToString() }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString().Trim());
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/nostdlib", "/t:library", src.ToString() }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("{FILE}(1,14): error CS0518: Predefined type 'System.Object' is not defined or imported",
outWriter.ToString().Replace(Path.GetFileName(src.Path), "{FILE}").Trim());
// Bug#15021: breaking change - empty source no error with /nostdlib
src.WriteAllText("namespace System { }");
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/langversion:8", src.ToString() }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(src.Path);
}
private string GetDefaultResponseFilePath()
{
var cscRsp = global::TestResources.ResourceLoader.GetResourceBlob("csc.rsp");
return Temp.CreateFile().WriteAllBytes(cscRsp).Path;
}
[Fact, WorkItem(530359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530359")]
public void NoStdLib02()
{
#region "source"
var source = @"
// <Title>A collection initializer can be declared with a user-defined IEnumerable that is declared in a user-defined System.Collections</Title>
using System.Collections;
class O<T> where T : new()
{
public T list = new T();
}
class C
{
static StructCollection sc = new StructCollection { 1 };
public static int Main()
{
ClassCollection cc = new ClassCollection { 2 };
var o1 = new O<ClassCollection> { list = { 5 } };
var o2 = new O<StructCollection> { list = sc };
return 0;
}
}
struct StructCollection : IEnumerable
{
public int added;
#region IEnumerable Members
public void Add(int t)
{
added = t;
}
#endregion
}
class ClassCollection : IEnumerable
{
public int added;
#region IEnumerable Members
public void Add(int t)
{
added = t;
}
#endregion
}
namespace System.Collections
{
public interface IEnumerable
{
void Add(int t);
}
}
";
#endregion
#region "mslib"
var mslib = @"
namespace System
{
public class Object {}
public struct Byte { }
public struct Int16 { }
public struct Int32 { }
public struct Int64 { }
public struct Single { }
public struct Double { }
public struct SByte { }
public struct UInt32 { }
public struct UInt64 { }
public struct Char { }
public struct Boolean { }
public struct UInt16 { }
public struct UIntPtr { }
public struct IntPtr { }
public class Delegate { }
public class String {
public int Length { get { return 10; } }
}
public class MulticastDelegate { }
public class Array { }
public class Exception { public Exception(string s){} }
public class Type { }
public class ValueType { }
public class Enum { }
public interface IEnumerable { }
public interface IDisposable { }
public class Attribute { }
public class ParamArrayAttribute { }
public struct Void { }
public struct RuntimeFieldHandle { }
public struct RuntimeTypeHandle { }
public class Activator
{
public static T CreateInstance<T>(){return default(T);}
}
namespace Collections
{
public interface IEnumerator { }
}
namespace Runtime
{
namespace InteropServices
{
public class OutAttribute { }
}
namespace CompilerServices
{
public class RuntimeHelpers { }
}
}
namespace Reflection
{
public class DefaultMemberAttribute { }
}
}
";
#endregion
var src = Temp.CreateFile("NoStdLib02.cs");
src.WriteAllText(source + mslib);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString().Trim());
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nostdlib", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString().Trim());
string OriginalSource = src.Path;
src = Temp.CreateFile("NoStdLib02b.cs");
src.WriteAllText(mslib);
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/nologo", "/noconfig", "/nostdlib", "/t:library", "/runtimemetadataversion:v4.0.30319", "/nowarn:8625", src.ToString() }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(OriginalSource);
CleanupAllGeneratedFiles(src.Path);
}
[Fact, WorkItem(546018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546018"), WorkItem(546020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546020"), WorkItem(546024, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546024"), WorkItem(546049, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546049")]
public void InvalidDefineSwitch()
{
var src = Temp.CreateFile("a.cs");
src.WriteAllText("public class C{}");
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", src.ToString(), "/define" }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define' option", outWriter.ToString().Trim());
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:""""" }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim());
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define: " }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim());
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:" }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS2006: Command-line syntax error: Missing '<text>' for '/define:' option", outWriter.ToString().Trim());
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,,," }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim());
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:,blah,Blah" }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", outWriter.ToString().Trim());
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a;;b@" }).Run(outWriter);
Assert.Equal(0, exitCode);
var errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; '' is not a valid identifier", errorLines[0]);
Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", errorLines[1]);
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), "/define:a,b@;" }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("warning CS2029: Invalid name for a preprocessing symbol; 'b@' is not a valid identifier", outWriter.ToString().Trim());
//Bug 531612 - Native would normally not give the 2nd warning
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/t:library", src.ToString(), @"/define:OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1", @"/d:TRACE=TRUE,DEBUG=TRUE" }).Run(outWriter);
Assert.Equal(0, exitCode);
errorLines = outWriter.ToString().Trim().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'OE_WIN32=-1:LANG_HOST_EN=-1:LANG_OE_EN=-1:LANG_PRJ_EN=-1:HOST_COM20SDKEVERETT=-1:EXEMODE=-1:OE_NT5=-1:Win32=-1' is not a valid identifier", errorLines[0]);
Assert.Equal(@"warning CS2029: Invalid name for a preprocessing symbol; 'TRACE=TRUE' is not a valid identifier", errorLines[1]);
CleanupAllGeneratedFiles(src.Path);
}
[WorkItem(733242, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/733242")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void Bug733242()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("a.cs");
src.WriteAllText(
@"
/// <summary>ABC...XYZ</summary>
class C {} ");
var xml = dir.CreateFile("a.xml");
xml.WriteAllText("EMPTY");
using (var xmlFileHandle = File.Open(xml.ToString(), FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite))
{
var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString());
Assert.Equal("", output.Trim());
Assert.True(File.Exists(Path.Combine(dir.ToString(), "a.xml")));
using (var reader = new StreamReader(xmlFileHandle))
{
var content = reader.ReadToEnd();
Assert.Equal(
@"<?xml version=""1.0""?>
<doc>
<assembly>
<name>a</name>
</assembly>
<members>
<member name=""T:C"">
<summary>ABC...XYZ</summary>
</member>
</members>
</doc>".Trim(), content.Trim());
}
}
CleanupAllGeneratedFiles(src.Path);
CleanupAllGeneratedFiles(xml.Path);
}
[WorkItem(768605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768605")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void Bug768605()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("a.cs");
src.WriteAllText(
@"
/// <summary>ABC</summary>
class C {}
/// <summary>XYZ</summary>
class E {}
");
var xml = dir.CreateFile("a.xml");
xml.WriteAllText("EMPTY");
var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString());
Assert.Equal("", output.Trim());
using (var reader = new StreamReader(xml.ToString()))
{
var content = reader.ReadToEnd();
Assert.Equal(
@"<?xml version=""1.0""?>
<doc>
<assembly>
<name>a</name>
</assembly>
<members>
<member name=""T:C"">
<summary>ABC</summary>
</member>
<member name=""T:E"">
<summary>XYZ</summary>
</member>
</members>
</doc>".Trim(), content.Trim());
}
src.WriteAllText(
@"
/// <summary>ABC</summary>
class C {}
");
output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /t:library /doc:\"{1}\" \"{0}\"", src.ToString(), xml.ToString()), startFolder: dir.ToString());
Assert.Equal("", output.Trim());
using (var reader = new StreamReader(xml.ToString()))
{
var content = reader.ReadToEnd();
Assert.Equal(
@"<?xml version=""1.0""?>
<doc>
<assembly>
<name>a</name>
</assembly>
<members>
<member name=""T:C"">
<summary>ABC</summary>
</member>
</members>
</doc>".Trim(), content.Trim());
}
CleanupAllGeneratedFiles(src.Path);
CleanupAllGeneratedFiles(xml.Path);
}
[Fact]
public void ParseFullpaths()
{
var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
Assert.False(parsedArgs.PrintFullPaths);
parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths" }, WorkingDirectory);
Assert.True(parsedArgs.PrintFullPaths);
parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths:" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code);
parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths: " }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code);
parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code);
parsedArgs = DefaultParse(new[] { "a.cs", "/fullpaths+:" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_BadSwitch, parsedArgs.Errors.First().Code);
}
[Fact]
public void CheckFullpaths()
{
string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
public class C
{
public static void Main()
{
string x;
}
}").Path;
var baseDir = Path.GetDirectoryName(source);
var fileName = Path.GetFileName(source);
// Checks the base case without /fullpaths (expect to see relative path name)
// c:\temp> csc.exe c:\temp\a.cs
// a.cs(6,16): warning CS0168: The variable 'x' is declared but never used
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/preferreduilang:en" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal);
// Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see relative path name)
// c:\temp> csc.exe c:\temp\example\a.cs
// example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used
outWriter = new StringWriter(CultureInfo.InvariantCulture);
csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en" });
exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains(fileName + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal);
Assert.DoesNotContain(source, outWriter.ToString(), StringComparison.Ordinal);
// Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name)
// c:\temp> csc.exe c:\test\a.cs
// c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used
outWriter = new StringWriter(CultureInfo.InvariantCulture);
csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en" });
exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal);
// Checks the case with /fullpaths (expect to see the full paths)
// c:\temp> csc.exe c:\temp\a.cs /fullpaths
// c:\temp\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used
outWriter = new StringWriter(CultureInfo.InvariantCulture);
csc = CreateCSharpCompiler(null, baseDir, new[] { source, "/fullpaths", "/preferreduilang:en" });
exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains(source + @"(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal);
// Checks the base case without /fullpaths when the file is located in the sub-folder (expect to see the full path name)
// c:\temp> csc.exe c:\temp\example\a.cs /fullpaths
// c:\temp\example\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used
outWriter = new StringWriter(CultureInfo.InvariantCulture);
csc = CreateCSharpCompiler(null, Directory.GetParent(baseDir).FullName, new[] { source, "/preferreduilang:en", "/fullpaths" });
exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal);
// Checks the base case without /fullpaths when the file is not located under the base directory (expect to see the full path name)
// c:\temp> csc.exe c:\test\a.cs /fullpaths
// c:\test\a.cs(6,16): warning CS0168: The variable 'x' is declared but never used
outWriter = new StringWriter(CultureInfo.InvariantCulture);
csc = CreateCSharpCompiler(null, Temp.CreateDirectory().Path, new[] { source, "/preferreduilang:en", "/fullpaths" });
exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Contains(source + "(6,16): warning CS0168: The variable 'x' is declared but never used", outWriter.ToString(), StringComparison.Ordinal);
CleanupAllGeneratedFiles(source);
CleanupAllGeneratedFiles(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(source)), Path.GetFileName(source)));
}
[Fact]
public void DefaultResponseFile()
{
var sdkDirectory = SdkDirectory;
MockCSharpCompiler csc = new MockCSharpCompiler(
GetDefaultResponseFilePath(),
RuntimeUtilities.CreateBuildPaths(WorkingDirectory, sdkDirectory),
new string[0]);
AssertEx.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[]
{
MscorlibFullPath,
"Accessibility.dll",
"Microsoft.CSharp.dll",
"System.Configuration.dll",
"System.Configuration.Install.dll",
"System.Core.dll",
"System.Data.dll",
"System.Data.DataSetExtensions.dll",
"System.Data.Linq.dll",
"System.Data.OracleClient.dll",
"System.Deployment.dll",
"System.Design.dll",
"System.DirectoryServices.dll",
"System.dll",
"System.Drawing.Design.dll",
"System.Drawing.dll",
"System.EnterpriseServices.dll",
"System.Management.dll",
"System.Messaging.dll",
"System.Runtime.Remoting.dll",
"System.Runtime.Serialization.dll",
"System.Runtime.Serialization.Formatters.Soap.dll",
"System.Security.dll",
"System.ServiceModel.dll",
"System.ServiceModel.Web.dll",
"System.ServiceProcess.dll",
"System.Transactions.dll",
"System.Web.dll",
"System.Web.Extensions.Design.dll",
"System.Web.Extensions.dll",
"System.Web.Mobile.dll",
"System.Web.RegularExpressions.dll",
"System.Web.Services.dll",
"System.Windows.Forms.dll",
"System.Workflow.Activities.dll",
"System.Workflow.ComponentModel.dll",
"System.Workflow.Runtime.dll",
"System.Xml.dll",
"System.Xml.Linq.dll",
}, StringComparer.OrdinalIgnoreCase);
}
[Fact]
public void DefaultResponseFileNoConfig()
{
MockCSharpCompiler csc = CreateCSharpCompiler(GetDefaultResponseFilePath(), WorkingDirectory, new[] { "/noconfig" });
Assert.Equal(csc.Arguments.MetadataReferences.Select(r => r.Reference), new string[]
{
MscorlibFullPath,
}, StringComparer.OrdinalIgnoreCase);
}
[Fact, WorkItem(545954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545954")]
public void TestFilterParseDiagnostics()
{
string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
#pragma warning disable 440
using global = A; // CS0440
class A
{
static void Main() {
#pragma warning suppress 440
}
}").Path;
var baseDir = Path.GetDirectoryName(source);
var fileName = Path.GetFileName(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", source.ToString() }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal(Path.GetFileName(source) + "(7,17): warning CS1634: Expected 'disable' or 'restore'", outWriter.ToString().Trim());
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/nowarn:1634", source.ToString() }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString().Trim());
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", Path.Combine(baseDir, "nonexistent.cs"), source.ToString() }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS2001: Source file '" + Path.Combine(baseDir, "nonexistent.cs") + "' could not be found.", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(source);
}
[Fact, WorkItem(546058, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546058")]
public void TestNoWarnParseDiagnostics()
{
string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
class Test
{
static void Main()
{
//Generates warning CS1522: Empty switch block
switch (1) { }
//Generates warning CS0642: Possible mistaken empty statement
while (false) ;
{ }
}
}
").Path;
var baseDir = Path.GetDirectoryName(source);
var fileName = Path.GetFileName(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1522,642", source.ToString() }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(source);
}
[Fact, WorkItem(41610, "https://github.com/dotnet/roslyn/issues/41610")]
public void TestWarnAsError_CS8632()
{
string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
public class C
{
public string? field;
public static void Main()
{
}
}
").Path;
var baseDir = Path.GetDirectoryName(source);
var fileName = Path.GetFileName(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror:nullable", source.ToString() }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal(
$@"{fileName}(4,18): error CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context.", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(source);
}
[Fact, WorkItem(546076, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546076")]
public void TestWarnAsError_CS1522()
{
string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
public class Test
{
// CS0169 (level 3)
private int x;
// CS0109 (level 4)
public new void Method() { }
public static int Main()
{
int i = 5;
// CS1522 (level 1)
switch (i) { }
return 0;
// CS0162 (level 2)
i = 6;
}
}
").Path;
var baseDir = Path.GetDirectoryName(source);
var fileName = Path.GetFileName(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, baseDir, new[] { "/nologo", "/preferreduilang:en", "/warn:3", "/warnaserror", source.ToString() }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal(
$@"{fileName}(12,20): error CS1522: Empty switch block
{fileName}(15,9): error CS0162: Unreachable code detected
{fileName}(5,17): error CS0169: The field 'Test.x' is never used", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(source);
}
[Fact(), WorkItem(546025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546025")]
public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_01()
{
string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path;
string badres = Temp.CreateFile().WriteAllBytes(TestResources.DiagnosticTests.badresfile).Path;
var baseDir = Path.GetDirectoryName(source);
var fileName = Path.GetFileName(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, baseDir, new[]
{
"/nologo",
"/preferreduilang:en",
"/win32res:" + badres,
source
}).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS1583: Error reading Win32 resources -- Image is too small.", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(source);
CleanupAllGeneratedFiles(badres);
}
[Fact(), WorkItem(217718, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=217718")]
public void TestWin32ResWithBadResFile_CS1583ERR_BadWin32Res_02()
{
string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"class Test { static void Main() {} }").Path;
string badres = Temp.CreateFile().WriteAllBytes(new byte[] { 0, 0 }).Path;
var baseDir = Path.GetDirectoryName(source);
var fileName = Path.GetFileName(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, baseDir, new[]
{
"/nologo",
"/preferreduilang:en",
"/win32res:" + badres,
source
}).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS1583: Error reading Win32 resources -- Unrecognized resource file format.", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(source);
CleanupAllGeneratedFiles(badres);
}
[Fact, WorkItem(546114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546114")]
public void TestFilterCommandLineDiagnostics()
{
string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
class A
{
static void Main() { }
}").Path;
var baseDir = Path.GetDirectoryName(source);
var fileName = Path.GetFileName(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", "/out:goo.dll", "/nowarn:2008" }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString().Trim());
System.IO.File.Delete(System.IO.Path.Combine(baseDir, "goo.dll"));
CleanupAllGeneratedFiles(source);
}
[Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")]
public void CS1691WRN_BadWarningNumber_Bug15905()
{
string source = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(@"
class Program
{
#pragma warning disable 1998
public static void Main() { }
#pragma warning restore 1998
} ").Path;
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
// Repro case 1
int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/warnaserror", source.ToString() }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString().Trim());
// Repro case 2
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/nowarn:1998", source.ToString() }).Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(source);
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void ExistingPdb()
{
var dir = Temp.CreateDirectory();
var source1 = dir.CreateFile("program1.cs").WriteAllText(@"
class " + new string('a', 10000) + @"
{
public static void Main()
{
}
}");
var source2 = dir.CreateFile("program2.cs").WriteAllText(@"
class Program2
{
public static void Main() { }
}");
var source3 = dir.CreateFile("program3.cs").WriteAllText(@"
class Program3
{
public static void Main() { }
}");
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int oldSize = 16 * 1024;
var exe = dir.CreateFile("Program.exe");
using (var stream = File.OpenWrite(exe.Path))
{
byte[] buffer = new byte[oldSize];
stream.Write(buffer, 0, buffer.Length);
}
var pdb = dir.CreateFile("Program.pdb");
using (var stream = File.OpenWrite(pdb.Path))
{
byte[] buffer = new byte[oldSize];
stream.Write(buffer, 0, buffer.Length);
}
int exitCode1 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source1.Path }).Run(outWriter);
Assert.NotEqual(0, exitCode1);
ValidateZeroes(exe.Path, oldSize);
ValidateZeroes(pdb.Path, oldSize);
int exitCode2 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source2.Path }).Run(outWriter);
Assert.Equal(0, exitCode2);
using (var peFile = File.OpenRead(exe.Path))
{
PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false);
}
Assert.True(new FileInfo(exe.Path).Length < oldSize);
Assert.True(new FileInfo(pdb.Path).Length < oldSize);
int exitCode3 = CreateCSharpCompiler(null, dir.Path, new[] { "/debug:full", "/out:Program.exe", source3.Path }).Run(outWriter);
Assert.Equal(0, exitCode3);
using (var peFile = File.OpenRead(exe.Path))
{
PdbValidation.ValidateDebugDirectory(peFile, null, pdb.Path, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic: false);
}
}
private static void ValidateZeroes(string path, int count)
{
using (var stream = File.OpenRead(path))
{
byte[] buffer = new byte[count];
stream.Read(buffer, 0, buffer.Length);
for (int i = 0; i < buffer.Length; i++)
{
if (buffer[i] != 0)
{
Assert.True(false);
}
}
}
}
/// <summary>
/// When the output file is open with <see cref="FileShare.Read"/> | <see cref="FileShare.Delete"/>
/// the compiler should delete the file to unblock build while allowing the reader to continue
/// reading the previous snapshot of the file content.
///
/// On Windows we can read the original data directly from the stream without creating a memory map.
/// </summary>
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
public void FileShareDeleteCompatibility_Windows()
{
var dir = Temp.CreateDirectory();
var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }");
var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL");
var libPdb = dir.CreateFile("Lib.pdb").WriteAllText("PDB");
var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/debug:full", libSrc.Path }).Run(outWriter);
if (exitCode != 0)
{
AssertEx.AssertEqualToleratingWhitespaceDifferences("", outWriter.ToString());
}
Assert.Equal(0, exitCode);
AssertEx.Equal(new byte[] { 0x4D, 0x5A }, ReadBytes(libDll.Path, 2));
AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3));
AssertEx.Equal(new byte[] { 0x4D, 0x69 }, ReadBytes(libPdb.Path, 2));
AssertEx.Equal(new[] { (byte)'P', (byte)'D', (byte)'B' }, ReadBytes(fsPdb, 3));
fsDll.Dispose();
fsPdb.Dispose();
AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order());
}
/// <summary>
/// On Linux/Mac <see cref="FileShare.Delete"/> on its own doesn't do anything.
/// We need to create the actual memory map. This works on Windows as well.
/// </summary>
[WorkItem(8896, "https://github.com/dotnet/roslyn/issues/8896")]
[ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void FileShareDeleteCompatibility_Xplat()
{
var bytes = TestResources.MetadataTests.InterfaceAndClass.CSClasses01;
var mvid = ReadMvid(new MemoryStream(bytes));
var dir = Temp.CreateDirectory();
var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }");
var libDll = dir.CreateFile("Lib.dll").WriteAllBytes(bytes);
var libPdb = dir.CreateFile("Lib.pdb").WriteAllBytes(bytes);
var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
var fsPdb = new FileStream(libPdb.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
var peDll = new PEReader(fsDll);
var pePdb = new PEReader(fsPdb);
// creates memory map view:
var imageDll = peDll.GetEntireImage();
var imagePdb = pePdb.GetEntireImage();
var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $"/target:library /debug:portable \"{libSrc.Path}\"", startFolder: dir.ToString());
AssertEx.AssertEqualToleratingWhitespaceDifferences($@"
Microsoft (R) Visual C# Compiler version {s_compilerVersion}
Copyright (C) Microsoft Corporation. All rights reserved.", output);
// reading original content from the memory map:
Assert.Equal(mvid, ReadMvid(new MemoryStream(imageDll.GetContent().ToArray())));
Assert.Equal(mvid, ReadMvid(new MemoryStream(imagePdb.GetContent().ToArray())));
// reading original content directly from the streams:
fsDll.Position = 0;
fsPdb.Position = 0;
Assert.Equal(mvid, ReadMvid(fsDll));
Assert.Equal(mvid, ReadMvid(fsPdb));
// reading new content from the file:
using (var fsNewDll = File.OpenRead(libDll.Path))
{
Assert.NotEqual(mvid, ReadMvid(fsNewDll));
}
// Portable PDB metadata signature:
AssertEx.Equal(new[] { (byte)'B', (byte)'S', (byte)'J', (byte)'B' }, ReadBytes(libPdb.Path, 4));
// dispose PEReaders (they dispose the underlying file streams)
peDll.Dispose();
pePdb.Dispose();
AssertEx.Equal(new[] { "Lib.cs", "Lib.dll", "Lib.pdb" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order());
// files can be deleted now:
File.Delete(libSrc.Path);
File.Delete(libDll.Path);
File.Delete(libPdb.Path);
// directory can be deleted (should be empty):
Directory.Delete(dir.Path, recursive: false);
}
private static Guid ReadMvid(Stream stream)
{
using (var peReader = new PEReader(stream, PEStreamOptions.LeaveOpen))
{
var mdReader = peReader.GetMetadataReader();
return mdReader.GetGuid(mdReader.GetModuleDefinition().Mvid);
}
}
// Seems like File.SetAttributes(libDll.Path, FileAttributes.ReadOnly) doesn't restrict access to the file on Mac (Linux passes).
[ConditionalFact(typeof(WindowsOnly)), WorkItem(8939, "https://github.com/dotnet/roslyn/issues/8939")]
public void FileShareDeleteCompatibility_ReadOnlyFiles()
{
var dir = Temp.CreateDirectory();
var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }");
var libDll = dir.CreateFile("Lib.dll").WriteAllText("DLL");
File.SetAttributes(libDll.Path, FileAttributes.ReadOnly);
var fsDll = new FileStream(libDll.Path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter);
Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString());
AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(libDll.Path, 3));
AssertEx.Equal(new[] { (byte)'D', (byte)'L', (byte)'L' }, ReadBytes(fsDll, 3));
fsDll.Dispose();
AssertEx.Equal(new[] { "Lib.cs", "Lib.dll" }, Directory.GetFiles(dir.Path).Select(p => Path.GetFileName(p)).Order());
}
[Fact]
public void FileShareDeleteCompatibility_ExistingDirectory()
{
var dir = Temp.CreateDirectory();
var libSrc = dir.CreateFile("Lib.cs").WriteAllText("class C { }");
var libDll = dir.CreateDirectory("Lib.dll");
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, dir.Path, new[] { "/target:library", "/preferreduilang:en", libSrc.Path }).Run(outWriter);
Assert.Contains($"error CS2012: Cannot open '{libDll.Path}' for writing", outWriter.ToString());
}
private byte[] ReadBytes(Stream stream, int count)
{
var buffer = new byte[count];
stream.Read(buffer, 0, count);
return buffer;
}
private byte[] ReadBytes(string path, int count)
{
using (var stream = File.OpenRead(path))
{
return ReadBytes(stream, count);
}
}
[Fact]
public void IOFailure_DisposeOutputFile()
{
var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path);
var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe");
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", srcPath });
csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) =>
{
if (file == exePath)
{
return new TestStream(backingStream: new MemoryStream(),
dispose: () => { throw new IOException("Fake IOException"); });
}
return File.Open(file, mode, access, share);
});
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
Assert.Equal(1, csc.Run(outWriter));
Assert.Contains($"error CS0016: Could not write to output file '{exePath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString());
}
[Fact]
public void IOFailure_DisposePdbFile()
{
var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path);
var exePath = Path.Combine(Path.GetDirectoryName(srcPath), "test.exe");
var pdbPath = Path.ChangeExtension(exePath, "pdb");
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug", $"/out:{exePath}", srcPath });
csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) =>
{
if (file == pdbPath)
{
return new TestStream(backingStream: new MemoryStream(),
dispose: () => { throw new IOException("Fake IOException"); });
}
return File.Open(file, mode, access, share);
});
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
Assert.Equal(1, csc.Run(outWriter));
Assert.Contains($"error CS0016: Could not write to output file '{pdbPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString());
}
[Fact]
public void IOFailure_DisposeXmlFile()
{
var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path);
var xmlPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.xml");
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/doc:{xmlPath}", srcPath });
csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) =>
{
if (file == xmlPath)
{
return new TestStream(backingStream: new MemoryStream(),
dispose: () => { throw new IOException("Fake IOException"); });
}
return File.Open(file, mode, access, share);
});
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
Assert.Equal(1, csc.Run(outWriter));
Assert.Equal($"error CS0016: Could not write to output file '{xmlPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString());
}
[Theory]
[InlineData("portable")]
[InlineData("full")]
public void IOFailure_DisposeSourceLinkFile(string format)
{
var srcPath = MakeTrivialExe(Temp.CreateDirectory().Path);
var sourceLinkPath = Path.Combine(Path.GetDirectoryName(srcPath), "test.json");
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/debug:" + format, $"/sourcelink:{sourceLinkPath}", srcPath });
csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) =>
{
if (file == sourceLinkPath)
{
return new TestStream(backingStream: new MemoryStream(Encoding.UTF8.GetBytes(@"
{
""documents"": {
""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*""
}
}
")),
dispose: () => { throw new IOException("Fake IOException"); });
}
return File.Open(file, mode, access, share);
});
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
Assert.Equal(1, csc.Run(outWriter));
Assert.Equal($"error CS0016: Could not write to output file '{sourceLinkPath}' -- 'Fake IOException'{Environment.NewLine}", outWriter.ToString());
}
[Fact]
public void IOFailure_OpenOutputFile()
{
string sourcePath = MakeTrivialExe();
string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe");
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", $"/out:{exePath}", sourcePath });
csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) =>
{
if (file == exePath)
{
throw new IOException();
}
return File.Open(file, mode, access, share);
});
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
Assert.Equal(1, csc.Run(outWriter));
Assert.Contains($"error CS2012: Cannot open '{exePath}' for writing", outWriter.ToString());
System.IO.File.Delete(sourcePath);
System.IO.File.Delete(exePath);
CleanupAllGeneratedFiles(sourcePath);
}
[Fact]
public void IOFailure_OpenPdbFileNotCalled()
{
string sourcePath = MakeTrivialExe();
string exePath = Path.Combine(Path.GetDirectoryName(sourcePath), "test.exe");
string pdbPath = Path.ChangeExtension(exePath, ".pdb");
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/debug-", $"/out:{exePath}", sourcePath });
csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) =>
{
if (file == pdbPath)
{
throw new IOException();
}
return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share);
});
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
Assert.Equal(0, csc.Run(outWriter));
System.IO.File.Delete(sourcePath);
System.IO.File.Delete(exePath);
System.IO.File.Delete(pdbPath);
CleanupAllGeneratedFiles(sourcePath);
}
[Fact]
public void IOFailure_OpenXmlFinal()
{
string sourcePath = MakeTrivialExe();
string xmlPath = Path.Combine(WorkingDirectory, "Test.xml");
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/preferreduilang:en", "/doc:" + xmlPath, sourcePath });
csc.FileSystem = TestableFileSystem.CreateForStandard(openFileFunc: (file, mode, access, share) =>
{
if (file == xmlPath)
{
throw new IOException();
}
else
{
return File.Open(file, (FileMode)mode, (FileAccess)access, (FileShare)share);
}
});
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = csc.Run(outWriter);
var expectedOutput = string.Format("error CS0016: Could not write to output file '{0}' -- 'I/O error occurred.'", xmlPath);
Assert.Equal(expectedOutput, outWriter.ToString().Trim());
Assert.NotEqual(0, exitCode);
System.IO.File.Delete(xmlPath);
System.IO.File.Delete(sourcePath);
CleanupAllGeneratedFiles(sourcePath);
}
private string MakeTrivialExe(string directory = null)
{
return Temp.CreateFile(directory: directory, prefix: "", extension: ".cs").WriteAllText(@"
class Program
{
public static void Main() { }
} ").Path;
}
[Fact, WorkItem(546452, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546452")]
public void CS1691WRN_BadWarningNumber_AllErrorCodes()
{
const int jump = 200;
for (int i = 0; i < 8000; i += (8000 / jump))
{
int startErrorCode = (int)i * jump;
int endErrorCode = startErrorCode + jump;
string source = ComputeSourceText(startErrorCode, endErrorCode);
// Previous versions of the compiler used to report a warning (CS1691)
// whenever an unrecognized warning code was supplied in a #pragma directive
// (or via /nowarn /warnaserror flags on the command line).
// Going forward, we won't generate any warning in such cases. This will make
// maintenance of backwards compatibility easier (we no longer need to worry
// about breaking existing projects / command lines if we deprecate / remove
// an old warning code).
Test(source, startErrorCode, endErrorCode);
}
}
private static string ComputeSourceText(int startErrorCode, int endErrorCode)
{
string pragmaDisableWarnings = String.Empty;
for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++)
{
string pragmaDisableStr = @"#pragma warning disable " + errorCode.ToString() + @"
";
pragmaDisableWarnings += pragmaDisableStr;
}
return pragmaDisableWarnings + @"
public class C
{
public static void Main() { }
}";
}
private void Test(string source, int startErrorCode, int endErrorCode)
{
string sourcePath = Temp.CreateFile(prefix: "", extension: ".cs").WriteAllText(source).Path;
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", sourcePath }).Run(outWriter);
Assert.Equal(0, exitCode);
var cscOutput = outWriter.ToString().Trim();
for (int errorCode = startErrorCode; errorCode < endErrorCode; errorCode++)
{
Assert.True(cscOutput == string.Empty, "Failed at error code: " + errorCode);
}
CleanupAllGeneratedFiles(sourcePath);
}
[Fact]
public void WriteXml()
{
var source = @"
/// <summary>
/// A subtype of <see cref=""object""/>.
/// </summary>
public class C { }
";
var sourcePath = Temp.CreateFile(directory: WorkingDirectory, extension: ".cs").WriteAllText(source).Path;
string xmlPath = Path.Combine(WorkingDirectory, "Test.xml");
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/target:library", "/out:Test.dll", "/doc:" + xmlPath, sourcePath });
var writer = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = csc.Run(writer);
if (exitCode != 0)
{
Console.WriteLine(writer.ToString());
Assert.Equal(0, exitCode);
}
var bytes = File.ReadAllBytes(xmlPath);
var actual = new string(Encoding.UTF8.GetChars(bytes));
var expected = @"
<?xml version=""1.0""?>
<doc>
<assembly>
<name>Test</name>
</assembly>
<members>
<member name=""T:C"">
<summary>
A subtype of <see cref=""T:System.Object""/>.
</summary>
</member>
</members>
</doc>
";
Assert.Equal(expected.Trim(), actual.Trim());
System.IO.File.Delete(xmlPath);
System.IO.File.Delete(sourcePath);
CleanupAllGeneratedFiles(sourcePath);
CleanupAllGeneratedFiles(xmlPath);
}
[WorkItem(546468, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546468")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
public void CS2002WRN_FileAlreadyIncluded()
{
const string cs2002 = @"warning CS2002: Source file '{0}' specified multiple times";
TempDirectory tempParentDir = Temp.CreateDirectory();
TempDirectory tempDir = tempParentDir.CreateDirectory("tmpDir");
TempFile tempFile = tempDir.CreateFile("a.cs").WriteAllText(@"public class A { }");
// Simple case
var commandLineArgs = new[] { "a.cs", "a.cs" };
// warning CS2002: Source file 'a.cs' specified multiple times
string aWrnString = String.Format(cs2002, "a.cs");
TestCS2002(commandLineArgs, tempDir.Path, 0, aWrnString);
// Multiple duplicates
commandLineArgs = new[] { "a.cs", "a.cs", "a.cs" };
// warning CS2002: Source file 'a.cs' specified multiple times
var warnings = new[] { aWrnString };
TestCS2002(commandLineArgs, tempDir.Path, 0, warnings);
// Case-insensitive
commandLineArgs = new[] { "a.cs", "A.cs" };
// warning CS2002: Source file 'A.cs' specified multiple times
string AWrnString = String.Format(cs2002, "A.cs");
TestCS2002(commandLineArgs, tempDir.Path, 0, AWrnString);
// Different extensions
tempDir.CreateFile("a.csx");
commandLineArgs = new[] { "a.cs", "a.csx" };
// No errors or warnings
TestCS2002(commandLineArgs, tempDir.Path, 0, String.Empty);
// Absolute vs Relative
commandLineArgs = new[] { @"tmpDir\a.cs", tempFile.Path };
// warning CS2002: Source file 'tmpDir\a.cs' specified multiple times
string tmpDiraString = String.Format(cs2002, @"tmpDir\a.cs");
TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString);
// Both relative
commandLineArgs = new[] { @"tmpDir\..\tmpDir\a.cs", @"tmpDir\a.cs" };
// warning CS2002: Source file 'tmpDir\a.cs' specified multiple times
TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString);
// With wild cards
commandLineArgs = new[] { tempFile.Path, @"tmpDir\*.cs" };
// warning CS2002: Source file 'tmpDir\a.cs' specified multiple times
TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString);
// "/recurse" scenarios
commandLineArgs = new[] { @"/recurse:a.cs", @"tmpDir\a.cs" };
// warning CS2002: Source file 'tmpDir\a.cs' specified multiple times
TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString);
commandLineArgs = new[] { @"/recurse:a.cs", @"/recurse:tmpDir\..\tmpDir\*.cs" };
// warning CS2002: Source file 'tmpDir\a.cs' specified multiple times
TestCS2002(commandLineArgs, tempParentDir.Path, 0, tmpDiraString);
// Invalid file/path characters
const string cs1504 = @"error CS1504: Source file '{0}' could not be opened -- {1}";
commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, "tmpDir\a.cs" };
// error CS1504: Source file '{0}' could not be opened: Illegal characters in path.
var formattedcs1504Str = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, "tmpDir\a.cs"), "Illegal characters in path.");
TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504Str);
commandLineArgs = new[] { tempFile.Path, @"tmpDi\r*a?.cs" };
var parseDiags = new[] {
// error CS2021: File name 'tmpDi\r*a?.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(@"tmpDi\r*a?.cs"),
// error CS2001: Source file 'tmpDi\r*a?.cs' could not be found.
Diagnostic(ErrorCode.ERR_FileNotFound).WithArguments(@"tmpDi\r*a?.cs")};
TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags);
char currentDrive = Directory.GetCurrentDirectory()[0];
commandLineArgs = new[] { tempFile.Path, currentDrive + @":a.cs" };
parseDiags = new[] {
// error CS2021: File name 'e:a.cs' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Diagnostic(ErrorCode.FTL_InvalidInputFileName).WithArguments(currentDrive + @":a.cs")};
TestCS2002(commandLineArgs, tempParentDir.Path, 1, (string[])null, parseDiags);
commandLineArgs = new[] { "/preferreduilang:en", tempFile.Path, @":a.cs" };
// error CS1504: Source file '{0}' could not be opened: {1}
var formattedcs1504 = String.Format(cs1504, PathUtilities.CombineAbsoluteAndRelativePaths(tempParentDir.Path, @":a.cs"), @"The given path's format is not supported.");
TestCS2002(commandLineArgs, tempParentDir.Path, 1, formattedcs1504);
CleanupAllGeneratedFiles(tempFile.Path);
System.IO.Directory.Delete(tempParentDir.Path, true);
}
private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string compileDiagnostic, params DiagnosticDescription[] parseDiagnostics)
{
TestCS2002(commandLineArgs, baseDirectory, expectedExitCode, new[] { compileDiagnostic }, parseDiagnostics);
}
private void TestCS2002(string[] commandLineArgs, string baseDirectory, int expectedExitCode, string[] compileDiagnostics, params DiagnosticDescription[] parseDiagnostics)
{
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var allCommandLineArgs = new[] { "/nologo", "/preferreduilang:en", "/t:library" }.Concat(commandLineArgs).ToArray();
// Verify command line parser diagnostics.
DefaultParse(allCommandLineArgs, baseDirectory).Errors.Verify(parseDiagnostics);
// Verify compile.
int exitCode = CreateCSharpCompiler(null, baseDirectory, allCommandLineArgs).Run(outWriter);
Assert.Equal(expectedExitCode, exitCode);
if (parseDiagnostics.IsEmpty())
{
// Verify compile diagnostics.
string outString = String.Empty;
for (int i = 0; i < compileDiagnostics.Length; i++)
{
if (i != 0)
{
outString += @"
";
}
outString += compileDiagnostics[i];
}
Assert.Equal(outString, outWriter.ToString().Trim());
}
else
{
Assert.Null(compileDiagnostics);
}
}
[Fact]
public void ErrorLineEnd()
{
var tree = SyntaxFactory.ParseSyntaxTree("class C public { }", path: "goo");
var comp = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/errorendlocation" });
var loc = new SourceLocation(tree.GetCompilationUnitRoot().FindToken(6));
var diag = new CSDiagnostic(new DiagnosticInfo(MessageProvider.Instance, (int)ErrorCode.ERR_MetadataNameTooLong), loc);
var text = comp.DiagnosticFormatter.Format(diag);
string stringStart = "goo(1,7,1,8)";
Assert.Equal(stringStart, text.Substring(0, stringStart.Length));
}
[Fact]
public void ReportAnalyzer()
{
var parsedArgs1 = DefaultParse(new[] { "a.cs", "/reportanalyzer" }, WorkingDirectory);
Assert.True(parsedArgs1.ReportAnalyzer);
var parsedArgs2 = DefaultParse(new[] { "a.cs", "" }, WorkingDirectory);
Assert.False(parsedArgs2.ReportAnalyzer);
}
[Fact]
public void ReportAnalyzerOutput()
{
var srcFile = Temp.CreateFile().WriteAllText(@"class C {}");
var srcDirectory = Path.GetDirectoryName(srcFile.Path);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, srcDirectory, new[] { "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path });
var exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
var output = outWriter.ToString();
Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal);
Assert.Contains("WarningDiagnosticAnalyzer (Warning01)", output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(srcFile.Path);
}
[Fact]
[WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")]
public void SkipAnalyzersParse()
{
var parsedArgs = DefaultParse(new[] { "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.SkipAnalyzers);
parsedArgs = DefaultParse(new[] { "/skipanalyzers+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.SkipAnalyzers);
parsedArgs = DefaultParse(new[] { "/skipanalyzers", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.SkipAnalyzers);
parsedArgs = DefaultParse(new[] { "/SKIPANALYZERS+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.SkipAnalyzers);
parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.SkipAnalyzers);
parsedArgs = DefaultParse(new[] { "/skipanalyzers-", "/skipanalyzers+", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.True(parsedArgs.SkipAnalyzers);
parsedArgs = DefaultParse(new[] { "/skipanalyzers", "/skipanalyzers-", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.False(parsedArgs.SkipAnalyzers);
}
[Theory, CombinatorialData]
[WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")]
public void SkipAnalyzersSemantics(bool skipAnalyzers)
{
var srcFile = Temp.CreateFile().WriteAllText(@"class C {}");
var srcDirectory = Path.GetDirectoryName(srcFile.Path);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var skipAnalyzersFlag = "/skipanalyzers" + (skipAnalyzers ? "+" : "-");
var csc = CreateCSharpCompiler(null, srcDirectory, new[] { skipAnalyzersFlag, "/reportanalyzer", "/t:library", "/a:" + Assembly.GetExecutingAssembly().Location, srcFile.Path });
var exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
var output = outWriter.ToString();
if (skipAnalyzers)
{
Assert.DoesNotContain(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal);
Assert.DoesNotContain(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal);
}
else
{
Assert.Contains(CodeAnalysisResources.AnalyzerExecutionTimeColumnHeader, output, StringComparison.Ordinal);
Assert.Contains(new WarningDiagnosticAnalyzer().ToString(), output, StringComparison.Ordinal);
}
CleanupAllGeneratedFiles(srcFile.Path);
}
[Fact]
[WorkItem(24835, "https://github.com/dotnet/roslyn/issues/24835")]
public void TestCompilationSuccessIfOnlySuppressedDiagnostics()
{
var srcFile = Temp.CreateFile().WriteAllText(@"
#pragma warning disable Warning01
class C { }
");
var errorLog = Temp.CreateFile();
var csc = CreateCSharpCompiler(
null,
workingDirectory: Path.GetDirectoryName(srcFile.Path),
args: new[] { "/errorlog:" + errorLog.Path, "/warnaserror+", "/nologo", "/t:library", srcFile.Path },
analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new WarningDiagnosticAnalyzer()));
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = csc.Run(outWriter);
// Previously, the compiler would return error code 1 without printing any diagnostics
Assert.Empty(outWriter.ToString());
Assert.Equal(0, exitCode);
CleanupAllGeneratedFiles(srcFile.Path);
CleanupAllGeneratedFiles(errorLog.Path);
}
[Fact]
[WorkItem(1759, "https://github.com/dotnet/roslyn/issues/1759")]
public void AnalyzerDiagnosticThrowsInGetMessage()
{
var srcFile = Temp.CreateFile().WriteAllText(@"class C {}");
var srcDirectory = Path.GetDirectoryName(srcFile.Path);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path },
analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage()));
var exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
var output = outWriter.ToString();
// Verify that the diagnostic reported by AnalyzerThatThrowsInGetMessage is reported, though it doesn't have the message.
Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal);
// Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported.
Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal);
Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(srcFile.Path);
}
[Fact]
[WorkItem(3707, "https://github.com/dotnet/roslyn/issues/3707")]
public void AnalyzerExceptionDiagnosticCanBeConfigured()
{
var srcFile = Temp.CreateFile().WriteAllText(@"class C {}");
var srcDirectory = Path.GetDirectoryName(srcFile.Path);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", $"/warnaserror:{AnalyzerExecutor.AnalyzerExceptionDiagnosticId}", srcFile.Path },
analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerThatThrowsInGetMessage()));
var exitCode = csc.Run(outWriter);
Assert.NotEqual(0, exitCode);
var output = outWriter.ToString();
// Verify that the analyzer exception diagnostic for the exception throw in AnalyzerThatThrowsInGetMessage is also reported.
Assert.Contains(AnalyzerExecutor.AnalyzerExceptionDiagnosticId, output, StringComparison.Ordinal);
Assert.Contains(nameof(NotImplementedException), output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(srcFile.Path);
}
[Fact]
[WorkItem(4589, "https://github.com/dotnet/roslyn/issues/4589")]
public void AnalyzerReportsMisformattedDiagnostic()
{
var srcFile = Temp.CreateFile().WriteAllText(@"class C {}");
var srcDirectory = Path.GetDirectoryName(srcFile.Path);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/t:library", srcFile.Path },
analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new AnalyzerReportingMisformattedDiagnostic()));
var exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
var output = outWriter.ToString();
// Verify that the diagnostic reported by AnalyzerReportingMisformattedDiagnostic is reported with the message format string, instead of the formatted message.
Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.Id, output, StringComparison.Ordinal);
Assert.Contains(AnalyzerThatThrowsInGetMessage.Rule.MessageFormat.ToString(CultureInfo.InvariantCulture), output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(srcFile.Path);
}
[Fact]
public void ErrorPathsFromLineDirectives()
{
string sampleProgram = @"
#line 10 "".."" //relative path
using System*
";
var syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs");
var comp = CreateCSharpCompiler(null, WorkingDirectory, new string[] { });
var text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First());
//Pull off the last segment of the current directory.
var expectedPath = Path.GetDirectoryName(WorkingDirectory);
//the end of the diagnostic's "file" portion should be signaled with the '(' of the line/col info.
Assert.Equal('(', text[expectedPath.Length]);
sampleProgram = @"
#line 10 "".>"" //invalid path character
using System*
";
syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs");
text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First());
Assert.True(text.StartsWith(".>", StringComparison.Ordinal));
sampleProgram = @"
#line 10 ""http://goo.bar/baz.aspx"" //URI
using System*
";
syntaxTree = SyntaxFactory.ParseSyntaxTree(sampleProgram, path: "filename.cs");
text = comp.DiagnosticFormatter.Format(syntaxTree.GetDiagnostics().First());
Assert.True(text.StartsWith("http://goo.bar/baz.aspx", StringComparison.Ordinal));
}
[WorkItem(1119609, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119609")]
[Fact]
public void PreferredUILang()
{
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang" }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal);
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:" }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Contains("CS2006", outWriter.ToString(), StringComparison.Ordinal);
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:zz" }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal);
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-zz" }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Contains("CS2038", outWriter.ToString(), StringComparison.Ordinal);
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:en-US" }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal);
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de" }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal);
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/preferreduilang:de-AT" }).Run(outWriter);
Assert.Equal(1, exitCode);
Assert.DoesNotContain("CS2038", outWriter.ToString(), StringComparison.Ordinal);
}
[WorkItem(531263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531263")]
[Fact]
public void EmptyFileName()
{
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = CreateCSharpCompiler(null, WorkingDirectory, new[] { "" }).Run(outWriter);
Assert.NotEqual(0, exitCode);
// error CS2021: File name '' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long
Assert.Contains("CS2021", outWriter.ToString(), StringComparison.Ordinal);
}
[WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")]
[Fact]
public void NoInfoDiagnostics()
{
string filePath = Temp.CreateFile().WriteAllText(@"
using System.Diagnostics; // Unused.
").Path;
var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/nologo", "/target:library", filePath });
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
Assert.Equal(0, exitCode);
Assert.Equal("", outWriter.ToString().Trim());
CleanupAllGeneratedFiles(filePath);
}
[Fact]
public void RuntimeMetadataVersion()
{
var parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code);
parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code);
parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion: " }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.ERR_SwitchNeedsString, parsedArgs.Errors.First().Code);
parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:v4.0.30319" }, WorkingDirectory);
Assert.Equal(0, parsedArgs.Errors.Length);
Assert.Equal("v4.0.30319", parsedArgs.EmitOptions.RuntimeMetadataVersion);
parsedArgs = DefaultParse(new[] { "a.cs", "/runtimemetadataversion:-_+@%#*^" }, WorkingDirectory);
Assert.Equal(0, parsedArgs.Errors.Length);
Assert.Equal("-_+@%#*^", parsedArgs.EmitOptions.RuntimeMetadataVersion);
var comp = CreateEmptyCompilation(string.Empty);
Assert.Equal("v4.0.30319", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "v4.0.30319"))).Module.MetadataVersion);
comp = CreateEmptyCompilation(string.Empty);
Assert.Equal("_+@%#*^", ModuleMetadata.CreateFromImage(comp.EmitToArray(new EmitOptions(runtimeMetadataVersion: "_+@%#*^"))).Module.MetadataVersion);
}
[WorkItem(715339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715339")]
[ConditionalFact(typeof(WindowsOnly))]
public void WRN_InvalidSearchPathDir()
{
var baseDir = Temp.CreateDirectory();
var sourceFile = baseDir.CreateFile("Source.cs");
var invalidPath = "::";
var nonExistentPath = "DoesNotExist";
// lib switch
DefaultParse(new[] { "/lib:" + invalidPath, sourceFile.Path }, WorkingDirectory).Errors.Verify(
// warning CS1668: Invalid search path '::' specified in '/LIB option' -- 'path is too long or invalid'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "/LIB option", "path is too long or invalid"));
DefaultParse(new[] { "/lib:" + nonExistentPath, sourceFile.Path }, WorkingDirectory).Errors.Verify(
// warning CS1668: Invalid search path 'DoesNotExist' specified in '/LIB option' -- 'directory does not exist'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "/LIB option", "directory does not exist"));
// LIB environment variable
DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: invalidPath).Errors.Verify(
// warning CS1668: Invalid search path '::' specified in 'LIB environment variable' -- 'path is too long or invalid'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("::", "LIB environment variable", "path is too long or invalid"));
DefaultParse(new[] { sourceFile.Path }, WorkingDirectory, additionalReferenceDirectories: nonExistentPath).Errors.Verify(
// warning CS1668: Invalid search path 'DoesNotExist' specified in 'LIB environment variable' -- 'directory does not exist'
Diagnostic(ErrorCode.WRN_InvalidSearchPathDir).WithArguments("DoesNotExist", "LIB environment variable", "directory does not exist"));
CleanupAllGeneratedFiles(sourceFile.Path);
}
[WorkItem(650083, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/650083")]
[InlineData("a.cs /t:library /appconfig:.\\aux.config")]
[InlineData("a.cs /out:com1.dll")]
[InlineData("a.cs /doc:..\\lpt2.xml")]
[InlineData("a.cs /pdb:..\\prn.pdb")]
[Theory]
public void ReservedDeviceNameAsFileName(string commandLine)
{
var parsedArgs = DefaultParse(commandLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries), WorkingDirectory);
if (ExecutionConditionUtil.OperatingSystemRestrictsFileNames)
{
Assert.Equal(1, parsedArgs.Errors.Length);
Assert.Equal((int)ErrorCode.FTL_InvalidInputFileName, parsedArgs.Errors.First().Code);
}
else
{
Assert.Equal(0, parsedArgs.Errors.Length);
}
}
[Fact]
public void ReservedDeviceNameAsFileName2()
{
string filePath = Temp.CreateFile().WriteAllText(@"class C {}").Path;
// make sure reserved device names don't
var cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/r:com2.dll", "/target:library", "/preferreduilang:en", filePath });
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Contains("error CS0006: Metadata file 'com2.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal);
cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/link:..\\lpt8.dll", "/target:library", "/preferreduilang:en", filePath });
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = cmd.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Contains("error CS0006: Metadata file '..\\lpt8.dll' could not be found", outWriter.ToString(), StringComparison.Ordinal);
cmd = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/lib:aux", "/preferreduilang:en", filePath });
outWriter = new StringWriter(CultureInfo.InvariantCulture);
exitCode = cmd.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Contains("warning CS1668: Invalid search path 'aux' specified in '/LIB option' -- 'directory does not exist'", outWriter.ToString(), StringComparison.Ordinal);
CleanupAllGeneratedFiles(filePath);
}
[Fact]
public void ParseFeatures()
{
var args = DefaultParse(new[] { "/features:Test", "a.vb" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal("Test", args.ParseOptions.Features.Single().Key);
args = DefaultParse(new[] { "/features:Test", "a.vb", "/Features:Experiment" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(2, args.ParseOptions.Features.Count);
Assert.True(args.ParseOptions.Features.ContainsKey("Test"));
Assert.True(args.ParseOptions.Features.ContainsKey("Experiment"));
args = DefaultParse(new[] { "/features:Test=false,Key=value", "a.vb" }, WorkingDirectory);
args.Errors.Verify();
Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "false" }, { "Key", "value" } }));
args = DefaultParse(new[] { "/features:Test,", "a.vb" }, WorkingDirectory);
args.Errors.Verify();
Assert.True(args.ParseOptions.Features.SetEquals(new Dictionary<string, string> { { "Test", "true" } }));
}
[ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
public void ParseAdditionalFile()
{
var args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles.Single().Path);
args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:app.manifest" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(2, args.AdditionalFiles.Length);
Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path);
Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path);
args = DefaultParse(new[] { "/additionalfile:web.config", "a.cs", "/additionalfile:web.config" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(2, args.AdditionalFiles.Length);
Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path);
Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[1].Path);
args = DefaultParse(new[] { "/additionalfile:..\\web.config", "a.cs" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(Path.Combine(WorkingDirectory, "..\\web.config"), args.AdditionalFiles.Single().Path);
var baseDir = Temp.CreateDirectory();
baseDir.CreateFile("web1.config");
baseDir.CreateFile("web2.config");
baseDir.CreateFile("web3.config");
args = DefaultParse(new[] { "/additionalfile:web*.config", "a.cs" }, baseDir.Path);
args.Errors.Verify();
Assert.Equal(3, args.AdditionalFiles.Length);
Assert.Equal(Path.Combine(baseDir.Path, "web1.config"), args.AdditionalFiles[0].Path);
Assert.Equal(Path.Combine(baseDir.Path, "web2.config"), args.AdditionalFiles[1].Path);
Assert.Equal(Path.Combine(baseDir.Path, "web3.config"), args.AdditionalFiles[2].Path);
args = DefaultParse(new[] { "/additionalfile:web.config;app.manifest", "a.cs" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(2, args.AdditionalFiles.Length);
Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path);
Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path);
args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(2, args.AdditionalFiles.Length);
Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path);
Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path);
args = DefaultParse(new[] { "/additionalfile:web.config,app.manifest", "a.cs" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(2, args.AdditionalFiles.Length);
Assert.Equal(Path.Combine(WorkingDirectory, "web.config"), args.AdditionalFiles[0].Path);
Assert.Equal(Path.Combine(WorkingDirectory, "app.manifest"), args.AdditionalFiles[1].Path);
args = DefaultParse(new[] { @"/additionalfile:""web.config,app.manifest""", "a.cs" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(1, args.AdditionalFiles.Length);
Assert.Equal(Path.Combine(WorkingDirectory, "web.config,app.manifest"), args.AdditionalFiles[0].Path);
args = DefaultParse(new[] { "/additionalfile:web.config:app.manifest", "a.cs" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(1, args.AdditionalFiles.Length);
Assert.Equal(Path.Combine(WorkingDirectory, "web.config:app.manifest"), args.AdditionalFiles[0].Path);
args = DefaultParse(new[] { "/additionalfile", "a.cs" }, WorkingDirectory);
args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile"));
Assert.Equal(0, args.AdditionalFiles.Length);
args = DefaultParse(new[] { "/additionalfile:", "a.cs" }, WorkingDirectory);
args.Errors.Verify(Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "additionalfile"));
Assert.Equal(0, args.AdditionalFiles.Length);
}
[Fact]
public void ParseEditorConfig()
{
var args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths.Single());
args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:subdir\\.editorconfig" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(2, args.AnalyzerConfigPaths.Length);
Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]);
Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]);
args = DefaultParse(new[] { "/analyzerconfig:.editorconfig", "a.cs", "/analyzerconfig:.editorconfig" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(2, args.AnalyzerConfigPaths.Length);
Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]);
Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[1]);
args = DefaultParse(new[] { "/analyzerconfig:..\\.editorconfig", "a.cs" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(Path.Combine(WorkingDirectory, "..\\.editorconfig"), args.AnalyzerConfigPaths.Single());
args = DefaultParse(new[] { "/analyzerconfig:.editorconfig;subdir\\.editorconfig", "a.cs" }, WorkingDirectory);
args.Errors.Verify();
Assert.Equal(2, args.AnalyzerConfigPaths.Length);
Assert.Equal(Path.Combine(WorkingDirectory, ".editorconfig"), args.AnalyzerConfigPaths[0]);
Assert.Equal(Path.Combine(WorkingDirectory, "subdir\\.editorconfig"), args.AnalyzerConfigPaths[1]);
args = DefaultParse(new[] { "/analyzerconfig", "a.cs" }, WorkingDirectory);
args.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1));
Assert.Equal(0, args.AnalyzerConfigPaths.Length);
args = DefaultParse(new[] { "/analyzerconfig:", "a.cs" }, WorkingDirectory);
args.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<file list>' for 'analyzerconfig' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<file list>", "analyzerconfig").WithLocation(1, 1));
Assert.Equal(0, args.AnalyzerConfigPaths.Length);
}
[Fact]
public void NullablePublicOnly()
{
string source =
@"namespace System.Runtime.CompilerServices
{
public sealed class NullableAttribute : Attribute { } // missing constructor
}
public class Program
{
private object? F = null;
}";
string errorMessage = "error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.NullableAttribute..ctor'";
string filePath = Temp.CreateFile().WriteAllText(source).Path;
int exitCode;
string output;
// No /feature
(exitCode, output) = compileAndRun(featureOpt: null);
Assert.Equal(1, exitCode);
Assert.Contains(errorMessage, output, StringComparison.Ordinal);
// /features:nullablePublicOnly
(exitCode, output) = compileAndRun("/features:nullablePublicOnly");
Assert.Equal(0, exitCode);
Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal);
// /features:nullablePublicOnly=true
(exitCode, output) = compileAndRun("/features:nullablePublicOnly=true");
Assert.Equal(0, exitCode);
Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal);
// /features:nullablePublicOnly=false (the value is ignored)
(exitCode, output) = compileAndRun("/features:nullablePublicOnly=false");
Assert.Equal(0, exitCode);
Assert.DoesNotContain(errorMessage, output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(filePath);
(int, string) compileAndRun(string featureOpt)
{
var args = new[] { "/target:library", "/preferreduilang:en", "/langversion:8", "/nullable+", filePath };
if (featureOpt != null) args = args.Concat(featureOpt).ToArray();
var compiler = CreateCSharpCompiler(null, WorkingDirectory, args);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = compiler.Run(outWriter);
return (exitCode, outWriter.ToString());
};
}
// See also NullableContextTests.NullableAnalysisFlags_01().
[Fact]
public void NullableAnalysisFlags()
{
string source =
@"class Program
{
#nullable enable
static object F1() => null;
#nullable disable
static object F2() => null;
}";
string filePath = Temp.CreateFile().WriteAllText(source).Path;
string fileName = Path.GetFileName(filePath);
string[] expectedWarningsAll = new[] { fileName + "(4,27): warning CS8603: Possible null reference return." };
string[] expectedWarningsNone = Array.Empty<string>();
AssertEx.Equal(expectedWarningsAll, compileAndRun(featureOpt: null));
AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis"));
AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=always"));
AssertEx.Equal(expectedWarningsNone, compileAndRun("/features:run-nullable-analysis=never"));
AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=ALWAYS")); // unrecognized value (incorrect case) ignored
AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=NEVER")); // unrecognized value (incorrect case) ignored
AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=true")); // unrecognized value ignored
AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=false")); // unrecognized value ignored
AssertEx.Equal(expectedWarningsAll, compileAndRun("/features:run-nullable-analysis=unknown")); // unrecognized value ignored
CleanupAllGeneratedFiles(filePath);
string[] compileAndRun(string featureOpt)
{
var args = new[] { "/target:library", "/preferreduilang:en", "/nologo", filePath };
if (featureOpt != null) args = args.Concat(featureOpt).ToArray();
var compiler = CreateCSharpCompiler(null, WorkingDirectory, args);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
int exitCode = compiler.Run(outWriter);
return outWriter.ToString().Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
};
}
[Fact]
public void Compiler_Uses_DriverCache()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
int sourceCallbackCount = 0;
var generator = new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) =>
{
sourceCallbackCount++;
});
});
// with no cache, we'll see the callback execute multiple times
RunWithNoCache();
Assert.Equal(1, sourceCallbackCount);
RunWithNoCache();
Assert.Equal(2, sourceCallbackCount);
RunWithNoCache();
Assert.Equal(3, sourceCallbackCount);
// now re-run with a cache
GeneratorDriverCache cache = new GeneratorDriverCache();
sourceCallbackCount = 0;
RunWithCache();
Assert.Equal(1, sourceCallbackCount);
RunWithCache();
Assert.Equal(1, sourceCallbackCount);
RunWithCache();
Assert.Equal(1, sourceCallbackCount);
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
void RunWithNoCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, analyzers: null);
void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:enable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null);
}
[Fact]
public void Compiler_Doesnt_Use_Cache_From_Other_Compilation()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
int sourceCallbackCount = 0;
var generator = new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) =>
{
sourceCallbackCount++;
});
});
// now re-run with a cache
GeneratorDriverCache cache = new GeneratorDriverCache();
sourceCallbackCount = 0;
RunWithCache("1.dll");
Assert.Equal(1, sourceCallbackCount);
RunWithCache("1.dll");
Assert.Equal(1, sourceCallbackCount);
// now emulate a new compilation, and check we were invoked, but only once
RunWithCache("2.dll");
Assert.Equal(2, sourceCallbackCount);
RunWithCache("2.dll");
Assert.Equal(2, sourceCallbackCount);
// now re-run our first compilation
RunWithCache("1.dll");
Assert.Equal(2, sourceCallbackCount);
// a new one
RunWithCache("3.dll");
Assert.Equal(3, sourceCallbackCount);
// and another old one
RunWithCache("2.dll");
Assert.Equal(3, sourceCallbackCount);
RunWithCache("1.dll");
Assert.Equal(3, sourceCallbackCount);
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
void RunWithCache(string outputPath) => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:" + outputPath, "/features:enable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null);
}
[Fact]
public void Compiler_Can_Enable_DriverCache()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
int sourceCallbackCount = 0;
var generator = new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) =>
{
sourceCallbackCount++;
});
});
// run with the cache
GeneratorDriverCache cache = new GeneratorDriverCache();
sourceCallbackCount = 0;
RunWithCache();
Assert.Equal(1, sourceCallbackCount);
RunWithCache();
Assert.Equal(1, sourceCallbackCount);
RunWithCache();
Assert.Equal(1, sourceCallbackCount);
// now re-run with the cache disabled
sourceCallbackCount = 0;
RunWithCacheDisabled();
Assert.Equal(1, sourceCallbackCount);
RunWithCacheDisabled();
Assert.Equal(2, sourceCallbackCount);
RunWithCacheDisabled();
Assert.Equal(3, sourceCallbackCount);
// now clear the cache as well as disabling, and verify we don't put any entries into it either
cache = new GeneratorDriverCache();
sourceCallbackCount = 0;
RunWithCacheDisabled();
Assert.Equal(1, sourceCallbackCount);
Assert.Equal(0, cache.CacheSize);
RunWithCacheDisabled();
Assert.Equal(2, sourceCallbackCount);
Assert.Equal(0, cache.CacheSize);
RunWithCacheDisabled();
Assert.Equal(3, sourceCallbackCount);
Assert.Equal(0, cache.CacheSize);
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:enable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null);
void RunWithCacheDisabled() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null);
}
[Fact]
public void Adding_Or_Removing_A_Generator_Invalidates_Cache()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
int sourceCallbackCount = 0;
int sourceCallbackCount2 = 0;
var generator = new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) =>
{
sourceCallbackCount++;
});
});
var generator2 = new PipelineCallbackGenerator2((ctx) =>
{
ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) =>
{
sourceCallbackCount2++;
});
});
// run with the cache
GeneratorDriverCache cache = new GeneratorDriverCache();
RunWithOneGenerator();
Assert.Equal(1, sourceCallbackCount);
Assert.Equal(0, sourceCallbackCount2);
RunWithOneGenerator();
Assert.Equal(1, sourceCallbackCount);
Assert.Equal(0, sourceCallbackCount2);
RunWithTwoGenerators();
Assert.Equal(2, sourceCallbackCount);
Assert.Equal(1, sourceCallbackCount2);
RunWithTwoGenerators();
Assert.Equal(2, sourceCallbackCount);
Assert.Equal(1, sourceCallbackCount2);
// this seems counterintuitive, but when the only thing to change is the generator, we end up back at the state of the project when
// we just ran a single generator. Thus we already have an entry in the cache we can use (the one created by the original call to
// RunWithOneGenerator above) meaning we can use the previously cached results and not run.
RunWithOneGenerator();
Assert.Equal(2, sourceCallbackCount);
Assert.Equal(1, sourceCallbackCount2);
void RunWithOneGenerator() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:enable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null);
void RunWithTwoGenerators() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:enable-generator-cache" }, generators: new[] { generator.AsSourceGenerator(), generator2.AsSourceGenerator() }, driverCache: cache, analyzers: null);
}
[Fact]
public void Compiler_Updates_Cached_Driver_AdditionalTexts()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText("class C { }");
var additionalFile = dir.CreateFile("additionalFile.txt").WriteAllText("some text");
int sourceCallbackCount = 0;
int additionalFileCallbackCount = 0;
var generator = new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) =>
{
sourceCallbackCount++;
});
ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, po) =>
{
additionalFileCallbackCount++;
});
});
GeneratorDriverCache cache = new GeneratorDriverCache();
RunWithCache();
Assert.Equal(1, sourceCallbackCount);
Assert.Equal(1, additionalFileCallbackCount);
RunWithCache();
Assert.Equal(1, sourceCallbackCount);
Assert.Equal(1, additionalFileCallbackCount);
additionalFile.WriteAllText("some new content");
RunWithCache();
Assert.Equal(1, sourceCallbackCount);
Assert.Equal(2, additionalFileCallbackCount); // additional file was updated
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:enable-generator-cache", "/additionalFile:" + additionalFile.Path }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null);
}
[Fact]
public void Compiler_DoesNotCache_Driver_ConfigProvider()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText("class C { }");
var editorconfig = dir.CreateFile(".editorconfig").WriteAllText(@"
[temp.cs]
a = localA
");
var globalconfig = dir.CreateFile(".globalconfig").WriteAllText(@"
is_global = true
a = globalA");
int sourceCallbackCount = 0;
int configOptionsCallbackCount = 0;
int filteredGlobalCallbackCount = 0;
int filteredLocalCallbackCount = 0;
string globalA = "";
string localA = "";
var generator = new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.ParseOptionsProvider, (spc, po) =>
{
sourceCallbackCount++;
});
ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider, (spc, po) =>
{
configOptionsCallbackCount++;
po.GlobalOptions.TryGetValue("a", out globalA);
});
ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider.Select((p, _) => { p.GlobalOptions.TryGetValue("a", out var value); return value; }), (spc, value) =>
{
filteredGlobalCallbackCount++;
globalA = value;
});
var syntaxTreeInput = ctx.CompilationProvider.Select((c, _) => c.SyntaxTrees.First());
ctx.RegisterSourceOutput(ctx.AnalyzerConfigOptionsProvider.Combine(syntaxTreeInput).Select((p, _) => { p.Left.GetOptions(p.Right).TryGetValue("a", out var value); return value; }), (spc, value) =>
{
filteredLocalCallbackCount++;
localA = value;
});
});
GeneratorDriverCache cache = new GeneratorDriverCache();
RunWithCache();
Assert.Equal(1, sourceCallbackCount);
Assert.Equal(1, configOptionsCallbackCount);
Assert.Equal(1, filteredGlobalCallbackCount);
Assert.Equal(1, filteredLocalCallbackCount);
Assert.Equal("globalA", globalA);
Assert.Equal("localA", localA);
RunWithCache();
Assert.Equal(1, sourceCallbackCount);
Assert.Equal(2, configOptionsCallbackCount); // we can't compare the provider directly, so we consider it modified
Assert.Equal(1, filteredGlobalCallbackCount); // however, the values in it will cache out correctly.
Assert.Equal(1, filteredLocalCallbackCount);
editorconfig.WriteAllText(@"
[temp.cs]
a = diffLocalA
");
RunWithCache();
Assert.Equal(1, sourceCallbackCount);
Assert.Equal(3, configOptionsCallbackCount);
Assert.Equal(1, filteredGlobalCallbackCount); // the provider changed, but only the local value changed
Assert.Equal(2, filteredLocalCallbackCount);
Assert.Equal("globalA", globalA);
Assert.Equal("diffLocalA", localA);
globalconfig.WriteAllText(@"
is_global = true
a = diffGlobalA
");
RunWithCache();
Assert.Equal(1, sourceCallbackCount);
Assert.Equal(4, configOptionsCallbackCount);
Assert.Equal(2, filteredGlobalCallbackCount); // only the global value was changed
Assert.Equal(2, filteredLocalCallbackCount);
Assert.Equal("diffGlobalA", globalA);
Assert.Equal("diffLocalA", localA);
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:enable-generator-cache", "/analyzerConfig:" + editorconfig.Path, "/analyzerConfig:" + globalconfig.Path }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null);
}
[Fact]
public void Compiler_DoesNotCache_Compilation()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
int sourceCallbackCount = 0;
var generator = new PipelineCallbackGenerator((ctx) =>
{
ctx.RegisterSourceOutput(ctx.CompilationProvider, (spc, po) =>
{
sourceCallbackCount++;
});
});
// now re-run with a cache
GeneratorDriverCache cache = new GeneratorDriverCache();
RunWithCache();
Assert.Equal(1, sourceCallbackCount);
RunWithCache();
Assert.Equal(2, sourceCallbackCount);
RunWithCache();
Assert.Equal(3, sourceCallbackCount);
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
void RunWithCache() => VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/features:enable-generator-cache" }, generators: new[] { generator.AsSourceGenerator() }, driverCache: cache, analyzers: null);
}
private static int OccurrenceCount(string source, string word)
{
var n = 0;
var index = source.IndexOf(word, StringComparison.Ordinal);
while (index >= 0)
{
++n;
index = source.IndexOf(word, index + word.Length, StringComparison.Ordinal);
}
return n;
}
private string VerifyOutput(TempDirectory sourceDir, TempFile sourceFile,
bool includeCurrentAssemblyAsAnalyzerReference = true,
string[] additionalFlags = null,
int expectedInfoCount = 0,
int expectedWarningCount = 0,
int expectedErrorCount = 0,
int? expectedExitCode = null,
bool errorlog = false,
bool skipAnalyzers = false,
IEnumerable<ISourceGenerator> generators = null,
GeneratorDriverCache driverCache = null,
params DiagnosticAnalyzer[] analyzers)
{
var args = new[] {
"/nologo", "/preferreduilang:en", "/t:library",
sourceFile.Path
};
if (includeCurrentAssemblyAsAnalyzerReference)
{
args = args.Append("/a:" + Assembly.GetExecutingAssembly().Location);
}
if (errorlog)
{
args = args.Append("/errorlog:errorlog");
}
if (skipAnalyzers)
{
args = args.Append("/skipAnalyzers");
}
if (additionalFlags != null)
{
args = args.Append(additionalFlags);
}
var csc = CreateCSharpCompiler(null, sourceDir.Path, args, analyzers: analyzers.ToImmutableArrayOrEmpty(), generators: generators.ToImmutableArrayOrEmpty(), driverCache: driverCache);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = csc.Run(outWriter);
var output = outWriter.ToString();
expectedExitCode ??= expectedErrorCount > 0 ? 1 : 0;
Assert.True(
expectedExitCode == exitCode,
string.Format("Expected exit code to be '{0}' was '{1}'.{2} Output:{3}{4}",
expectedExitCode, exitCode, Environment.NewLine, Environment.NewLine, output));
Assert.DoesNotContain("hidden", output, StringComparison.Ordinal);
if (expectedInfoCount == 0)
{
Assert.DoesNotContain("info", output, StringComparison.Ordinal);
}
else
{
// Info diagnostics are only logged with /errorlog.
Assert.True(errorlog);
Assert.Equal(expectedInfoCount, OccurrenceCount(output, "info"));
}
if (expectedWarningCount == 0)
{
Assert.DoesNotContain("warning", output, StringComparison.Ordinal);
}
else
{
Assert.Equal(expectedWarningCount, OccurrenceCount(output, "warning"));
}
if (expectedErrorCount == 0)
{
Assert.DoesNotContain("error", output, StringComparison.Ordinal);
}
else
{
Assert.Equal(expectedErrorCount, OccurrenceCount(output, "error"));
}
return output;
}
[WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")]
[Fact]
public void NoWarnAndWarnAsError_AnalyzerDriverWarnings()
{
// This assembly has an abstract MockAbstractDiagnosticAnalyzer type which should cause
// compiler warning CS8032 to be produced when compilations created in this test try to load it.
string source = @"using System;";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
var output = VerifyOutput(dir, file, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that compiler warning CS8032 can be suppressed via /warn:0.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" });
Assert.True(string.IsNullOrEmpty(output));
// TEST: Verify that compiler warning CS8032 can be individually suppressed via /nowarn:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:CS8032" });
Assert.True(string.IsNullOrEmpty(output));
// TEST: Verify that compiler warning CS8032 can be promoted to an error via /warnaserror.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1);
Assert.Contains("error CS8032", output, StringComparison.Ordinal);
// TEST: Verify that compiler warning CS8032 can be individually promoted to an error via /warnaserror:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:8032" }, expectedErrorCount: 1);
Assert.Contains("error CS8032", output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(file.Path);
}
[WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")]
[WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")]
[WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")]
[Fact]
public void NoWarnAndWarnAsError_HiddenDiagnostic()
{
// This assembly has a HiddenDiagnosticAnalyzer type which should produce custom hidden
// diagnostics for #region directives present in the compilations created in this test.
var source = @"using System;
#region Region
#endregion";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
var output = VerifyOutput(dir, file, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" });
Assert.True(string.IsNullOrEmpty(output));
// TEST: Verify that /nowarn: has no impact on custom hidden diagnostic Hidden01.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /warnaserror+ has no impact on custom hidden diagnostic Hidden01.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" });
Assert.True(string.IsNullOrEmpty(output));
// TEST: Verify that /warnaserror- has no impact on custom hidden diagnostic Hidden01.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /warnaserror: promotes custom hidden diagnostic Hidden01 to an error.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal);
// TEST: Verify that /warnaserror-: has no impact on custom hidden diagnostic Hidden01.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify /nowarn: overrides /warnaserror:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify /nowarn: overrides /warnaserror:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror:Hidden01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify /nowarn: overrides /warnaserror-:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/nowarn:Hidden01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify /nowarn: overrides /warnaserror-:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Hidden01" });
Assert.True(string.IsNullOrEmpty(output));
// TEST: Verify that /warn:0 has no impact on custom hidden diagnostic Hidden01.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Hidden01", "/warn:0" });
Assert.True(string.IsNullOrEmpty(output));
// TEST: Verify that last /warnaserror[+/-]: flag on command line wins.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-:Hidden01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last /warnaserror[+/-]: flag on command line wins.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Hidden01" }, expectedWarningCount: 1, expectedErrorCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror+" }, expectedErrorCount: 1);
Assert.Contains("error CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Hidden01", "/nowarn:8032" }, expectedErrorCount: 1);
Assert.Contains("a.cs(2,1): error Hidden01: Throwing a diagnostic for #region", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror+", "/nowarn:8032" });
Assert.True(string.IsNullOrEmpty(output));
// TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Hidden01", "/warnaserror-" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Hidden01", "/nowarn:8032" });
Assert.True(string.IsNullOrEmpty(output));
// TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Hidden01", "/warnaserror-" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Hidden01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(file.Path);
}
[WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")]
[WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")]
[WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")]
[WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")]
[CombinatorialData, Theory]
public void NoWarnAndWarnAsError_InfoDiagnostic(bool errorlog)
{
// NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details.
// This assembly has an InfoDiagnosticAnalyzer type which should produce custom info
// diagnostics for the #pragma warning restore directives present in the compilations created in this test.
var source = @"using System;
#pragma warning restore";
var name = "a.cs";
string output;
output = GetOutput(name, source, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
if (errorlog)
Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
// TEST: Verify that /warn:0 suppresses custom info diagnostic Info01.
output = GetOutput(name, source, additionalFlags: new[] { "/warn:0" }, errorlog: errorlog);
// TEST: Verify that custom info diagnostic Info01 can be individually suppressed via /nowarn:.
output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that custom info diagnostic Info01 can never be promoted to an error via /warnaserror+.
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog);
if (errorlog)
Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
// TEST: Verify that custom info diagnostic Info01 is still reported as an info when /warnaserror- is used.
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
if (errorlog)
Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
// TEST: Verify that custom info diagnostic Info01 can be individually promoted to an error via /warnaserror:.
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
// TEST: Verify that custom info diagnostic Info01 is still reported as an info when passed to /warnaserror-:.
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
if (errorlog)
Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
// TEST: Verify /nowarn overrides /warnaserror.
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify /nowarn overrides /warnaserror.
output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror:Info01" }, expectedWarningCount: 1, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify /nowarn overrides /warnaserror-.
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/nowarn:Info01" }, expectedWarningCount: 1, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify /nowarn overrides /warnaserror-.
output = GetOutput(name, source, additionalFlags: new[] { "/nowarn:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01.
output = GetOutput(name, source, additionalFlags: new[] { "/warn:0", "/warnaserror:Info01" }, errorlog: errorlog);
// TEST: Verify that /warn:0 has no impact on custom info diagnostic Info01.
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror:Info01", "/warn:0" });
// TEST: Verify that last /warnaserror[+/-]: flag on command line wins.
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
if (errorlog)
Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
// TEST: Verify that last /warnaserror[+/-]: flag on command line wins.
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Info01" }, expectedWarningCount: 1, expectedErrorCount: 1, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog);
if (errorlog)
Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror+", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog);
if (errorlog)
Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror+:Info01", "/nowarn:8032" }, expectedErrorCount: 1, errorlog: errorlog);
Assert.Contains("a.cs(2,1): error Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
if (errorlog)
Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror+", "/warnaserror-:Info01", "/nowarn:8032" }, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog);
if (errorlog)
Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-:Info01", "/warnaserror-" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
if (errorlog)
Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
output = GetOutput(name, source, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Info01" }, expectedWarningCount: 1, expectedInfoCount: errorlog ? 1 : 0, errorlog: errorlog);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
if (errorlog)
Assert.Contains("a.cs(2,1): info Info01: Throwing a diagnostic for #pragma restore", output, StringComparison.Ordinal);
}
private string GetOutput(
string name,
string source,
bool includeCurrentAssemblyAsAnalyzerReference = true,
string[] additionalFlags = null,
int expectedInfoCount = 0,
int expectedWarningCount = 0,
int expectedErrorCount = 0,
bool errorlog = false)
{
var dir = Temp.CreateDirectory();
var file = dir.CreateFile(name);
file.WriteAllText(source);
var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference, additionalFlags, expectedInfoCount, expectedWarningCount, expectedErrorCount, null, errorlog);
CleanupAllGeneratedFiles(file.Path);
return output;
}
[WorkItem(11368, "https://github.com/dotnet/roslyn/issues/11368")]
[WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")]
[WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")]
[WorkItem(998069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998069")]
[WorkItem(998724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/998724")]
[WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")]
[Fact]
public void NoWarnAndWarnAsError_WarningDiagnostic()
{
// This assembly has a WarningDiagnosticAnalyzer type which should produce custom warning
// diagnostics for source types present in the compilations created in this test.
string source = @"
class C
{
static void Main()
{
int i;
}
}
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
var output = VerifyOutput(dir, file, expectedWarningCount: 3);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
// TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be suppressed via /warn:0.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" });
Assert.True(string.IsNullOrEmpty(output));
// TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be individually suppressed via /nowarn:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /nowarn:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:cs0168,warning01,700000" }, expectedWarningCount: 3);
Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/nowarn:8032" }, expectedErrorCount: 2);
Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
// TEST: Verify that compiler warning CS0168 as well as custom warning diagnostic Warning01 can be promoted to errors via /warnaserror+.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:8032" }, expectedErrorCount: 2);
Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
// TEST: Verify that /warnaserror- keeps compiler warning CS0168 as well as custom warning diagnostic Warning01 as warnings.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedWarningCount: 3);
Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that custom warning diagnostic Warning01 can be individually promoted to an error via /warnaserror:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1);
Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that compiler warning CS0168 can be individually promoted to an error via /warnaserror+:.
// This doesn't work correctly currently - promoting compiler warning CS0168 to an error causes us to no longer report any custom warning diagnostics as errors (Bug 998069).
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:CS0168" }, expectedWarningCount: 2, expectedErrorCount: 1);
Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that diagnostic ids are processed in case-sensitive fashion inside /warnaserror.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:cs0168,warning01,58000" }, expectedWarningCount: 3);
Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that custom warning diagnostic Warning01 as well as compiler warning CS0168 can be promoted to errors via /warnaserror:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:CS0168,Warning01" }, expectedWarningCount: 1, expectedErrorCount: 2);
Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): error CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /warn:0 overrides /warnaserror+.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror+" });
// TEST: Verify that /warn:0 overrides /warnaserror.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warn:0" });
// TEST: Verify that /warn:0 overrides /warnaserror-.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warn:0" });
// TEST: Verify that /warn:0 overrides /warnaserror-.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror-" });
// TEST: Verify that /nowarn: overrides /warnaserror:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /nowarn: overrides /warnaserror:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror:Something,CS0168,Warning01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /nowarn: overrides /warnaserror-:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Something,CS0168,Warning01", "/nowarn:0168,Warning01,58000" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /nowarn: overrides /warnaserror-:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000", "/warnaserror-:Something,CS0168,Warning01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /nowarn: overrides /warnaserror+.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:0168,Warning01,58000,8032" });
// TEST: Verify that /nowarn: overrides /warnaserror+.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror+" });
// TEST: Verify that /nowarn: overrides /warnaserror-.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:0168,Warning01,58000,8032" });
// TEST: Verify that /nowarn: overrides /warnaserror-.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:0168,Warning01,58000,8032", "/warnaserror-" });
// TEST: Verify that /warn:0 overrides /warnaserror:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Something,CS0168,Warning01", "/warn:0" });
// TEST: Verify that /warn:0 overrides /warnaserror:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0", "/warnaserror:Something,CS0168,Warning01" });
// TEST: Verify that last /warnaserror[+/-] flag on command line wins.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+" }, expectedErrorCount: 1);
Assert.Contains("error CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last /warnaserror[+/-] flag on command line wins.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-" }, expectedWarningCount: 3);
Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last /warnaserror[+/-]: flag on command line wins.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1);
Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last /warnaserror[+/-]: flag on command line wins.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Warning01", "/warnaserror-:Warning01" }, expectedWarningCount: 3);
Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,CS0168,58000,8032", "/warnaserror+" }, expectedErrorCount: 1);
Assert.Contains("error CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror-:Warning01,CS0168,58000,8032" }, expectedWarningCount: 3);
Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3);
Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror+:Warning01" }, expectedWarningCount: 2, expectedErrorCount: 1);
Assert.Contains("a.cs(2,7): error Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Warning01,CS0168,58000", "/warnaserror+" }, expectedErrorCount: 1);
Assert.Contains("error CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror", "/warnaserror+:Warning01,CS0168,58000" }, expectedErrorCount: 1);
Assert.Contains("error CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-]: and /warnaserror[+/-].
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Warning01,58000,8032", "/warnaserror-" }, expectedWarningCount: 3);
Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that last one wins between /warnaserror[+/-] and /warnaserror[+/-]:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/warnaserror-:Warning01,58000,8032" }, expectedWarningCount: 3);
Assert.Contains("a.cs(2,7): warning Warning01: Throwing a diagnostic for types declared", output, StringComparison.Ordinal);
Assert.Contains("a.cs(6,13): warning CS0168: The variable 'i' is declared but never used", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(file.Path);
}
[WorkItem(899050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899050")]
[WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")]
[Fact]
public void NoWarnAndWarnAsError_ErrorDiagnostic()
{
// This assembly has an ErrorDiagnosticAnalyzer type which should produce custom error
// diagnostics for #pragma warning disable directives present in the compilations created in this test.
string source = @"using System;
#pragma warning disable";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
var output = VerifyOutput(dir, file, expectedErrorCount: 1, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal);
// TEST: Verify that custom error diagnostic Error01 can't be suppressed via /warn:0.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1);
Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal);
// TEST: Verify that custom error diagnostic Error01 can be suppressed via /nowarn:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /nowarn: overrides /warnaserror+.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+", "/nowarn:Error01" }, expectedErrorCount: 1);
Assert.Contains("error CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /nowarn: overrides /warnaserror.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror" }, expectedErrorCount: 1);
Assert.Contains("error CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /nowarn: overrides /warnaserror+:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror+:Error01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /nowarn: overrides /warnaserror:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01", "/nowarn:Error01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /nowarn: overrides /warnaserror-.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-", "/nowarn:Error01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /nowarn: overrides /warnaserror-.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /nowarn: overrides /warnaserror-.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01", "/nowarn:Error01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that /nowarn: overrides /warnaserror-.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/nowarn:Error01", "/warnaserror-:Error01" }, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
// TEST: Verify that nothing bad happens when using /warnaserror[+/-] when custom error diagnostic Error01 is present.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1);
Assert.Contains("error CS8032", output, StringComparison.Ordinal);
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1);
Assert.Contains("error CS8032", output, StringComparison.Ordinal);
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal);
// TEST: Verify that nothing bad happens if someone passes custom error diagnostic Error01 to /warnaserror[+/-]:.
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal);
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror+:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal);
output = VerifyOutput(dir, file, additionalFlags: new[] { "/warnaserror-:Error01" }, expectedErrorCount: 1, expectedWarningCount: 1);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
Assert.Contains("a.cs(2,1): error Error01: Throwing a diagnostic for #pragma disable", output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(file.Path);
}
[Fact]
[WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")]
public void ConsistentErrorMessageWhenProvidingNoKeyFile()
{
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim());
}
[Fact]
[WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")]
public void ConsistentErrorMessageWhenProvidingEmptyKeyFile()
{
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim());
}
[Fact]
[WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")]
public void ConsistentErrorMessageWhenProvidingNoKeyFile_PublicSign()
{
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim());
}
[Fact]
[WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")]
public void ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign()
{
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, WorkingDirectory, new[] { "/keyfile:\"\"", "/publicsign", "/target:library", "/nologo", "/preferreduilang:en", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Equal("error CS2005: Missing file specification for 'keyfile' option", outWriter.ToString().Trim());
}
[WorkItem(981677, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/981677")]
[Fact]
public void NoWarnAndWarnAsError_CompilerErrorDiagnostic()
{
string source = @"using System;
class C
{
static void Main()
{
int i = new Exception();
}
}";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.cs");
file.WriteAllText(source);
var output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, expectedErrorCount: 1);
Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
// TEST: Verify that compiler error CS0029 can't be suppressed via /warn:0.
output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warn:0" }, expectedErrorCount: 1);
Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
// TEST: Verify that compiler error CS0029 can't be suppressed via /nowarn:.
output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:29" }, expectedErrorCount: 1);
Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS0029" }, expectedErrorCount: 1);
Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
// TEST: Verify that nothing bad happens when using /warnaserror[+/-] when compiler error CS0029 is present.
output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror" }, expectedErrorCount: 1);
Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+" }, expectedErrorCount: 1);
Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-" }, expectedErrorCount: 1);
Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
// TEST: Verify that nothing bad happens if someone passes compiler error CS0029 to /warnaserror[+/-]:.
output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror:0029" }, expectedErrorCount: 1);
Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror+:CS0029" }, expectedErrorCount: 1);
Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:29" }, expectedErrorCount: 1);
Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
output = VerifyOutput(dir, file, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/warnaserror-:CS0029" }, expectedErrorCount: 1);
Assert.Contains("a.cs(6,17): error CS0029: Cannot implicitly convert type 'System.Exception' to 'int'", output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(file.Path);
}
[WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")]
[Fact]
public void WarnAsError_LastOneWins1()
{
var arguments = DefaultParse(new[] { "/warnaserror-:3001", "/warnaserror" }, null);
var options = arguments.CompilationOptions;
var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)]
public class C
{
public void M(ushort i)
{
}
public static void Main(string[] args) {}
}", options: options);
comp.VerifyDiagnostics(
// (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant
// public void M(ushort i)
Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i")
.WithArguments("ushort")
.WithLocation(4, 26)
.WithWarningAsError(true));
}
[WorkItem(1021115, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1021115")]
[Fact]
public void WarnAsError_LastOneWins2()
{
var arguments = DefaultParse(new[] { "/warnaserror", "/warnaserror-:3001" }, null);
var options = arguments.CompilationOptions;
var comp = CreateCompilation(@"[assembly: System.CLSCompliant(true)]
public class C
{
public void M(ushort i)
{
}
public static void Main(string[] args) {}
}", options: options);
comp.VerifyDiagnostics(
// (4,26): warning CS3001: Argument type 'ushort' is not CLS-compliant
// public void M(ushort i)
Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i")
.WithArguments("ushort")
.WithLocation(4, 26)
.WithWarningAsError(false));
}
[WorkItem(1091972, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091972")]
[WorkItem(444, "CodePlex")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void Bug1091972()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("a.cs");
src.WriteAllText(
@"
/// <summary>ABC...XYZ</summary>
class C {
static void Main()
{
var textStreamReader = new System.IO.StreamReader(typeof(C).Assembly.GetManifestResourceStream(""doc.xml""));
System.Console.WriteLine(textStreamReader.ReadToEnd());
}
} ");
var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, String.Format("/nologo /doc:doc.xml /out:out.exe /resource:doc.xml \"{0}\"", src.ToString()), startFolder: dir.ToString());
Assert.Equal("", output.Trim());
Assert.True(File.Exists(Path.Combine(dir.ToString(), "doc.xml")));
var expected =
@"<?xml version=""1.0""?>
<doc>
<assembly>
<name>out</name>
</assembly>
<members>
<member name=""T:C"">
<summary>ABC...XYZ</summary>
</member>
</members>
</doc>".Trim();
using (var reader = new StreamReader(Path.Combine(dir.ToString(), "doc.xml")))
{
var content = reader.ReadToEnd();
Assert.Equal(expected, content.Trim());
}
output = ProcessUtilities.RunAndGetOutput(Path.Combine(dir.ToString(), "out.exe"), startFolder: dir.ToString());
Assert.Equal(expected, output.Trim());
CleanupAllGeneratedFiles(src.Path);
}
[ConditionalFact(typeof(WindowsOnly))]
public void CommandLineMisc()
{
CSharpCommandLineArguments args = null;
string baseDirectory = @"c:\test";
Func<string, CSharpCommandLineArguments> parse = (x) => FullParse(x, baseDirectory);
args = parse(@"/out:""a.exe""");
Assert.Equal(@"a.exe", args.OutputFileName);
args = parse(@"/pdb:""a.pdb""");
Assert.Equal(Path.Combine(baseDirectory, @"a.pdb"), args.PdbPath);
// The \ here causes " to be treated as a quote, not as an escaping construct
args = parse(@"a\""b c""\d.cs");
Assert.Equal(
new[] { @"c:\test\a""b", @"c:\test\c\d.cs" },
args.SourceFiles.Select(x => x.Path));
args = parse(@"a\\""b c""\d.cs");
Assert.Equal(
new[] { @"c:\test\a\b c\d.cs" },
args.SourceFiles.Select(x => x.Path));
args = parse(@"/nostdlib /r:""a.dll"",""b.dll"" c.cs");
Assert.Equal(
new[] { @"a.dll", @"b.dll" },
args.MetadataReferences.Select(x => x.Reference));
args = parse(@"/nostdlib /r:""a-s.dll"",""b-s.dll"" c.cs");
Assert.Equal(
new[] { @"a-s.dll", @"b-s.dll" },
args.MetadataReferences.Select(x => x.Reference));
args = parse(@"/nostdlib /r:""a,;s.dll"",""b,;s.dll"" c.cs");
Assert.Equal(
new[] { @"a,;s.dll", @"b,;s.dll" },
args.MetadataReferences.Select(x => x.Reference));
}
[Fact]
public void CommandLine_ScriptRunner1()
{
var args = ScriptParse(new[] { "--", "script.csx", "b", "c" }, baseDirectory: WorkingDirectory);
AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path));
AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments);
args = ScriptParse(new[] { "--", "@script.csx", "b", "c" }, baseDirectory: WorkingDirectory);
AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "@script.csx") }, args.SourceFiles.Select(f => f.Path));
AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments);
args = ScriptParse(new[] { "--", "-script.csx", "b", "c" }, baseDirectory: WorkingDirectory);
AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "-script.csx") }, args.SourceFiles.Select(f => f.Path));
AssertEx.Equal(new[] { "b", "c" }, args.ScriptArguments);
args = ScriptParse(new[] { "script.csx", "--", "b", "c" }, baseDirectory: WorkingDirectory);
AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path));
AssertEx.Equal(new[] { "--", "b", "c" }, args.ScriptArguments);
args = ScriptParse(new[] { "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory);
AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path));
AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments);
args = ScriptParse(new[] { "script.csx", "a", "--", "b", "c" }, baseDirectory: WorkingDirectory);
AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path));
AssertEx.Equal(new[] { "a", "--", "b", "c" }, args.ScriptArguments);
args = ScriptParse(new[] { "-i", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory);
Assert.True(args.InteractiveMode);
AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path));
AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments);
args = ScriptParse(new[] { "-i", "--", "script.csx", "a", "b", "c" }, baseDirectory: WorkingDirectory);
Assert.True(args.InteractiveMode);
AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "script.csx") }, args.SourceFiles.Select(f => f.Path));
AssertEx.Equal(new[] { "a", "b", "c" }, args.ScriptArguments);
args = ScriptParse(new[] { "-i", "--", "--", "--" }, baseDirectory: WorkingDirectory);
Assert.True(args.InteractiveMode);
AssertEx.Equal(new[] { Path.Combine(WorkingDirectory, "--") }, args.SourceFiles.Select(f => f.Path));
Assert.True(args.SourceFiles[0].IsScript);
AssertEx.Equal(new[] { "--" }, args.ScriptArguments);
// TODO: fails on Linux (https://github.com/dotnet/roslyn/issues/5904)
// Result: C:\/script.csx
//args = ScriptParse(new[] { "-i", "script.csx", "--", "--" }, baseDirectory: @"C:\");
//Assert.True(args.InteractiveMode);
//AssertEx.Equal(new[] { @"C:\script.csx" }, args.SourceFiles.Select(f => f.Path));
//Assert.True(args.SourceFiles[0].IsScript);
//AssertEx.Equal(new[] { "--" }, args.ScriptArguments);
}
[WorkItem(127403, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/127403")]
[Fact]
public void ParseSeparatedPaths_QuotedComma()
{
var paths = CSharpCommandLineParser.ParseSeparatedPaths(@"""a, b""");
Assert.Equal(
new[] { @"a, b" },
paths);
}
[Fact]
[CompilerTrait(CompilerFeature.Determinism)]
public void PathMapParser()
{
var s = PathUtilities.DirectorySeparatorStr;
var parsedArgs = DefaultParse(new[] { "/pathmap:", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap);
parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]);
parsedArgs = DefaultParse(new[] { $"/pathmap:abc{s}=/", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(KeyValuePairUtil.Create("abc" + s, "/"), parsedArgs.PathMap[0]);
parsedArgs = DefaultParse(new[] { "/pathmap:K1=V1,K2=V2", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(KeyValuePairUtil.Create("K1" + s, "V1" + s), parsedArgs.PathMap[0]);
Assert.Equal(KeyValuePairUtil.Create("K2" + s, "V2" + s), parsedArgs.PathMap[1]);
parsedArgs = DefaultParse(new[] { "/pathmap:,", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(ImmutableArray.Create<KeyValuePair<string, string>>(), parsedArgs.PathMap);
parsedArgs = DefaultParse(new[] { "/pathmap:,,", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Count());
Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code);
parsedArgs = DefaultParse(new[] { "/pathmap:,,,", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Count());
Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code);
parsedArgs = DefaultParse(new[] { "/pathmap:k=,=v", "a.cs" }, WorkingDirectory);
Assert.Equal(2, parsedArgs.Errors.Count());
Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code);
Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[1].Code);
parsedArgs = DefaultParse(new[] { "/pathmap:k=v=bad", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Count());
Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code);
parsedArgs = DefaultParse(new[] { "/pathmap:k=", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Count());
Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code);
parsedArgs = DefaultParse(new[] { "/pathmap:=v", "a.cs" }, WorkingDirectory);
Assert.Equal(1, parsedArgs.Errors.Count());
Assert.Equal((int)ErrorCode.ERR_InvalidPathMap, parsedArgs.Errors[0].Code);
parsedArgs = DefaultParse(new[] { "/pathmap:\"supporting spaces=is hard\"", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(KeyValuePairUtil.Create("supporting spaces" + s, "is hard" + s), parsedArgs.PathMap[0]);
parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1=V 1\",\"K 2=V 2\"", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]);
Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]);
parsedArgs = DefaultParse(new[] { "/pathmap:\"K 1\"=\"V 1\",\"K 2\"=\"V 2\"", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(KeyValuePairUtil.Create("K 1" + s, "V 1" + s), parsedArgs.PathMap[0]);
Assert.Equal(KeyValuePairUtil.Create("K 2" + s, "V 2" + s), parsedArgs.PathMap[1]);
parsedArgs = DefaultParse(new[] { "/pathmap:\"a ==,,b\"=\"1,,== 2\",\"x ==,,y\"=\"3 4\",", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(KeyValuePairUtil.Create("a =,b" + s, "1,= 2" + s), parsedArgs.PathMap[0]);
Assert.Equal(KeyValuePairUtil.Create("x =,y" + s, "3 4" + s), parsedArgs.PathMap[1]);
parsedArgs = DefaultParse(new[] { @"/pathmap:C:\temp\=/_1/,C:\temp\a\=/_2/,C:\temp\a\b\=/_3/", "a.cs", @"a\b.cs", @"a\b\c.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\b\", "/_3/"), parsedArgs.PathMap[0]);
Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\a\", "/_2/"), parsedArgs.PathMap[1]);
Assert.Equal(KeyValuePairUtil.Create(@"C:\temp\", "/_1/"), parsedArgs.PathMap[2]);
}
[Theory]
[InlineData("", new string[0])]
[InlineData(",", new[] { "", "" })]
[InlineData(",,", new[] { "," })]
[InlineData(",,,", new[] { ",", "" })]
[InlineData(",,,,", new[] { ",," })]
[InlineData("a,", new[] { "a", "" })]
[InlineData("a,b", new[] { "a", "b" })]
[InlineData(",,a,,,,,b,,", new[] { ",a,,", "b," })]
public void SplitWithDoubledSeparatorEscaping(string str, string[] expected)
{
AssertEx.Equal(expected, CommandLineParser.SplitWithDoubledSeparatorEscaping(str, ','));
}
[ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
[CompilerTrait(CompilerFeature.Determinism)]
public void PathMapPdbParser()
{
var dir = Path.Combine(WorkingDirectory, "a");
var parsedArgs = DefaultParse(new[] { $@"/pathmap:{dir}=b:\", "a.cs", @"/pdb:a\data.pdb", "/debug:full" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Path.Combine(dir, @"data.pdb"), parsedArgs.PdbPath);
// This value is calculate during Emit phases and should be null even in the face of a pathmap targeting it.
Assert.Null(parsedArgs.EmitOptions.PdbFilePath);
}
[ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.NativePdbRequiresDesktop)]
[CompilerTrait(CompilerFeature.Determinism)]
public void PathMapPdbEmit()
{
void AssertPdbEmit(TempDirectory dir, string pdbPath, string pePdbPath, params string[] extraArgs)
{
var source = @"class Program { static void Main() { } }";
var src = dir.CreateFile("a.cs").WriteAllText(source);
var defaultArgs = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug:full", $"/pdb:{pdbPath}" };
var isDeterministic = extraArgs.Contains("/deterministic");
var args = defaultArgs.Concat(extraArgs).ToArray();
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, args);
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
var exePath = Path.Combine(dir.Path, "a.exe");
Assert.True(File.Exists(exePath));
Assert.True(File.Exists(pdbPath));
using (var peStream = File.OpenRead(exePath))
{
PdbValidation.ValidateDebugDirectory(peStream, null, pePdbPath, hashAlgorithm: default, hasEmbeddedPdb: false, isDeterministic);
}
}
// Case with no mappings
using (var dir = new DisposableDirectory(Temp))
{
var pdbPath = Path.Combine(dir.Path, "a.pdb");
AssertPdbEmit(dir, pdbPath, pdbPath);
}
// Simple mapping
using (var dir = new DisposableDirectory(Temp))
{
var pdbPath = Path.Combine(dir.Path, "a.pdb");
AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\");
}
// Simple mapping deterministic
using (var dir = new DisposableDirectory(Temp))
{
var pdbPath = Path.Combine(dir.Path, "a.pdb");
AssertPdbEmit(dir, pdbPath, @"q:\a.pdb", $@"/pathmap:{dir.Path}=q:\", "/deterministic");
}
// Partial mapping
using (var dir = new DisposableDirectory(Temp))
{
dir.CreateDirectory("pdb");
var pdbPath = Path.Combine(dir.Path, @"pdb\a.pdb");
AssertPdbEmit(dir, pdbPath, @"q:\pdb\a.pdb", $@"/pathmap:{dir.Path}=q:\");
}
// Legacy feature flag
using (var dir = new DisposableDirectory(Temp))
{
var pdbPath = Path.Combine(dir.Path, "a.pdb");
AssertPdbEmit(dir, pdbPath, @"a.pdb", $@"/features:pdb-path-determinism");
}
// Unix path map
using (var dir = new DisposableDirectory(Temp))
{
var pdbPath = Path.Combine(dir.Path, "a.pdb");
AssertPdbEmit(dir, pdbPath, @"/a.pdb", $@"/pathmap:{dir.Path}=/");
}
// Multi-specified path map with mixed slashes
using (var dir = new DisposableDirectory(Temp))
{
var pdbPath = Path.Combine(dir.Path, "a.pdb");
AssertPdbEmit(dir, pdbPath, "/goo/a.pdb", $"/pathmap:{dir.Path}=/goo,{dir.Path}{PathUtilities.DirectorySeparatorChar}=/bar");
}
}
[CompilerTrait(CompilerFeature.Determinism)]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void DeterministicPdbsRegardlessOfBitness()
{
var dir = Temp.CreateDirectory();
var dir32 = dir.CreateDirectory("32");
var dir64 = dir.CreateDirectory("64");
var programExe32 = dir32.CreateFile("Program.exe");
var programPdb32 = dir32.CreateFile("Program.pdb");
var programExe64 = dir64.CreateFile("Program.exe");
var programPdb64 = dir64.CreateFile("Program.pdb");
var sourceFile = dir.CreateFile("Source.cs").WriteAllText(@"
using System;
using System.Linq;
using System.Collections.Generic;
namespace N
{
using I4 = System.Int32;
class Program
{
public static IEnumerable<int> F()
{
I4 x = 1;
yield return 1;
yield return x;
}
public static void Main(string[] args)
{
dynamic x = 1;
const int a = 1;
F().ToArray();
Console.WriteLine(x + a);
}
}
}");
var csc32src = $@"
using System;
using System.Reflection;
class Runner
{{
static int Main(string[] args)
{{
var assembly = Assembly.LoadFrom(@""{s_CSharpCompilerExecutable}"");
var program = assembly.GetType(""Microsoft.CodeAnalysis.CSharp.CommandLine.Program"");
var main = program.GetMethod(""Main"");
return (int)main.Invoke(null, new object[] {{ args }});
}}
}}
";
var csc32 = CreateCompilationWithMscorlib46(csc32src, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86), assemblyName: "csc32");
var csc32exe = dir.CreateFile("csc32.exe").WriteAllBytes(csc32.EmitToArray());
dir.CopyFile(Path.ChangeExtension(s_CSharpCompilerExecutable, ".exe.config"), "csc32.exe.config");
dir.CopyFile(Path.Combine(Path.GetDirectoryName(s_CSharpCompilerExecutable), "csc.rsp"));
var output = ProcessUtilities.RunAndGetOutput(csc32exe.Path, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir32.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir32.Path);
Assert.Equal("", output);
output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, $@"/nologo /debug:full /deterministic /out:Program.exe /pathmap:""{dir64.Path}""=X:\ ""{sourceFile.Path}""", expectedRetCode: 0, startFolder: dir64.Path);
Assert.Equal("", output);
AssertEx.Equal(programExe32.ReadAllBytes(), programExe64.ReadAllBytes());
AssertEx.Equal(programPdb32.ReadAllBytes(), programPdb64.ReadAllBytes());
}
[WorkItem(7588, "https://github.com/dotnet/roslyn/issues/7588")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void Version()
{
var folderName = Temp.CreateDirectory().ToString();
var argss = new[]
{
"/version",
"a.cs /version /preferreduilang:en",
"/version /nologo",
"/version /help",
};
foreach (var args in argss)
{
var output = ProcessUtilities.RunAndGetOutput(s_CSharpCompilerExecutable, args, startFolder: folderName);
Assert.Equal(s_compilerVersion, output.Trim());
}
}
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void RefOut()
{
var dir = Temp.CreateDirectory();
var refDir = dir.CreateDirectory("ref");
var src = dir.CreateFile("a.cs");
src.WriteAllText(@"
public class C
{
/// <summary>Main method</summary>
public static void Main()
{
System.Console.Write(""Hello"");
}
/// <summary>Private method</summary>
private static void PrivateMethod()
{
System.Console.Write(""Private"");
}
}");
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path,
new[] { "/nologo", "/out:a.exe", "/refout:ref/a.dll", "/doc:doc.xml", "/deterministic", "/langversion:7", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
var exe = Path.Combine(dir.Path, "a.exe");
Assert.True(File.Exists(exe));
MetadataReaderUtils.VerifyPEMetadata(exe,
new[] { "TypeDefinition:<Module>", "TypeDefinition:C" },
new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C.PrivateMethod()", "MethodDefinition:Void C..ctor()" },
new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute" }
);
var doc = Path.Combine(dir.Path, "doc.xml");
Assert.True(File.Exists(doc));
var content = File.ReadAllText(doc);
var expectedDoc =
@"<?xml version=""1.0""?>
<doc>
<assembly>
<name>a</name>
</assembly>
<members>
<member name=""M:C.Main"">
<summary>Main method</summary>
</member>
<member name=""M:C.PrivateMethod"">
<summary>Private method</summary>
</member>
</members>
</doc>";
Assert.Equal(expectedDoc, content.Trim());
var output = ProcessUtilities.RunAndGetOutput(exe, startFolder: dir.Path);
Assert.Equal("Hello", output.Trim());
var refDll = Path.Combine(refDir.Path, "a.dll");
Assert.True(File.Exists(refDll));
// The types and members that are included needs further refinement.
// See issue https://github.com/dotnet/roslyn/issues/17612
MetadataReaderUtils.VerifyPEMetadata(refDll,
new[] { "TypeDefinition:<Module>", "TypeDefinition:C" },
new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" },
new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" }
);
// Clean up temp files
CleanupAllGeneratedFiles(dir.Path);
CleanupAllGeneratedFiles(refDir.Path);
}
[Fact]
public void RefOutWithError()
{
var dir = Temp.CreateDirectory();
dir.CreateDirectory("ref");
var src = dir.CreateFile("a.cs");
src.WriteAllText(@"class C { public static void Main() { error(); } }");
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path,
new[] { "/nologo", "/out:a.dll", "/refout:ref/a.dll", "/deterministic", "/preferreduilang:en", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal(1, exitCode);
var dll = Path.Combine(dir.Path, "a.dll");
Assert.False(File.Exists(dll));
var refDll = Path.Combine(dir.Path, Path.Combine("ref", "a.dll"));
Assert.False(File.Exists(refDll));
Assert.Equal("a.cs(1,39): error CS0103: The name 'error' does not exist in the current context", outWriter.ToString().Trim());
// Clean up temp files
CleanupAllGeneratedFiles(dir.Path);
}
[Fact]
public void RefOnly()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("a.cs");
src.WriteAllText(@"
using System;
class C
{
/// <summary>Main method</summary>
public static void Main()
{
error(); // semantic error in method body
}
private event Action E1
{
add { }
remove { }
}
private event Action E2;
/// <summary>Private Class Field</summary>
private int field;
/// <summary>Private Struct</summary>
private struct S
{
/// <summary>Private Struct Field</summary>
private int field;
}
}");
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path,
new[] { "/nologo", "/out:a.dll", "/refonly", "/debug", "/deterministic", "/langversion:7", "/doc:doc.xml", "a.cs" });
int exitCode = csc.Run(outWriter);
Assert.Equal("", outWriter.ToString());
Assert.Equal(0, exitCode);
var refDll = Path.Combine(dir.Path, "a.dll");
Assert.True(File.Exists(refDll));
// The types and members that are included needs further refinement.
// See issue https://github.com/dotnet/roslyn/issues/17612
MetadataReaderUtils.VerifyPEMetadata(refDll,
new[] { "TypeDefinition:<Module>", "TypeDefinition:C", "TypeDefinition:S" },
new[] { "MethodDefinition:Void C.Main()", "MethodDefinition:Void C..ctor()" },
new[] { "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute", "ReferenceAssemblyAttribute" }
);
var pdb = Path.Combine(dir.Path, "a.pdb");
Assert.False(File.Exists(pdb));
var doc = Path.Combine(dir.Path, "doc.xml");
Assert.True(File.Exists(doc));
var content = File.ReadAllText(doc);
var expectedDoc =
@"<?xml version=""1.0""?>
<doc>
<assembly>
<name>a</name>
</assembly>
<members>
<member name=""M:C.Main"">
<summary>Main method</summary>
</member>
<member name=""F:C.field"">
<summary>Private Class Field</summary>
</member>
<member name=""T:C.S"">
<summary>Private Struct</summary>
</member>
<member name=""F:C.S.field"">
<summary>Private Struct Field</summary>
</member>
</members>
</doc>";
Assert.Equal(expectedDoc, content.Trim());
// Clean up temp files
CleanupAllGeneratedFiles(dir.Path);
}
[Fact]
public void CompilingCodeWithInvalidPreProcessorSymbolsShouldProvideDiagnostics()
{
var parsedArgs = DefaultParse(new[] { "/define:1", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// warning CS2029: Invalid name for a preprocessing symbol; '1' is not a valid identifier
Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("1").WithLocation(1, 1));
}
[Fact]
public void WhitespaceInDefine()
{
var parsedArgs = DefaultParse(new[] { "/define:\" a\"", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify();
Assert.Equal("a", parsedArgs.ParseOptions.PreprocessorSymbols.Single());
}
[Fact]
public void WhitespaceInDefine_OnlySpaces()
{
var parsedArgs = DefaultParse(new[] { "/define:\" \"", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments(" ").WithLocation(1, 1)
);
Assert.True(parsedArgs.ParseOptions.PreprocessorSymbols.IsEmpty);
}
[Fact]
public void CompilingCodeWithInvalidLanguageVersionShouldProvideDiagnostics()
{
var parsedArgs = DefaultParse(new[] { "/langversion:1000", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// error CS1617: Invalid option '1000' for /langversion. Use '/langversion:?' to list supported values.
Diagnostic(ErrorCode.ERR_BadCompatMode).WithArguments("1000").WithLocation(1, 1));
}
[Fact, WorkItem(16913, "https://github.com/dotnet/roslyn/issues/16913")]
public void CompilingCodeWithMultipleInvalidPreProcessorSymbolsShouldErrorOut()
{
var parsedArgs = DefaultParse(new[] { "/define:valid1,2invalid,valid3", "/define:4,5,valid6", "a.cs" }, WorkingDirectory);
parsedArgs.Errors.Verify(
// warning CS2029: Invalid value for '/define'; '2invalid' is not a valid identifier
Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("2invalid"),
// warning CS2029: Invalid value for '/define'; '4' is not a valid identifier
Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("4"),
// warning CS2029: Invalid value for '/define'; '5' is not a valid identifier
Diagnostic(ErrorCode.WRN_DefineIdentifierRequired).WithArguments("5"));
}
[WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=406649")]
[ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void MissingCompilerAssembly()
{
var dir = Temp.CreateDirectory();
var cscPath = dir.CopyFile(s_CSharpCompilerExecutable).Path;
dir.CopyFile(typeof(Compilation).Assembly.Location);
// Missing Microsoft.CodeAnalysis.CSharp.dll.
var result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path);
Assert.Equal(1, result.ExitCode);
Assert.Equal(
$"Could not load file or assembly '{typeof(CSharpCompilation).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.",
result.Output.Trim());
// Missing System.Collections.Immutable.dll.
dir.CopyFile(typeof(CSharpCompilation).Assembly.Location);
result = ProcessUtilities.Run(cscPath, arguments: "/nologo /t:library unknown.cs", workingDirectory: dir.Path);
Assert.Equal(1, result.ExitCode);
Assert.Equal(
$"Could not load file or assembly '{typeof(ImmutableArray).Assembly.FullName}' or one of its dependencies. The system cannot find the file specified.",
result.Output.Trim());
}
#if NET472
[ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void LoadinganalyzerNetStandard13()
{
var analyzerFileName = "AnalyzerNS13.dll";
var srcFileName = "src.cs";
var analyzerDir = Temp.CreateDirectory();
var analyzerFile = analyzerDir.CreateFile(analyzerFileName).WriteAllBytes(CreateCSharpAnalyzerNetStandard13(Path.GetFileNameWithoutExtension(analyzerFileName)));
var srcFile = analyzerDir.CreateFile(srcFileName).WriteAllText("public class C { }");
var result = ProcessUtilities.Run(s_CSharpCompilerExecutable, arguments: $"/nologo /t:library /analyzer:{analyzerFileName} {srcFileName}", workingDirectory: analyzerDir.Path);
var outputWithoutPaths = Regex.Replace(result.Output, " in .*", "");
AssertEx.AssertEqualToleratingWhitespaceDifferences(
$@"warning AD0001: Analyzer 'TestAnalyzer' threw an exception of type 'System.NotImplementedException' with message '28'.
System.NotImplementedException: 28
at TestAnalyzer.get_SupportedDiagnostics()
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerManager.AnalyzerExecutionContext.<>c__DisplayClass20_0.<ComputeDiagnosticDescriptors>b__0(Object _)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action`1 analyze, TArg argument, Nullable`1 info)
-----", outputWithoutPaths);
Assert.Equal(0, result.ExitCode);
}
#endif
private static ImmutableArray<byte> CreateCSharpAnalyzerNetStandard13(string analyzerAssemblyName)
{
var minSystemCollectionsImmutableSource = @"
[assembly: System.Reflection.AssemblyVersion(""1.2.3.0"")]
namespace System.Collections.Immutable
{
public struct ImmutableArray<T>
{
}
}
";
var minCodeAnalysisSource = @"
using System;
[assembly: System.Reflection.AssemblyVersion(""2.0.0.0"")]
namespace Microsoft.CodeAnalysis.Diagnostics
{
[AttributeUsage(AttributeTargets.Class)]
public sealed class DiagnosticAnalyzerAttribute : Attribute
{
public DiagnosticAnalyzerAttribute(string firstLanguage, params string[] additionalLanguages) {}
}
public abstract class DiagnosticAnalyzer
{
public abstract System.Collections.Immutable.ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }
public abstract void Initialize(AnalysisContext context);
}
public abstract class AnalysisContext
{
}
}
namespace Microsoft.CodeAnalysis
{
public sealed class DiagnosticDescriptor
{
}
}
";
var minSystemCollectionsImmutableImage = CSharpCompilation.Create(
"System.Collections.Immutable",
new[] { SyntaxFactory.ParseSyntaxTree(minSystemCollectionsImmutableSource) },
new MetadataReference[] { NetStandard13.SystemRuntime },
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_b03f5f7f11d50a3a)).EmitToArray();
var minSystemCollectionsImmutableRef = MetadataReference.CreateFromImage(minSystemCollectionsImmutableImage);
var minCodeAnalysisImage = CSharpCompilation.Create(
"Microsoft.CodeAnalysis",
new[] { SyntaxFactory.ParseSyntaxTree(minCodeAnalysisSource) },
new MetadataReference[]
{
NetStandard13.SystemRuntime,
minSystemCollectionsImmutableRef
},
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, cryptoPublicKey: TestResources.TestKeys.PublicKey_31bf3856ad364e35)).EmitToArray();
var minCodeAnalysisRef = MetadataReference.CreateFromImage(minCodeAnalysisImage);
var analyzerSource = @"
using System;
using System.Collections.ObjectModel;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Net.Security;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.Win32.SafeHandles;
[DiagnosticAnalyzer(""C#"")]
public class TestAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => throw new NotImplementedException(new[]
{
typeof(Win32Exception), // Microsoft.Win32.Primitives
typeof(AppContext), // System.AppContext
typeof(Console), // System.Console
typeof(ValueTuple), // System.ValueTuple
typeof(FileVersionInfo), // System.Diagnostics.FileVersionInfo
typeof(Process), // System.Diagnostics.Process
typeof(ChineseLunisolarCalendar), // System.Globalization.Calendars
typeof(ZipArchive), // System.IO.Compression
typeof(ZipFile), // System.IO.Compression.ZipFile
typeof(FileOptions), // System.IO.FileSystem
typeof(FileAttributes), // System.IO.FileSystem.Primitives
typeof(HttpClient), // System.Net.Http
typeof(AuthenticatedStream), // System.Net.Security
typeof(IOControlCode), // System.Net.Sockets
typeof(RuntimeInformation), // System.Runtime.InteropServices.RuntimeInformation
typeof(SerializationException), // System.Runtime.Serialization.Primitives
typeof(GenericIdentity), // System.Security.Claims
typeof(Aes), // System.Security.Cryptography.Algorithms
typeof(CspParameters), // System.Security.Cryptography.Csp
typeof(AsnEncodedData), // System.Security.Cryptography.Encoding
typeof(AsymmetricAlgorithm), // System.Security.Cryptography.Primitives
typeof(SafeX509ChainHandle), // System.Security.Cryptography.X509Certificates
typeof(IXmlLineInfo), // System.Xml.ReaderWriter
typeof(XmlNode), // System.Xml.XmlDocument
typeof(XPathDocument), // System.Xml.XPath
typeof(XDocumentExtensions), // System.Xml.XPath.XDocument
typeof(CodePagesEncodingProvider),// System.Text.Encoding.CodePages
typeof(ValueTask<>), // System.Threading.Tasks.Extensions
// csc doesn't ship with facades for the following assemblies.
// Analyzers can't use them unless they carry the facade with them.
// typeof(SafePipeHandle), // System.IO.Pipes
// typeof(StackFrame), // System.Diagnostics.StackTrace
// typeof(BindingFlags), // System.Reflection.TypeExtensions
// typeof(AccessControlActions), // System.Security.AccessControl
// typeof(SafeAccessTokenHandle), // System.Security.Principal.Windows
// typeof(Thread), // System.Threading.Thread
}.Length.ToString());
public override void Initialize(AnalysisContext context)
{
}
}";
var references =
new MetadataReference[]
{
minCodeAnalysisRef,
minSystemCollectionsImmutableRef
};
references = references.Concat(NetStandard13.All).ToArray();
var analyzerImage = CSharpCompilation.Create(
analyzerAssemblyName,
new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree(analyzerSource) },
references: references,
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)).EmitToArray();
return analyzerImage;
}
[WorkItem(406649, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=484417")]
[ConditionalFact(typeof(WindowsDesktopOnly), typeof(IsEnglishLocal), Reason = "https://github.com/dotnet/roslyn/issues/30321")]
public void MicrosoftDiaSymReaderNativeAltLoadPath()
{
var dir = Temp.CreateDirectory();
var cscDir = Path.GetDirectoryName(s_CSharpCompilerExecutable);
// copy csc and dependencies except for DSRN:
foreach (var filePath in Directory.EnumerateFiles(cscDir))
{
var fileName = Path.GetFileName(filePath);
if (fileName.StartsWith("csc") ||
fileName.StartsWith("System.") ||
fileName.StartsWith("Microsoft.") && !fileName.StartsWith("Microsoft.DiaSymReader.Native"))
{
dir.CopyFile(filePath);
}
}
dir.CreateFile("Source.cs").WriteAllText("class C { void F() { } }");
var cscCopy = Path.Combine(dir.Path, "csc.exe");
var arguments = "/nologo /t:library /debug:full Source.cs";
// env variable not set (deterministic) -- DSRN is required:
var result = ProcessUtilities.Run(
cscCopy,
arguments + " /deterministic",
workingDirectory: dir.Path,
additionalEnvironmentVars: new[] { KeyValuePairUtil.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", "") });
AssertEx.AssertEqualToleratingWhitespaceDifferences(
"error CS0041: Unexpected error writing debug information -- 'Unable to load DLL 'Microsoft.DiaSymReader.Native.amd64.dll': " +
"The specified module could not be found. (Exception from HRESULT: 0x8007007E)'", result.Output.Trim());
// env variable not set (non-deterministic) -- globally registered SymReader is picked up:
result = ProcessUtilities.Run(cscCopy, arguments, workingDirectory: dir.Path);
AssertEx.AssertEqualToleratingWhitespaceDifferences("", result.Output.Trim());
// env variable set:
result = ProcessUtilities.Run(
cscCopy,
arguments + " /deterministic",
workingDirectory: dir.Path,
additionalEnvironmentVars: new[] { KeyValuePairUtil.Create("MICROSOFT_DIASYMREADER_NATIVE_ALT_LOAD_PATH", cscDir) });
Assert.Equal("", result.Output.Trim());
}
[ConditionalFact(typeof(WindowsOnly))]
[WorkItem(21935, "https://github.com/dotnet/roslyn/issues/21935")]
public void PdbPathNotEmittedWithoutPdb()
{
var dir = Temp.CreateDirectory();
var source = @"class Program { static void Main() { } }";
var src = dir.CreateFile("a.cs").WriteAllText(source);
var args = new[] { "/nologo", "a.cs", "/out:a.exe", "/debug-" };
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(null, dir.Path, args);
int exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
var exePath = Path.Combine(dir.Path, "a.exe");
Assert.True(File.Exists(exePath));
using (var peStream = File.OpenRead(exePath))
using (var peReader = new PEReader(peStream))
{
var debugDirectory = peReader.PEHeaders.PEHeader.DebugTableDirectory;
Assert.Equal(0, debugDirectory.Size);
Assert.Equal(0, debugDirectory.RelativeVirtualAddress);
}
}
[Fact]
public void StrongNameProviderWithCustomTempPath()
{
var tempDir = Temp.CreateDirectory();
var workingDir = Temp.CreateDirectory();
workingDir.CreateFile("a.cs");
var buildPaths = new BuildPaths(clientDir: "", workingDir: workingDir.Path, sdkDir: null, tempDir: tempDir.Path);
var csc = new MockCSharpCompiler(null, buildPaths, args: new[] { "/features:UseLegacyStrongNameProvider", "/nostdlib", "a.cs" });
var comp = csc.CreateCompilation(new StringWriter(), new TouchedFileLogger(), errorLogger: null);
Assert.True(!comp.SignUsingBuilder);
}
public class QuotedArgumentTests : CommandLineTestBase
{
private static readonly string s_rootPath = ExecutionConditionUtil.IsWindows
? @"c:\"
: "/";
private void VerifyQuotedValid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue)
{
var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath);
Assert.Equal(0, args.Errors.Length);
Assert.Equal(expected, getValue(args));
args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath);
Assert.Equal(0, args.Errors.Length);
Assert.Equal(expected, getValue(args));
}
private void VerifyQuotedInvalid<T>(string name, string value, T expected, Func<CSharpCommandLineArguments, T> getValue)
{
var args = DefaultParse(new[] { $"/{name}:{value}", "a.cs" }, s_rootPath);
Assert.Equal(0, args.Errors.Length);
Assert.Equal(expected, getValue(args));
args = DefaultParse(new[] { $@"/{name}:""{value}""", "a.cs" }, s_rootPath);
Assert.True(args.Errors.Length > 0);
}
[WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")]
[Fact]
public void DebugFlag()
{
var platformPdbKind = PathUtilities.IsUnixLikePlatform ? DebugInformationFormat.PortablePdb : DebugInformationFormat.Pdb;
var list = new List<Tuple<string, DebugInformationFormat>>()
{
Tuple.Create("portable", DebugInformationFormat.PortablePdb),
Tuple.Create("full", platformPdbKind),
Tuple.Create("pdbonly", platformPdbKind),
Tuple.Create("embedded", DebugInformationFormat.Embedded)
};
foreach (var tuple in list)
{
VerifyQuotedValid("debug", tuple.Item1, tuple.Item2, x => x.EmitOptions.DebugInformationFormat);
}
}
[WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30328")]
public void CodePage()
{
VerifyQuotedValid("codepage", "1252", 1252, x => x.Encoding.CodePage);
}
[WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")]
[Fact]
public void Target()
{
var list = new List<Tuple<string, OutputKind>>()
{
Tuple.Create("exe", OutputKind.ConsoleApplication),
Tuple.Create("winexe", OutputKind.WindowsApplication),
Tuple.Create("library", OutputKind.DynamicallyLinkedLibrary),
Tuple.Create("module", OutputKind.NetModule),
Tuple.Create("appcontainerexe", OutputKind.WindowsRuntimeApplication),
Tuple.Create("winmdobj", OutputKind.WindowsRuntimeMetadata)
};
foreach (var tuple in list)
{
VerifyQuotedInvalid("target", tuple.Item1, tuple.Item2, x => x.CompilationOptions.OutputKind);
}
}
[WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")]
[Fact]
public void PlatformFlag()
{
var list = new List<Tuple<string, Platform>>()
{
Tuple.Create("x86", Platform.X86),
Tuple.Create("x64", Platform.X64),
Tuple.Create("itanium", Platform.Itanium),
Tuple.Create("anycpu", Platform.AnyCpu),
Tuple.Create("anycpu32bitpreferred",Platform.AnyCpu32BitPreferred),
Tuple.Create("arm", Platform.Arm)
};
foreach (var tuple in list)
{
VerifyQuotedValid("platform", tuple.Item1, tuple.Item2, x => x.CompilationOptions.Platform);
}
}
[WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")]
[Fact]
public void WarnFlag()
{
VerifyQuotedValid("warn", "1", 1, x => x.CompilationOptions.WarningLevel);
}
[WorkItem(12427, "https://github.com/dotnet/roslyn/issues/12427")]
[Fact]
public void LangVersionFlag()
{
VerifyQuotedValid("langversion", "2", LanguageVersion.CSharp2, x => x.ParseOptions.LanguageVersion);
}
}
[Fact]
[WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")]
public void InvalidPathCharacterInPathMap()
{
string filePath = Temp.CreateFile().WriteAllText("").Path;
var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[]
{
filePath,
"/debug:embedded",
"/pathmap:test\\=\"",
"/target:library",
"/preferreduilang:en"
});
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = compiler.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Contains("error CS8101: The pathmap option was incorrectly formatted.", outWriter.ToString(), StringComparison.Ordinal);
}
[WorkItem(23525, "https://github.com/dotnet/roslyn/issues/23525")]
[ConditionalFact(typeof(WindowsDesktopOnly), Reason = "https://github.com/dotnet/roslyn/issues/30289")]
public void InvalidPathCharacterInPdbPath()
{
string filePath = Temp.CreateFile().WriteAllText("").Path;
var compiler = CreateCSharpCompiler(null, WorkingDirectory, new[]
{
filePath,
"/debug:embedded",
"/pdb:test\\?.pdb",
"/target:library",
"/preferreduilang:en"
});
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = compiler.Run(outWriter);
Assert.Equal(1, exitCode);
Assert.Contains("error CS2021: File name 'test\\?.pdb' is empty, contains invalid characters, has a drive specification without an absolute path, or is too long", outWriter.ToString(), StringComparison.Ordinal);
}
[WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")]
[ConditionalFact(typeof(IsEnglishLocal))]
public void TestSuppression_CompilerParserWarningAsError()
{
string source = @"
class C
{
long M(int i)
{
// warning CS0078 : The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
return 0l;
}
}
";
var srcDirectory = Temp.CreateDirectory();
var srcFile = srcDirectory.CreateFile("a.cs");
srcFile.WriteAllText(source);
// Verify that parser warning CS0078 is reported.
var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false);
Assert.Contains("warning CS0078", output, StringComparison.Ordinal);
// Verify that parser warning CS0078 is reported as error for /warnaserror.
output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1,
additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false);
Assert.Contains("error CS0078", output, StringComparison.Ordinal);
// Verify that parser warning CS0078 is suppressed with diagnostic suppressor even with /warnaserror
// and info diagnostic is logged with programmatic suppression information.
var suppressor = new DiagnosticSuppressorForId("CS0078");
output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0,
additionalFlags: new[] { "/warnAsError" },
includeCurrentAssemblyAsAnalyzerReference: false,
errorlog: true,
analyzers: suppressor);
Assert.DoesNotContain($"error CS0078", output, StringComparison.Ordinal);
Assert.DoesNotContain($"warning CS0078", output, StringComparison.Ordinal);
// Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}'
var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage,
suppressor.SuppressionDescriptor.SuppressedDiagnosticId,
new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_LowercaseEllSuffix, "l"), Location.None).GetMessage(CultureInfo.InvariantCulture),
suppressor.SuppressionDescriptor.Id,
suppressor.SuppressionDescriptor.Justification);
Assert.Contains("info SP0001", output, StringComparison.Ordinal);
Assert.Contains(suppressionMessage, output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(srcFile.Path);
}
[WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")]
[ConditionalTheory(typeof(IsEnglishLocal)), CombinatorialData]
public void TestSuppression_CompilerSyntaxWarning(bool skipAnalyzers)
{
// warning CS1522: Empty switch block
// NOTE: Empty switch block warning is reported by the C# language parser
string source = @"
class C
{
void M(int i)
{
switch (i)
{
}
}
}";
var srcDirectory = Temp.CreateDirectory();
var srcFile = srcDirectory.CreateFile("a.cs");
srcFile.WriteAllText(source);
// Verify that compiler warning CS1522 is reported.
var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, skipAnalyzers: skipAnalyzers);
Assert.Contains("warning CS1522", output, StringComparison.Ordinal);
// Verify that compiler warning CS1522 is suppressed with diagnostic suppressor
// and info diagnostic is logged with programmatic suppression information.
var suppressor = new DiagnosticSuppressorForId("CS1522");
// Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}'
var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage,
suppressor.SuppressionDescriptor.SuppressedDiagnosticId,
new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_EmptySwitch), Location.None).GetMessage(CultureInfo.InvariantCulture),
suppressor.SuppressionDescriptor.Id,
suppressor.SuppressionDescriptor.Justification);
output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false,
analyzers: suppressor, errorlog: true, skipAnalyzers: skipAnalyzers);
Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal);
Assert.Contains($"info SP0001", output, StringComparison.Ordinal);
Assert.Contains(suppressionMessage, output, StringComparison.Ordinal);
// Verify that compiler warning CS1522 is reported as error for /warnaserror.
output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1,
additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, skipAnalyzers: skipAnalyzers);
Assert.Contains("error CS1522", output, StringComparison.Ordinal);
// Verify that compiler warning CS1522 is suppressed with diagnostic suppressor even with /warnaserror
// and info diagnostic is logged with programmatic suppression information.
output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0,
additionalFlags: new[] { "/warnAsError" },
includeCurrentAssemblyAsAnalyzerReference: false,
errorlog: true,
skipAnalyzers: skipAnalyzers,
analyzers: suppressor);
Assert.DoesNotContain($"error CS1522", output, StringComparison.Ordinal);
Assert.DoesNotContain($"warning CS1522", output, StringComparison.Ordinal);
Assert.Contains("info SP0001", output, StringComparison.Ordinal);
Assert.Contains(suppressionMessage, output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(srcFile.Path);
}
[WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")]
[ConditionalTheory(typeof(IsEnglishLocal)), CombinatorialData]
public void TestSuppression_CompilerSemanticWarning(bool skipAnalyzers)
{
string source = @"
class C
{
// warning CS0169: The field 'C.f' is never used
private readonly int f;
}";
var srcDirectory = Temp.CreateDirectory();
var srcFile = srcDirectory.CreateFile("a.cs");
srcFile.WriteAllText(source);
// Verify that compiler warning CS0169 is reported.
var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, skipAnalyzers: skipAnalyzers);
Assert.Contains("warning CS0169", output, StringComparison.Ordinal);
// Verify that compiler warning CS0169 is suppressed with diagnostic suppressor
// and info diagnostic is logged with programmatic suppression information.
var suppressor = new DiagnosticSuppressorForId("CS0169");
// Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}'
var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage,
suppressor.SuppressionDescriptor.SuppressedDiagnosticId,
new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.WRN_UnreferencedField, "C.f"), Location.None).GetMessage(CultureInfo.InvariantCulture),
suppressor.SuppressionDescriptor.Id,
suppressor.SuppressionDescriptor.Justification);
output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, includeCurrentAssemblyAsAnalyzerReference: false,
analyzers: suppressor, errorlog: true, skipAnalyzers: skipAnalyzers);
Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal);
Assert.Contains("info SP0001", output, StringComparison.Ordinal);
Assert.Contains(suppressionMessage, output, StringComparison.Ordinal);
// Verify that compiler warning CS0169 is reported as error for /warnaserror.
output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1,
additionalFlags: new[] { "/warnAsError" }, includeCurrentAssemblyAsAnalyzerReference: false, skipAnalyzers: skipAnalyzers);
Assert.Contains("error CS0169", output, StringComparison.Ordinal);
// Verify that compiler warning CS0169 is suppressed with diagnostic suppressor even with /warnaserror
// and info diagnostic is logged with programmatic suppression information.
output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0, expectedErrorCount: 0,
additionalFlags: new[] { "/warnAsError" },
includeCurrentAssemblyAsAnalyzerReference: false,
errorlog: true,
skipAnalyzers: skipAnalyzers,
analyzers: suppressor);
Assert.DoesNotContain($"error CS0169", output, StringComparison.Ordinal);
Assert.DoesNotContain($"warning CS0169", output, StringComparison.Ordinal);
Assert.Contains("info SP0001", output, StringComparison.Ordinal);
Assert.Contains(suppressionMessage, output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(srcFile.Path);
}
[WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")]
[Fact]
public void TestNoSuppression_CompilerSyntaxError()
{
// error CS1001: Identifier expected
string source = @"
class { }";
var srcDirectory = Temp.CreateDirectory();
var srcFile = srcDirectory.CreateFile("a.cs");
srcFile.WriteAllText(source);
// Verify that compiler syntax error CS1001 is reported.
var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false);
Assert.Contains("error CS1001", output, StringComparison.Ordinal);
// Verify that compiler syntax error CS1001 cannot be suppressed with diagnostic suppressor.
output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false,
analyzers: new DiagnosticSuppressorForId("CS1001"));
Assert.Contains("error CS1001", output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(srcFile.Path);
}
[WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")]
[Fact]
public void TestNoSuppression_CompilerSemanticError()
{
// error CS0246: The type or namespace name 'UndefinedType' could not be found (are you missing a using directive or an assembly reference?)
string source = @"
class C
{
void M(UndefinedType x) { }
}";
var srcDirectory = Temp.CreateDirectory();
var srcFile = srcDirectory.CreateFile("a.cs");
srcFile.WriteAllText(source);
// Verify that compiler error CS0246 is reported.
var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false);
Assert.Contains("error CS0246", output, StringComparison.Ordinal);
// Verify that compiler error CS0246 cannot be suppressed with diagnostic suppressor.
output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false,
analyzers: new DiagnosticSuppressorForId("CS0246"));
Assert.Contains("error CS0246", output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(srcFile.Path);
}
[WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")]
[ConditionalFact(typeof(IsEnglishLocal))]
public void TestSuppression_AnalyzerWarning()
{
string source = @"
class C { }";
var srcDirectory = Temp.CreateDirectory();
var srcFile = srcDirectory.CreateFile("a.cs");
srcFile.WriteAllText(source);
// Verify that analyzer warning is reported.
var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true);
var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1,
includeCurrentAssemblyAsAnalyzerReference: false,
analyzers: analyzer);
Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal);
// Verify that analyzer warning is suppressed with diagnostic suppressor
// and info diagnostic is logged with programmatic suppression information.
var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id);
// Diagnostic '{0}: {1}' was programmatically suppressed by a DiagnosticSuppressor with suppression ID '{2}' and justification '{3}'
var suppressionMessage = string.Format(CodeAnalysisResources.SuppressionDiagnosticDescriptorMessage,
suppressor.SuppressionDescriptor.SuppressedDiagnosticId,
analyzer.Descriptor.MessageFormat,
suppressor.SuppressionDescriptor.Id,
suppressor.SuppressionDescriptor.Justification);
var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor };
output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0,
includeCurrentAssemblyAsAnalyzerReference: false,
errorlog: true,
analyzers: analyzerAndSuppressor);
Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal);
Assert.Contains("info SP0001", output, StringComparison.Ordinal);
Assert.Contains(suppressionMessage, output, StringComparison.Ordinal);
// Verify that analyzer warning is reported as error for /warnaserror.
output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1,
additionalFlags: new[] { "/warnAsError" },
includeCurrentAssemblyAsAnalyzerReference: false,
analyzers: analyzer);
Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal);
// Verify that analyzer warning is suppressed with diagnostic suppressor even with /warnaserror
// and info diagnostic is logged with programmatic suppression information.
output = VerifyOutput(srcDirectory, srcFile, expectedInfoCount: 1, expectedWarningCount: 0,
additionalFlags: new[] { "/warnAsError" },
includeCurrentAssemblyAsAnalyzerReference: false,
errorlog: true,
analyzers: analyzerAndSuppressor);
Assert.DoesNotContain($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal);
Assert.Contains("info SP0001", output, StringComparison.Ordinal);
Assert.Contains(suppressionMessage, output, StringComparison.Ordinal);
// Verify that "NotConfigurable" analyzer warning cannot be suppressed with diagnostic suppressor.
analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: false);
suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id);
analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor };
output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1,
includeCurrentAssemblyAsAnalyzerReference: false,
analyzers: analyzerAndSuppressor);
Assert.Contains($"warning {analyzer.Descriptor.Id}", output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(srcFile.Path);
}
[WorkItem(20242, "https://github.com/dotnet/roslyn/issues/20242")]
[Fact]
public void TestNoSuppression_AnalyzerError()
{
string source = @"
class C { }";
var srcDirectory = Temp.CreateDirectory();
var srcFile = srcDirectory.CreateFile("a.cs");
srcFile.WriteAllText(source);
// Verify that analyzer error is reported.
var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Error, configurable: true);
var output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1,
includeCurrentAssemblyAsAnalyzerReference: false,
analyzers: analyzer);
Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal);
// Verify that analyzer error cannot be suppressed with diagnostic suppressor.
var suppressor = new DiagnosticSuppressorForId(analyzer.Descriptor.Id);
var analyzerAndSuppressor = new DiagnosticAnalyzer[] { analyzer, suppressor };
output = VerifyOutput(srcDirectory, srcFile, expectedErrorCount: 1,
includeCurrentAssemblyAsAnalyzerReference: false,
analyzers: analyzerAndSuppressor);
Assert.Contains($"error {analyzer.Descriptor.Id}", output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(srcFile.Path);
}
[WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")]
[InlineData(DiagnosticSeverity.Warning, false)]
[InlineData(DiagnosticSeverity.Info, true)]
[InlineData(DiagnosticSeverity.Info, false)]
[InlineData(DiagnosticSeverity.Hidden, false)]
[Theory]
public void TestCategoryBasedBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog)
{
var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity);
var diagnosticId = analyzer.Descriptor.Id;
var category = analyzer.Descriptor.Category;
// Verify category based configuration without any diagnostic ID configuration is respected.
var analyzerConfigText = $@"
[*.cs]
dotnet_analyzer_diagnostic.category-{category}.severity = error";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error);
// Verify category based configuration does not get applied for suppressed diagnostic.
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true);
// Verify category based configuration does not get applied for diagnostic configured in ruleset.
var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis"">
<Rule Id=""{diagnosticId}"" Action=""Warning"" />
</Rules>
</RuleSet>";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText);
// Verify category based configuration before diagnostic ID configuration is not respected.
analyzerConfigText = $@"
[*.cs]
dotnet_analyzer_diagnostic.category-{category}.severity = error
dotnet_diagnostic.{diagnosticId}.severity = warning";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn);
// Verify category based configuration after diagnostic ID configuration is not respected.
analyzerConfigText = $@"
[*.cs]
dotnet_diagnostic.{diagnosticId}.severity = warning
dotnet_analyzer_diagnostic.category-{category}.severity = error";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn);
// Verify global config based configuration before diagnostic ID configuration is not respected.
analyzerConfigText = $@"
is_global = true
dotnet_analyzer_diagnostic.category-{category}.severity = error
dotnet_diagnostic.{diagnosticId}.severity = warning";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn);
// Verify global config based configuration after diagnostic ID configuration is not respected.
analyzerConfigText = $@"
is_global = true
dotnet_diagnostic.{diagnosticId}.severity = warning
dotnet_analyzer_diagnostic.category-{category}.severity = error";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn);
// Verify category based configuration to warning + /warnaserror reports errors.
analyzerConfigText = $@"
[*.cs]
dotnet_analyzer_diagnostic.category-{category}.severity = warning";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, warnAsError: true, expectedDiagnosticSeverity: ReportDiagnostic.Error);
// Verify disabled by default analyzer is not enabled by category based configuration.
analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity);
analyzerConfigText = $@"
[*.cs]
dotnet_analyzer_diagnostic.category-{category}.severity = error";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress);
// Verify disabled by default analyzer is not enabled by category based configuration in global config
analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity);
analyzerConfigText = $@"
is_global=true
dotnet_analyzer_diagnostic.category-{category}.severity = error";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress);
if (defaultSeverity == DiagnosticSeverity.Hidden ||
defaultSeverity == DiagnosticSeverity.Info && !errorlog)
{
// Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed.
analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true);
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress);
// Verify that bulk configuration 'none' entry does not enable this analyzer.
analyzerConfigText = $@"
[*.cs]
dotnet_analyzer_diagnostic.category-{category}.severity = none";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress);
// Verify that bulk configuration 'none' entry does not enable this analyzer via global config
analyzerConfigText = $@"
[*.cs]
dotnet_analyzer_diagnostic.category-{category}.severity = none";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress);
}
}
[WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")]
[InlineData(DiagnosticSeverity.Warning, false)]
[InlineData(DiagnosticSeverity.Info, true)]
[InlineData(DiagnosticSeverity.Info, false)]
[InlineData(DiagnosticSeverity.Hidden, false)]
[Theory]
public void TestBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog)
{
var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity);
var diagnosticId = analyzer.Descriptor.Id;
// Verify bulk configuration without any diagnostic ID configuration is respected.
var analyzerConfigText = $@"
[*.cs]
dotnet_analyzer_diagnostic.severity = error";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error);
// Verify bulk configuration does not get applied for suppressed diagnostic.
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress, noWarn: true);
// Verify bulk configuration does not get applied for diagnostic configured in ruleset.
var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis"">
<Rule Id=""{diagnosticId}"" Action=""Warning"" />
</Rules>
</RuleSet>";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText: rulesetText);
// Verify bulk configuration before diagnostic ID configuration is not respected.
analyzerConfigText = $@"
[*.cs]
dotnet_analyzer_diagnostic.severity = error
dotnet_diagnostic.{diagnosticId}.severity = warning";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn);
// Verify bulk configuration after diagnostic ID configuration is not respected.
analyzerConfigText = $@"
[*.cs]
dotnet_diagnostic.{diagnosticId}.severity = warning
dotnet_analyzer_diagnostic.severity = error";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn);
// Verify bulk configuration to warning + /warnaserror reports errors.
analyzerConfigText = $@"
[*.cs]
dotnet_analyzer_diagnostic.severity = warning";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, warnAsError: true, expectedDiagnosticSeverity: ReportDiagnostic.Error);
// Verify disabled by default analyzer is not enabled by bulk configuration.
analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: false, defaultSeverity);
analyzerConfigText = $@"
[*.cs]
dotnet_analyzer_diagnostic.severity = error";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress);
if (defaultSeverity == DiagnosticSeverity.Hidden ||
defaultSeverity == DiagnosticSeverity.Info && !errorlog)
{
// Verify analyzer with Hidden severity OR Info severity + no /errorlog is not executed.
analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true);
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText: string.Empty, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress);
// Verify that bulk configuration 'none' entry does not enable this analyzer.
analyzerConfigText = $@"
[*.cs]
dotnet_analyzer_diagnostic.severity = none";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Suppress);
}
}
[WorkItem(38674, "https://github.com/dotnet/roslyn/issues/38674")]
[InlineData(DiagnosticSeverity.Warning, false)]
[InlineData(DiagnosticSeverity.Info, true)]
[InlineData(DiagnosticSeverity.Info, false)]
[InlineData(DiagnosticSeverity.Hidden, false)]
[Theory]
public void TestMixedCategoryBasedAndBulkAnalyzerDiagnosticConfiguration(DiagnosticSeverity defaultSeverity, bool errorlog)
{
var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity);
var diagnosticId = analyzer.Descriptor.Id;
var category = analyzer.Descriptor.Category;
// Verify category based configuration before bulk analyzer diagnostic configuration is respected.
var analyzerConfigText = $@"
[*.cs]
dotnet_analyzer_diagnostic.category-{category}.severity = error
dotnet_analyzer_diagnostic.severity = warning";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error);
// Verify category based configuration after bulk analyzer diagnostic configuration is respected.
analyzerConfigText = $@"
[*.cs]
dotnet_analyzer_diagnostic.severity = warning
dotnet_analyzer_diagnostic.category-{category}.severity = error";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Error);
// Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in analyzer config.
analyzerConfigText = $@"
[*.cs]
dotnet_diagnostic.{diagnosticId}.severity = warning
dotnet_analyzer_diagnostic.category-{category}.severity = none
dotnet_analyzer_diagnostic.severity = suggestion";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn);
// Verify neither category based nor bulk diagnostic configuration is respected when specific diagnostic ID is configured in ruleset.
analyzerConfigText = $@"
[*.cs]
dotnet_analyzer_diagnostic.category-{category}.severity = none
dotnet_analyzer_diagnostic.severity = suggestion";
var rulesetText = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis"">
<Rule Id=""{diagnosticId}"" Action=""Warning"" />
</Rules>
</RuleSet>";
TestBulkAnalyzerConfigurationCore(analyzer, analyzerConfigText, errorlog, expectedDiagnosticSeverity: ReportDiagnostic.Warn, rulesetText);
}
private void TestBulkAnalyzerConfigurationCore(
NamedTypeAnalyzerWithConfigurableEnabledByDefault analyzer,
string analyzerConfigText,
bool errorlog,
ReportDiagnostic expectedDiagnosticSeverity,
string rulesetText = null,
bool noWarn = false,
bool warnAsError = false)
{
var diagnosticId = analyzer.Descriptor.Id;
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }");
var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(analyzerConfigText);
var arguments = new[] {
"/nologo",
"/t:library",
"/preferreduilang:en",
"/analyzerconfig:" + analyzerConfig.Path,
src.Path };
if (noWarn)
{
arguments = arguments.Append($"/nowarn:{diagnosticId}");
}
if (warnAsError)
{
arguments = arguments.Append($"/warnaserror");
}
if (errorlog)
{
arguments = arguments.Append($"/errorlog:errorlog");
}
if (rulesetText != null)
{
var rulesetFile = CreateRuleSetFile(rulesetText);
arguments = arguments.Append($"/ruleset:{rulesetFile.Path}");
}
var cmd = CreateCSharpCompiler(null, dir.Path, arguments,
analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer));
Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths));
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
var expectedErrorCode = expectedDiagnosticSeverity == ReportDiagnostic.Error ? 1 : 0;
Assert.Equal(expectedErrorCode, exitCode);
var prefix = expectedDiagnosticSeverity switch
{
ReportDiagnostic.Error => "error",
ReportDiagnostic.Warn => "warning",
ReportDiagnostic.Info => errorlog ? "info" : null,
ReportDiagnostic.Hidden => null,
ReportDiagnostic.Suppress => null,
_ => throw ExceptionUtilities.UnexpectedValue(expectedDiagnosticSeverity)
};
if (prefix == null)
{
Assert.DoesNotContain(diagnosticId, outWriter.ToString());
}
else
{
Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", outWriter.ToString());
}
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")]
public void CompilerWarnAsErrorDoesNotEmit(bool warnAsError)
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
int _f; // CS0169: unused field
}");
var docName = "temp.xml";
var pdbName = "temp.pdb";
var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" };
if (warnAsError)
{
additionalArgs = additionalArgs.Append("/warnaserror").AsArray();
}
var expectedErrorCount = warnAsError ? 1 : 0;
var expectedWarningCount = !warnAsError ? 1 : 0;
var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false,
additionalArgs,
expectedErrorCount: expectedErrorCount,
expectedWarningCount: expectedWarningCount);
var expectedOutput = warnAsError ? "error CS0169" : "warning CS0169";
Assert.Contains(expectedOutput, output);
string binaryPath = Path.Combine(dir.Path, "temp.dll");
Assert.True(File.Exists(binaryPath) == !warnAsError);
string pdbPath = Path.Combine(dir.Path, pdbName);
Assert.True(File.Exists(pdbPath) == !warnAsError);
string xmlDocFilePath = Path.Combine(dir.Path, docName);
Assert.True(File.Exists(xmlDocFilePath) == !warnAsError);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")]
public void AnalyzerConfigSeverityEscalationToErrorDoesNotEmit(bool analyzerConfigSetToError)
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
int _f; // CS0169: unused field
}");
var docName = "temp.xml";
var pdbName = "temp.pdb";
var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" };
if (analyzerConfigSetToError)
{
var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@"
[*.cs]
dotnet_diagnostic.cs0169.severity = error");
additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray();
}
var expectedErrorCount = analyzerConfigSetToError ? 1 : 0;
var expectedWarningCount = !analyzerConfigSetToError ? 1 : 0;
var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false,
additionalArgs,
expectedErrorCount: expectedErrorCount,
expectedWarningCount: expectedWarningCount);
var expectedOutput = analyzerConfigSetToError ? "error CS0169" : "warning CS0169";
Assert.Contains(expectedOutput, output);
string binaryPath = Path.Combine(dir.Path, "temp.dll");
Assert.True(File.Exists(binaryPath) == !analyzerConfigSetToError);
string pdbPath = Path.Combine(dir.Path, pdbName);
Assert.True(File.Exists(pdbPath) == !analyzerConfigSetToError);
string xmlDocFilePath = Path.Combine(dir.Path, docName);
Assert.True(File.Exists(xmlDocFilePath) == !analyzerConfigSetToError);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")]
public void RulesetSeverityEscalationToErrorDoesNotEmit(bool rulesetSetToError)
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
int _f; // CS0169: unused field
}");
var docName = "temp.xml";
var pdbName = "temp.pdb";
var additionalArgs = new[] { $"/doc:{docName}", $"/pdb:{pdbName}", "/debug" };
if (rulesetSetToError)
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.CodeAnalysis"" RuleNamespace=""Microsoft.CodeAnalysis"">
<Rule Id=""CS0169"" Action=""Error"" />
</Rules>
</RuleSet>
";
var rulesetFile = CreateRuleSetFile(source);
additionalArgs = additionalArgs.Append("/ruleset:" + rulesetFile.Path).ToArray();
}
var expectedErrorCount = rulesetSetToError ? 1 : 0;
var expectedWarningCount = !rulesetSetToError ? 1 : 0;
var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false,
additionalArgs,
expectedErrorCount: expectedErrorCount,
expectedWarningCount: expectedWarningCount);
var expectedOutput = rulesetSetToError ? "error CS0169" : "warning CS0169";
Assert.Contains(expectedOutput, output);
string binaryPath = Path.Combine(dir.Path, "temp.dll");
Assert.True(File.Exists(binaryPath) == !rulesetSetToError);
string pdbPath = Path.Combine(dir.Path, pdbName);
Assert.True(File.Exists(pdbPath) == !rulesetSetToError);
string xmlDocFilePath = Path.Combine(dir.Path, docName);
Assert.True(File.Exists(xmlDocFilePath) == !rulesetSetToError);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
[WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")]
public void AnalyzerWarnAsErrorDoesNotEmit(bool warnAsError)
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText("class C { }");
var additionalArgs = warnAsError ? new[] { "/warnaserror" } : null;
var expectedErrorCount = warnAsError ? 1 : 0;
var expectedWarningCount = !warnAsError ? 1 : 0;
var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false,
additionalArgs,
expectedErrorCount: expectedErrorCount,
expectedWarningCount: expectedWarningCount,
analyzers: new[] { new WarningDiagnosticAnalyzer() });
var expectedDiagnosticSeverity = warnAsError ? "error" : "warning";
Assert.Contains($"{expectedDiagnosticSeverity} {WarningDiagnosticAnalyzer.Warning01.Id}", output);
string binaryPath = Path.Combine(dir.Path, "temp.dll");
Assert.True(File.Exists(binaryPath) == !warnAsError);
}
// Currently, configuring no location diagnostics through editorconfig is not supported.
[Theory(Skip = "https://github.com/dotnet/roslyn/issues/38042")]
[CombinatorialData]
public void AnalyzerConfigRespectedForNoLocationDiagnostic(ReportDiagnostic reportDiagnostic, bool isEnabledByDefault, bool noWarn, bool errorlog)
{
var analyzer = new AnalyzerWithNoLocationDiagnostics(isEnabledByDefault);
TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, reportDiagnostic, noWarn, errorlog);
}
[WorkItem(37876, "https://github.com/dotnet/roslyn/issues/37876")]
[Theory]
[CombinatorialData]
public void AnalyzerConfigRespectedForDisabledByDefaultDiagnostic(ReportDiagnostic analyzerConfigSeverity, bool isEnabledByDefault, bool noWarn, bool errorlog)
{
var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity: DiagnosticSeverity.Warning);
TestAnalyzerConfigRespectedCore(analyzer, analyzer.Descriptor, analyzerConfigSeverity, noWarn, errorlog);
}
private void TestAnalyzerConfigRespectedCore(DiagnosticAnalyzer analyzer, DiagnosticDescriptor descriptor, ReportDiagnostic analyzerConfigSeverity, bool noWarn, bool errorlog)
{
if (analyzerConfigSeverity == ReportDiagnostic.Default)
{
// "dotnet_diagnostic.ID.severity = default" is not supported.
return;
}
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }");
var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@"
[*.cs]
dotnet_diagnostic.{descriptor.Id}.severity = {analyzerConfigSeverity.ToAnalyzerConfigString()}");
var arguments = new[] {
"/nologo",
"/t:library",
"/preferreduilang:en",
"/analyzerconfig:" + analyzerConfig.Path,
src.Path };
if (noWarn)
{
arguments = arguments.Append($"/nowarn:{descriptor.Id}");
}
if (errorlog)
{
arguments = arguments.Append($"/errorlog:errorlog");
}
var cmd = CreateCSharpCompiler(null, dir.Path, arguments,
analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer));
Assert.Equal(analyzerConfig.Path, Assert.Single(cmd.Arguments.AnalyzerConfigPaths));
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
var expectedErrorCode = !noWarn && analyzerConfigSeverity == ReportDiagnostic.Error ? 1 : 0;
Assert.Equal(expectedErrorCode, exitCode);
// NOTE: Info diagnostics are only logged on command line when /errorlog is specified. See https://github.com/dotnet/roslyn/issues/42166 for details.
if (!noWarn &&
(analyzerConfigSeverity == ReportDiagnostic.Error ||
analyzerConfigSeverity == ReportDiagnostic.Warn ||
(analyzerConfigSeverity == ReportDiagnostic.Info && errorlog)))
{
var prefix = analyzerConfigSeverity == ReportDiagnostic.Error ? "error" : analyzerConfigSeverity == ReportDiagnostic.Warn ? "warning" : "info";
Assert.Contains($"{prefix} {descriptor.Id}: {descriptor.MessageFormat}", outWriter.ToString());
}
else
{
Assert.DoesNotContain(descriptor.Id.ToString(), outWriter.ToString());
}
}
[Fact]
[WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")]
public void IsUserConfiguredGeneratedCodeInAnalyzerConfig()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
void M(C? c)
{
_ = c.ToString(); // warning CS8602: Dereference of a possibly null reference.
}
}");
var output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable" }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false);
// warning CS8602: Dereference of a possibly null reference.
Assert.Contains("warning CS8602", output, StringComparison.Ordinal);
// generated_code = true
var analyzerConfigFile = dir.CreateFile(".editorconfig");
var analyzerConfig = analyzerConfigFile.WriteAllText(@"
[*.cs]
generated_code = true");
output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false);
Assert.DoesNotContain("warning CS8602", output, StringComparison.Ordinal);
// warning CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable' directive in source.
Assert.Contains("warning CS8669", output, StringComparison.Ordinal);
// generated_code = false
analyzerConfig = analyzerConfigFile.WriteAllText(@"
[*.cs]
generated_code = false");
output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false);
// warning CS8602: Dereference of a possibly null reference.
Assert.Contains("warning CS8602", output, StringComparison.Ordinal);
// generated_code = auto
analyzerConfig = analyzerConfigFile.WriteAllText(@"
[*.cs]
generated_code = auto");
output = VerifyOutput(dir, src, additionalFlags: new[] { "/nullable", "/analyzerconfig:" + analyzerConfig.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false);
// warning CS8602: Dereference of a possibly null reference.
Assert.Contains("warning CS8602", output, StringComparison.Ordinal);
}
[WorkItem(42166, "https://github.com/dotnet/roslyn/issues/42166")]
[CombinatorialData, Theory]
public void TestAnalyzerFilteringBasedOnSeverity(DiagnosticSeverity defaultSeverity, bool errorlog)
{
// This test verifies that analyzer execution is skipped at build time for the following:
// 1. Analyzer reporting Hidden diagnostics
// 2. Analyzer reporting Info diagnostics, when /errorlog is not specified
var analyzerShouldBeSkipped = defaultSeverity == DiagnosticSeverity.Hidden ||
defaultSeverity == DiagnosticSeverity.Info && !errorlog;
// We use an analyzer that throws an exception on every analyzer callback.
// So an AD0001 analyzer exception diagnostic is reported if analyzer executed, otherwise not.
var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: true);
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }");
var args = new[] { "/nologo", "/t:library", "/preferreduilang:en", src.Path };
if (errorlog)
args = args.Append("/errorlog:errorlog");
var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer));
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
Assert.Equal(0, exitCode);
var output = outWriter.ToString();
if (analyzerShouldBeSkipped)
{
Assert.Empty(output);
}
else
{
Assert.Contains("warning AD0001: Analyzer 'Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+NamedTypeAnalyzerWithConfigurableEnabledByDefault' threw an exception of type 'System.NotImplementedException'",
output, StringComparison.Ordinal);
}
}
[WorkItem(47017, "https://github.com/dotnet/roslyn/issues/47017")]
[CombinatorialData, Theory]
public void TestWarnAsErrorMinusDoesNotEnableDisabledByDefaultAnalyzers(DiagnosticSeverity defaultSeverity, bool isEnabledByDefault)
{
// This test verifies that '/warnaserror-:DiagnosticId' does not affect if analyzers are executed or skipped..
// Setup the analyzer to always throw an exception on analyzer callbacks for cases where we expect analyzer execution to be skipped:
// 1. Disabled by default analyzer, i.e. 'isEnabledByDefault == false'.
// 2. Default severity Hidden/Info: We only execute analyzers reporting Warning/Error severity diagnostics on command line builds.
var analyzerShouldBeSkipped = !isEnabledByDefault ||
defaultSeverity == DiagnosticSeverity.Hidden ||
defaultSeverity == DiagnosticSeverity.Info;
var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault, defaultSeverity, throwOnAllNamedTypes: analyzerShouldBeSkipped);
var diagnosticId = analyzer.Descriptor.Id;
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }");
// Verify '/warnaserror-:DiagnosticId' behavior.
var args = new[] { "/warnaserror+", $"/warnaserror-:{diagnosticId}", "/nologo", "/t:library", "/preferreduilang:en", src.Path };
var cmd = CreateCSharpCompiler(null, dir.Path, args, analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(analyzer));
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
var expectedExitCode = !analyzerShouldBeSkipped && defaultSeverity == DiagnosticSeverity.Error ? 1 : 0;
Assert.Equal(expectedExitCode, exitCode);
var output = outWriter.ToString();
if (analyzerShouldBeSkipped)
{
Assert.Empty(output);
}
else
{
var prefix = defaultSeverity == DiagnosticSeverity.Warning ? "warning" : "error";
Assert.Contains($"{prefix} {diagnosticId}: {analyzer.Descriptor.MessageFormat}", output);
}
}
[WorkItem(49446, "https://github.com/dotnet/roslyn/issues/49446")]
[Theory]
// Verify '/warnaserror-:ID' prevents escalation to 'Error' when config file bumps severity to 'Warning'
[InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Error)]
[InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Warning, DiagnosticSeverity.Warning)]
// Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and no config file setting is specified.
[InlineData(false, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Error)]
[InlineData(true, DiagnosticSeverity.Warning, null, DiagnosticSeverity.Warning)]
// Verify '/warnaserror-:ID' prevents escalation to 'Error' when default severity is 'Warning' and config file bumps severity to 'Error'
[InlineData(false, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Error)]
[InlineData(true, DiagnosticSeverity.Warning, DiagnosticSeverity.Error, DiagnosticSeverity.Warning)]
// Verify '/warnaserror-:ID' has no effect when default severity is 'Info' and config file bumps severity to 'Error'
[InlineData(false, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)]
[InlineData(true, DiagnosticSeverity.Info, DiagnosticSeverity.Error, DiagnosticSeverity.Error)]
public void TestWarnAsErrorMinusDoesNotNullifyEditorConfig(
bool warnAsErrorMinus,
DiagnosticSeverity defaultSeverity,
DiagnosticSeverity? severityInConfigFile,
DiagnosticSeverity expectedEffectiveSeverity)
{
var analyzer = new NamedTypeAnalyzerWithConfigurableEnabledByDefault(isEnabledByDefault: true, defaultSeverity, throwOnAllNamedTypes: false);
var diagnosticId = analyzer.Descriptor.Id;
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("test.cs").WriteAllText(@"class C { }");
var additionalFlags = new[] { "/warnaserror+" };
if (severityInConfigFile.HasValue)
{
var severityString = DiagnosticDescriptor.MapSeverityToReport(severityInConfigFile.Value).ToAnalyzerConfigString();
var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@"
[*.cs]
dotnet_diagnostic.{diagnosticId}.severity = {severityString}");
additionalFlags = additionalFlags.Append($"/analyzerconfig:{analyzerConfig.Path}").ToArray();
}
if (warnAsErrorMinus)
{
additionalFlags = additionalFlags.Append($"/warnaserror-:{diagnosticId}").ToArray();
}
int expectedWarningCount = 0, expectedErrorCount = 0;
switch (expectedEffectiveSeverity)
{
case DiagnosticSeverity.Warning:
expectedWarningCount = 1;
break;
case DiagnosticSeverity.Error:
expectedErrorCount = 1;
break;
default:
throw ExceptionUtilities.UnexpectedValue(expectedEffectiveSeverity);
}
VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false,
expectedWarningCount: expectedWarningCount,
expectedErrorCount: expectedErrorCount,
additionalFlags: additionalFlags,
analyzers: new[] { analyzer });
}
[Fact]
public void SourceGenerators_EmbeddedSources()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
var generatedSource = "public class D { }";
var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs");
VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null);
var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator);
ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, $"generatedSource.cs"), generatedSource } }, dir, true);
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
}
[Theory, CombinatorialData]
[WorkItem(40926, "https://github.com/dotnet/roslyn/issues/40926")]
public void TestSourceGeneratorsWithAnalyzers(bool includeCurrentAssemblyAsAnalyzerReference, bool skipAnalyzers)
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
var generatedSource = "public class D { }";
var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs");
// 'skipAnalyzers' should have no impact on source generator execution, but should prevent analyzer execution.
var skipAnalyzersFlag = "/skipAnalyzers" + (skipAnalyzers ? "+" : "-");
// Verify analyzers were executed only if both the following conditions were satisfied:
// 1. Current assembly was added as an analyzer reference, i.e. "includeCurrentAssemblyAsAnalyzerReference = true" and
// 2. We did not explicitly request skipping analyzers, i.e. "skipAnalyzers = false".
var expectedAnalyzerExecution = includeCurrentAssemblyAsAnalyzerReference && !skipAnalyzers;
// 'WarningDiagnosticAnalyzer' generates a warning for each named type.
// We expect two warnings for this test: type "C" defined in source and the source generator defined type.
// Additionally, we also have an analyzer that generates "warning CS8032: An instance of analyzer cannot be created"
// CS8032 is generated with includeCurrentAssemblyAsAnalyzerReference even when we are skipping analyzers as we will instantiate all analyzers, just not execute them.
var expectedWarningCount = expectedAnalyzerExecution ? 3 : (includeCurrentAssemblyAsAnalyzerReference ? 1 : 0);
var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference,
expectedWarningCount: expectedWarningCount,
additionalFlags: new[] { "/debug:embedded", "/out:embed.exe", skipAnalyzersFlag },
generators: new[] { generator });
// Verify source generator was executed, regardless of the value of 'skipAnalyzers'.
var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator);
ValidateEmbeddedSources_Portable(new Dictionary<string, string> { { Path.Combine(dir.Path, generatorPrefix, "generatedSource.cs"), generatedSource } }, dir, true);
if (expectedAnalyzerExecution)
{
Assert.Contains("warning Warning01", output, StringComparison.Ordinal);
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
}
else if (includeCurrentAssemblyAsAnalyzerReference)
{
Assert.Contains("warning CS8032", output, StringComparison.Ordinal);
}
else
{
Assert.Empty(output);
}
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
}
[Theory]
[InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names
[InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names
[InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names
[InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names
[InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file
public void SourceGenerators_EmbeddedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name)
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
var generator = new SingleFileTestGenerator(source1, source1Name);
var generator2 = new SingleFileTestGenerator2(source2, source2Name);
VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/debug:embedded", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null);
var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator);
var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2);
ValidateEmbeddedSources_Portable(new Dictionary<string, string>
{
{ Path.Combine(dir.Path, generator1Prefix, source1Name), source1},
{ Path.Combine(dir.Path, generator2Prefix, source2Name), source2},
}, dir, true);
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
}
[Fact]
public void SourceGenerators_WriteGeneratedSources()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
var generatedDir = dir.CreateDirectory("generated");
var generatedSource = "public class D { }";
var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs");
VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null);
var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator);
ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } });
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
}
[Fact]
public void SourceGenerators_OverwriteGeneratedSources()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
var generatedDir = dir.CreateDirectory("generated");
var generatedSource1 = "class D { } class E { }";
var generator1 = new SingleFileTestGenerator(generatedSource1, "generatedSource.cs");
VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator1 }, analyzers: null);
var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator1);
ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource1 } } } });
var generatedSource2 = "public class D { }";
var generator2 = new SingleFileTestGenerator(generatedSource2, "generatedSource.cs");
VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator2 }, analyzers: null);
ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource2 } } } });
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
}
[Theory]
[InlineData("partial class D {}", "file1.cs", "partial class E {}", "file2.cs")] // different files, different names
[InlineData("partial class D {}", "file1.cs", "partial class E {}", "file1.cs")] // different files, same names
[InlineData("partial class D {}", "file1.cs", "partial class D {}", "file2.cs")] // same files, different names
[InlineData("partial class D {}", "file1.cs", "partial class D {}", "file1.cs")] // same files, same names
[InlineData("partial class D {}", "file1.cs", "", "file2.cs")] // empty second file
public void SourceGenerators_WriteGeneratedSources_MultipleFiles(string source1, string source1Name, string source2, string source2Name)
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
var generatedDir = dir.CreateDirectory("generated");
var generator = new SingleFileTestGenerator(source1, source1Name);
var generator2 = new SingleFileTestGenerator2(source2, source2Name);
VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator, generator2 }, analyzers: null);
var generator1Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator);
var generator2Prefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator2);
ValidateWrittenSources(new()
{
{ Path.Combine(generatedDir.Path, generator1Prefix), new() { { source1Name, source1 } } },
{ Path.Combine(generatedDir.Path, generator2Prefix), new() { { source2Name, source2 } } }
});
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
}
[ConditionalFact(typeof(DesktopClrOnly))] //CoreCLR doesn't support SxS loading
[WorkItem(47990, "https://github.com/dotnet/roslyn/issues/47990")]
public void SourceGenerators_SxS_AssemblyLoading()
{
// compile the generators
var dir = Temp.CreateDirectory();
var snk = Temp.CreateFile("TestKeyPair_", ".snk", dir.Path).WriteAllBytes(TestResources.General.snKey);
var src = dir.CreateFile("generator.cs");
var virtualSnProvider = new DesktopStrongNameProvider(ImmutableArray.Create(dir.Path));
string createGenerator(string version)
{
var generatorSource = $@"
using Microsoft.CodeAnalysis;
[assembly:System.Reflection.AssemblyVersion(""{version}"")]
[Generator]
public class TestGenerator : ISourceGenerator
{{
public void Execute(GeneratorExecutionContext context) {{ context.AddSource(""generatedSource.cs"", ""//from version {version}""); }}
public void Initialize(GeneratorInitializationContext context) {{ }}
}}";
var path = Path.Combine(dir.Path, Guid.NewGuid().ToString() + ".dll");
var comp = CreateEmptyCompilation(source: generatorSource,
references: TargetFrameworkUtil.NetStandard20References.Add(MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly)),
options: TestOptions.DebugDll.WithCryptoKeyFile(Path.GetFileName(snk.Path)).WithStrongNameProvider(virtualSnProvider),
assemblyName: "generator");
comp.VerifyDiagnostics();
comp.Emit(path);
return path;
}
var gen1 = createGenerator("1.0.0.0");
var gen2 = createGenerator("2.0.0.0");
var generatedDir = dir.CreateDirectory("generated");
VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/analyzer:" + gen1, "/analyzer:" + gen2 }.ToArray());
// This is wrong! Both generators are writing the same file out, over the top of each other
// See https://github.com/dotnet/roslyn/issues/47990
ValidateWrittenSources(new()
{
// { Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 1.0.0.0" } } },
{ Path.Combine(generatedDir.Path, "generator", "TestGenerator"), new() { { "generatedSource.cs", "//from version 2.0.0.0" } } }
});
}
[Fact]
public void SourceGenerators_DoNotWriteGeneratedSources_When_No_Directory_Supplied()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
var generatedDir = dir.CreateDirectory("generated");
var generatedSource = "public class D { }";
var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs");
VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null);
ValidateWrittenSources(new() { { generatedDir.Path, new() } });
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
}
[Fact]
public void SourceGenerators_Error_When_GeneratedDir_NotExist()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
var generatedDirPath = Path.Combine(dir.Path, "noexist");
var generatedSource = "public class D { }";
var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs");
var output = VerifyOutput(dir, src, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDirPath, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null);
Assert.Contains("CS0016:", output);
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
}
[Fact]
public void SourceGenerators_GeneratedDir_Has_Spaces()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
var generatedDir = dir.CreateDirectory("generated files");
var generatedSource = "public class D { }";
var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs");
VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null);
var generatorPrefix = GeneratorDriver.GetFilePathPrefixForGenerator(generator);
ValidateWrittenSources(new() { { Path.Combine(generatedDir.Path, generatorPrefix), new() { { "generatedSource.cs", generatedSource } } } });
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
}
[Fact]
public void ParseGeneratedFilesOut()
{
string root = PathUtilities.IsUnixLikePlatform ? "/" : "c:\\";
string baseDirectory = Path.Combine(root, "abc", "def");
var parsedArgs = DefaultParse(new[] { @"/generatedfilesout:", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:"));
Assert.Null(parsedArgs.GeneratedFilesOutputDirectory);
parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""""", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify(
// error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option
Diagnostic(ErrorCode.ERR_SwitchNeedsString).WithArguments("<text>", "/generatedfilesout:\"\""));
Assert.Null(parsedArgs.GeneratedFilesOutputDirectory);
parsedArgs = DefaultParse(new[] { @"/generatedfilesout:outdir", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory);
parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""outdir""", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Path.Combine(baseDirectory, "outdir"), parsedArgs.GeneratedFilesOutputDirectory);
parsedArgs = DefaultParse(new[] { @"/generatedfilesout:out dir", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory);
parsedArgs = DefaultParse(new[] { @"/generatedfilesout:""out dir""", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(Path.Combine(baseDirectory, "out dir"), parsedArgs.GeneratedFilesOutputDirectory);
var absPath = Path.Combine(root, "outdir");
parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory);
parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory);
absPath = Path.Combine(root, "generated files");
parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:{absPath}", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory);
parsedArgs = DefaultParse(new[] { $@"/generatedfilesout:""{absPath}""", "a.cs" }, baseDirectory);
parsedArgs.Errors.Verify();
Assert.Equal(absPath, parsedArgs.GeneratedFilesOutputDirectory);
}
[Fact]
public void SourceGenerators_Error_When_NoDirectoryArgumentGiven()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
var output = VerifyOutput(dir, src, expectedErrorCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:", "/langversion:preview", "/out:embed.exe" });
Assert.Contains("error CS2006: Command-line syntax error: Missing '<text>' for '/generatedfilesout:' option", output);
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
}
[Fact]
public void SourceGenerators_ReportedWrittenFiles_To_TouchedFilesLogger()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
var generatedDir = dir.CreateDirectory("generated");
var generatedSource = "public class D { }";
var generator = new SingleFileTestGenerator(generatedSource, "generatedSource.cs");
VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/generatedfilesout:" + generatedDir.Path, $"/touchedfiles:{dir.Path}/touched", "/langversion:preview", "/out:embed.exe" }, generators: new[] { generator }, analyzers: null);
var touchedFiles = Directory.GetFiles(dir.Path, "touched*");
Assert.Equal(2, touchedFiles.Length);
string[] writtenText = File.ReadAllLines(Path.Combine(dir.Path, "touched.write"));
Assert.Equal(2, writtenText.Length);
Assert.EndsWith("EMBED.EXE", writtenText[0], StringComparison.OrdinalIgnoreCase);
Assert.EndsWith("GENERATEDSOURCE.CS", writtenText[1], StringComparison.OrdinalIgnoreCase);
// Clean up temp files
CleanupAllGeneratedFiles(src.Path);
Directory.Delete(dir.Path, true);
}
[Fact]
[WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44087")]
public void SourceGeneratorsAndAnalyzerConfig()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@"
[*.cs]
key = value");
var generator = new SingleFileTestGenerator("public class D {}", "generated.cs");
VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path }, generators: new[] { generator }, analyzers: null);
}
[Fact]
public void SourceGeneratorsCanReadAnalyzerConfig()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
var analyzerConfig1 = dir.CreateFile(".globaleditorconfig").WriteAllText(@"
is_global = true
key1 = value1
[*.cs]
key2 = value2
[*.vb]
key3 = value3");
var analyzerConfig2 = dir.CreateFile(".editorconfig").WriteAllText(@"
[*.cs]
key4 = value4
[*.vb]
key5 = value5");
var subDir = dir.CreateDirectory("subDir");
var analyzerConfig3 = subDir.CreateFile(".editorconfig").WriteAllText(@"
[*.cs]
key6 = value6
[*.vb]
key7 = value7");
var generator = new CallbackGenerator((ic) => { }, (gc) =>
{
// can get the global options
var globalOptions = gc.AnalyzerConfigOptions.GlobalOptions;
Assert.True(globalOptions.TryGetValue("key1", out var keyValue));
Assert.Equal("value1", keyValue);
Assert.False(globalOptions.TryGetValue("key2", out _));
Assert.False(globalOptions.TryGetValue("key3", out _));
Assert.False(globalOptions.TryGetValue("key4", out _));
Assert.False(globalOptions.TryGetValue("key5", out _));
Assert.False(globalOptions.TryGetValue("key6", out _));
Assert.False(globalOptions.TryGetValue("key7", out _));
// can get the options for class C
var classOptions = gc.AnalyzerConfigOptions.GetOptions(gc.Compilation.SyntaxTrees.First());
Assert.True(classOptions.TryGetValue("key1", out keyValue));
Assert.Equal("value1", keyValue);
Assert.False(classOptions.TryGetValue("key2", out _));
Assert.False(classOptions.TryGetValue("key3", out _));
Assert.True(classOptions.TryGetValue("key4", out keyValue));
Assert.Equal("value4", keyValue);
Assert.False(classOptions.TryGetValue("key5", out _));
Assert.False(classOptions.TryGetValue("key6", out _));
Assert.False(classOptions.TryGetValue("key7", out _));
});
var args = new[] {
"/analyzerconfig:" + analyzerConfig1.Path,
"/analyzerconfig:" + analyzerConfig2.Path,
"/analyzerconfig:" + analyzerConfig3.Path,
"/t:library",
src.Path
};
var cmd = CreateCSharpCompiler(null, dir.Path, args, generators: ImmutableArray.Create<ISourceGenerator>(generator));
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
Assert.Equal(0, exitCode);
// test for both the original tree and the generated one
var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider;
// get the global options
var globalOptions = provider.GlobalOptions;
Assert.True(globalOptions.TryGetValue("key1", out var keyValue));
Assert.Equal("value1", keyValue);
Assert.False(globalOptions.TryGetValue("key2", out _));
Assert.False(globalOptions.TryGetValue("key3", out _));
Assert.False(globalOptions.TryGetValue("key4", out _));
Assert.False(globalOptions.TryGetValue("key5", out _));
Assert.False(globalOptions.TryGetValue("key6", out _));
Assert.False(globalOptions.TryGetValue("key7", out _));
// get the options for class C
var classOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.First());
Assert.True(classOptions.TryGetValue("key1", out keyValue));
Assert.Equal("value1", keyValue);
Assert.False(classOptions.TryGetValue("key2", out _));
Assert.False(classOptions.TryGetValue("key3", out _));
Assert.True(classOptions.TryGetValue("key4", out keyValue));
Assert.Equal("value4", keyValue);
Assert.False(classOptions.TryGetValue("key5", out _));
Assert.False(classOptions.TryGetValue("key6", out _));
Assert.False(classOptions.TryGetValue("key7", out _));
// get the options for generated class D
var generatedOptions = provider.GetOptions(cmd.Compilation.SyntaxTrees.Last());
Assert.True(generatedOptions.TryGetValue("key1", out keyValue));
Assert.Equal("value1", keyValue);
Assert.False(generatedOptions.TryGetValue("key2", out _));
Assert.False(generatedOptions.TryGetValue("key3", out _));
Assert.True(classOptions.TryGetValue("key4", out keyValue));
Assert.Equal("value4", keyValue);
Assert.False(generatedOptions.TryGetValue("key5", out _));
Assert.False(generatedOptions.TryGetValue("key6", out _));
Assert.False(generatedOptions.TryGetValue("key7", out _));
}
[Theory]
[CombinatorialData]
public void SourceGeneratorsRunRegardlessOfLanguageVersion(LanguageVersion version)
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"class C {}");
var generator = new CallbackGenerator(i => { }, e => throw null);
var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/langversion:" + version.ToDisplayString() }, generators: new[] { generator }, expectedWarningCount: 1, expectedErrorCount: 1, expectedExitCode: 0);
Assert.Contains("CS8785: Generator 'CallbackGenerator' failed to generate source.", output);
}
[DiagnosticAnalyzer(LanguageNames.CSharp)]
private sealed class FieldAnalyzer : DiagnosticAnalyzer
{
private static readonly DiagnosticDescriptor _rule = new DiagnosticDescriptor("Id", "Title", "Message", "Category", DiagnosticSeverity.Warning, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(_rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeFieldDeclaration, SyntaxKind.FieldDeclaration);
}
private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context)
{
}
}
[Fact]
[WorkItem(44000, "https://github.com/dotnet/roslyn/issues/44000")]
public void TupleField_ForceComplete()
{
var source =
@"namespace System
{
public struct ValueTuple<T1>
{
public T1 Item1;
public ValueTuple(T1 item1)
{
Item1 = item1;
}
}
}";
var srcFile = Temp.CreateFile().WriteAllText(source);
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var csc = CreateCSharpCompiler(
null,
WorkingDirectory,
new[] { "/nologo", "/t:library", srcFile.Path },
analyzers: ImmutableArray.Create<DiagnosticAnalyzer>(new FieldAnalyzer())); // at least one analyzer required
var exitCode = csc.Run(outWriter);
Assert.Equal(0, exitCode);
var output = outWriter.ToString();
Assert.Empty(output);
CleanupAllGeneratedFiles(srcFile.Path);
}
[Fact]
public void GlobalAnalyzerConfigsAllowedInSameDir()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("test.cs").WriteAllText(@"
class C
{
int _f;
}");
var configText = @"
is_global = true
";
var analyzerConfig1 = dir.CreateFile("analyzerconfig1").WriteAllText(configText);
var analyzerConfig2 = dir.CreateFile("analyzerconfig2").WriteAllText(configText);
var cmd = CreateCSharpCompiler(null, dir.Path, new[] {
"/nologo",
"/t:library",
"/preferreduilang:en",
"/analyzerconfig:" + analyzerConfig1.Path,
"/analyzerconfig:" + analyzerConfig2.Path,
src.Path
});
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
Assert.Equal(0, exitCode);
}
[Fact]
public void GlobalAnalyzerConfigMultipleSetKeys()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
}");
var analyzerConfigFile = dir.CreateFile(".globalconfig");
var analyzerConfig = analyzerConfigFile.WriteAllText(@"
is_global = true
global_level = 100
option1 = abc");
var analyzerConfigFile2 = dir.CreateFile(".globalconfig2");
var analyzerConfig2 = analyzerConfigFile2.WriteAllText(@"
is_global = true
global_level = 100
option1 = def");
var output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false);
// warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'Global Section'. It has been unset. Key was set by the following files: ...
Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal);
Assert.Contains("'option1'", output, StringComparison.Ordinal);
Assert.Contains("'Global Section'", output, StringComparison.Ordinal);
analyzerConfig = analyzerConfigFile.WriteAllText(@"
is_global = true
global_level = 100
[/file.cs]
option1 = abc");
analyzerConfig2 = analyzerConfigFile2.WriteAllText(@"
is_global = true
global_level = 100
[/file.cs]
option1 = def");
output = VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + analyzerConfig.Path + "," + analyzerConfig2.Path }, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false);
// warning MultipleGlobalAnalyzerKeys: Multiple global analyzer config files set the same key 'option1' in section 'file.cs'. It has been unset. Key was set by the following files: ...
Assert.Contains("MultipleGlobalAnalyzerKeys:", output, StringComparison.Ordinal);
Assert.Contains("'option1'", output, StringComparison.Ordinal);
Assert.Contains("'/file.cs'", output, StringComparison.Ordinal);
}
[Fact]
public void GlobalAnalyzerConfigWithOptions()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("test.cs").WriteAllText(@"
class C
{
}");
var additionalFile = dir.CreateFile("file.txt");
var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@"
[*.cs]
key1 = value1
[*.txt]
key2 = value2");
var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@"
is_global = true
key3 = value3");
var cmd = CreateCSharpCompiler(null, dir.Path, new[] {
"/nologo",
"/t:library",
"/analyzerconfig:" + analyzerConfig.Path,
"/analyzerconfig:" + globalConfig.Path,
"/analyzer:" + Assembly.GetExecutingAssembly().Location,
"/nowarn:8032,Warning01",
"/additionalfile:" + additionalFile.Path,
src.Path });
var outWriter = new StringWriter(CultureInfo.InvariantCulture);
var exitCode = cmd.Run(outWriter);
Assert.Equal("", outWriter.ToString());
Assert.Equal(0, exitCode);
var comp = cmd.Compilation;
var tree = comp.SyntaxTrees.Single();
var provider = cmd.AnalyzerOptions.AnalyzerConfigOptionsProvider;
var options = provider.GetOptions(tree);
Assert.NotNull(options);
Assert.True(options.TryGetValue("key1", out string val));
Assert.Equal("value1", val);
Assert.False(options.TryGetValue("key2", out _));
Assert.True(options.TryGetValue("key3", out val));
Assert.Equal("value3", val);
options = provider.GetOptions(cmd.AnalyzerOptions.AdditionalFiles.Single());
Assert.NotNull(options);
Assert.False(options.TryGetValue("key1", out _));
Assert.True(options.TryGetValue("key2", out val));
Assert.Equal("value2", val);
Assert.True(options.TryGetValue("key3", out val));
Assert.Equal("value3", val);
options = provider.GlobalOptions;
Assert.NotNull(options);
Assert.False(options.TryGetValue("key1", out _));
Assert.False(options.TryGetValue("key2", out _));
Assert.True(options.TryGetValue("key3", out val));
Assert.Equal("value3", val);
}
[Fact]
[WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")]
public void GlobalAnalyzerConfigDiagnosticOptionsCanBeOverridenByCommandLine()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
void M()
{
label1:;
}
}");
var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@"
is_global = true
dotnet_diagnostic.CS0164.severity = error;
");
var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText(@"
[*.cs]
dotnet_diagnostic.CS0164.severity = warning;
");
var none = Array.Empty<TempFile>();
var globalOnly = new[] { globalConfig };
var globalAndSpecific = new[] { globalConfig, analyzerConfig };
// by default a warning, which can be suppressed via cmdline
verify(configs: none, expectedWarnings: 1);
verify(configs: none, noWarn: "CS0164", expectedWarnings: 0);
// the global analyzer config ups the warning to an error, but the cmdline setting overrides it
verify(configs: globalOnly, expectedErrors: 1);
verify(configs: globalOnly, noWarn: "CS0164", expectedWarnings: 0);
verify(configs: globalOnly, noWarn: "164", expectedWarnings: 0); // cmdline can be shortened, but still works
// the editor config downgrades the error back to warning, but the cmdline setting overrides it
verify(configs: globalAndSpecific, expectedWarnings: 1);
verify(configs: globalAndSpecific, noWarn: "CS0164", expectedWarnings: 0);
void verify(TempFile[] configs, int expectedWarnings = 0, int expectedErrors = 0, string noWarn = "0")
=> VerifyOutput(dir, src,
expectedErrorCount: expectedErrors,
expectedWarningCount: expectedWarnings,
includeCurrentAssemblyAsAnalyzerReference: false,
analyzers: null,
additionalFlags: configs.SelectAsArray(c => "/analyzerconfig:" + c.Path)
.Add("/noWarn:" + noWarn).ToArray());
}
[Fact]
[WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")]
public void GlobalAnalyzerConfigSpecificDiagnosticOptionsOverrideGeneralCommandLineOptions()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
void M()
{
label1:;
}
}");
var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@"
is_global = true
dotnet_diagnostic.CS0164.severity = none;
");
VerifyOutput(dir, src, additionalFlags: new[] { "/warnaserror+", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false);
}
[Theory, CombinatorialData]
[WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")]
public void WarnAsErrorIsRespectedForForWarningsConfiguredInRulesetOrGlobalConfig(bool useGlobalConfig)
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
void M()
{
label1:;
}
}");
var additionalFlags = new[] { "/warnaserror+" };
if (useGlobalConfig)
{
var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@"
is_global = true
dotnet_diagnostic.CS0164.severity = warning;
");
additionalFlags = additionalFlags.Append("/analyzerconfig:" + globalConfig.Path).ToArray();
}
else
{
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""15.0"">
<Rules AnalyzerId=""Compiler"" RuleNamespace=""Compiler"">
<Rule Id=""CS0164"" Action=""Warning"" />
</Rules>
</RuleSet>
";
_ = dir.CreateFile("Rules.ruleset").WriteAllText(ruleSetSource);
additionalFlags = additionalFlags.Append("/ruleset:Rules.ruleset").ToArray();
}
VerifyOutput(dir, src, additionalFlags: additionalFlags, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false);
}
[Fact]
[WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")]
public void GlobalAnalyzerConfigSectionsDoNotOverrideCommandLine()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(@"
class C
{
void M()
{
label1:;
}
}");
var globalConfig = dir.CreateFile(".globalconfig").WriteAllText($@"
is_global = true
[{PathUtilities.NormalizeWithForwardSlash(src.Path)}]
dotnet_diagnostic.CS0164.severity = error;
");
VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:0164", "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 0, includeCurrentAssemblyAsAnalyzerReference: false);
}
[Fact]
[WorkItem(44087, "https://github.com/dotnet/roslyn/issues/44804")]
public void GlobalAnalyzerConfigCanSetDiagnosticWithNoLocation()
{
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("test.cs").WriteAllText(@"
class C
{
}");
var globalConfig = dir.CreateFile(".globalconfig").WriteAllText(@"
is_global = true
dotnet_diagnostic.Warning01.severity = error;
");
VerifyOutput(dir, src, additionalFlags: new[] { "/analyzerconfig:" + globalConfig.Path }, expectedErrorCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer());
VerifyOutput(dir, src, additionalFlags: new[] { "/nowarn:Warning01", "/analyzerconfig:" + globalConfig.Path }, includeCurrentAssemblyAsAnalyzerReference: false, analyzers: new WarningDiagnosticAnalyzer());
}
[Theory, CombinatorialData]
public void TestAdditionalFileAnalyzer(bool registerFromInitialize)
{
var srcDirectory = Temp.CreateDirectory();
var source = "class C { }";
var srcFile = srcDirectory.CreateFile("a.cs");
srcFile.WriteAllText(source);
var additionalText = "Additional Text";
var additionalFile = srcDirectory.CreateFile("b.txt");
additionalFile.WriteAllText(additionalText);
var diagnosticSpan = new TextSpan(2, 2);
var analyzer = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan);
var output = VerifyOutput(srcDirectory, srcFile, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false,
additionalFlags: new[] { "/additionalfile:" + additionalFile.Path },
analyzers: analyzer);
Assert.Contains("b.txt(1,3): warning ID0001", output, StringComparison.Ordinal);
CleanupAllGeneratedFiles(srcDirectory.Path);
}
[Theory]
// "/warnaserror" tests
[InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)]
[InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)]
[InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)]
// "/warnaserror:CS0169" tests
[InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)]
[InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)]
[InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:CS0169", /*expectError*/true, /*expectWarning*/false)]
// "/nowarn" tests
[InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)]
[InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)]
[InlineData(/*analyzerConfigSeverity*/null, "/nowarn:CS0169", /*expectError*/false, /*expectWarning*/false)]
// Neither "/nowarn" nor "/warnaserror" tests
[InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)]
[InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)]
[InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)]
[WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")]
public void TestCompilationOptionsOverrideAnalyzerConfig_CompilerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning)
{
var src = @"
class C
{
int _f; // CS0169: unused field
}";
TestCompilationOptionsOverrideAnalyzerConfigCore(src, diagnosticId: "CS0169", analyzerConfigSeverity, additionalArg, expectError, expectWarning);
}
[Theory]
// "/warnaserror" tests
[InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror", /*expectError*/true, /*expectWarning*/false)]
[InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror", /*expectError*/true, /*expectWarning*/false)]
[InlineData(/*analyzerConfigSeverity*/null, "/warnaserror", /*expectError*/true, /*expectWarning*/false)]
// "/warnaserror:DiagnosticId" tests
[InlineData(/*analyzerConfigSeverity*/"warning", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)]
[InlineData(/*analyzerConfigSeverity*/"error", "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)]
[InlineData(/*analyzerConfigSeverity*/null, "/warnaserror:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/true, /*expectWarning*/false)]
// "/nowarn" tests
[InlineData(/*analyzerConfigSeverity*/"warning", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)]
[InlineData(/*analyzerConfigSeverity*/"error", "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)]
[InlineData(/*analyzerConfigSeverity*/null, "/nowarn:" + CompilationAnalyzerWithSeverity.DiagnosticId, /*expectError*/false, /*expectWarning*/false)]
// Neither "/nowarn" nor "/warnaserror" tests
[InlineData(/*analyzerConfigSeverity*/"warning", /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)]
[InlineData(/*analyzerConfigSeverity*/"error", /*additionalArg*/null, /*expectError*/true, /*expectWarning*/false)]
[InlineData(/*analyzerConfigSeverity*/null, /*additionalArg*/null, /*expectError*/false, /*expectWarning*/true)]
[WorkItem(43051, "https://github.com/dotnet/roslyn/issues/43051")]
public void TestCompilationOptionsOverrideAnalyzerConfig_AnalyzerWarning(string analyzerConfigSeverity, string additionalArg, bool expectError, bool expectWarning)
{
var analyzer = new CompilationAnalyzerWithSeverity(DiagnosticSeverity.Warning, configurable: true);
var src = @"class C { }";
TestCompilationOptionsOverrideAnalyzerConfigCore(src, CompilationAnalyzerWithSeverity.DiagnosticId, analyzerConfigSeverity, additionalArg, expectError, expectWarning, analyzer);
}
private void TestCompilationOptionsOverrideAnalyzerConfigCore(
string source,
string diagnosticId,
string analyzerConfigSeverity,
string additionalArg,
bool expectError,
bool expectWarning,
params DiagnosticAnalyzer[] analyzers)
{
Assert.True(!expectError || !expectWarning);
var dir = Temp.CreateDirectory();
var src = dir.CreateFile("temp.cs").WriteAllText(source);
var additionalArgs = Array.Empty<string>();
if (analyzerConfigSeverity != null)
{
var analyzerConfig = dir.CreateFile(".editorconfig").WriteAllText($@"
[*.cs]
dotnet_diagnostic.{diagnosticId}.severity = {analyzerConfigSeverity}");
additionalArgs = additionalArgs.Append("/analyzerconfig:" + analyzerConfig.Path).ToArray();
}
if (!string.IsNullOrEmpty(additionalArg))
{
additionalArgs = additionalArgs.Append(additionalArg);
}
var output = VerifyOutput(dir, src, includeCurrentAssemblyAsAnalyzerReference: false,
additionalArgs,
expectedErrorCount: expectError ? 1 : 0,
expectedWarningCount: expectWarning ? 1 : 0,
analyzers: analyzers);
if (expectError)
{
Assert.Contains($"error {diagnosticId}", output);
}
else if (expectWarning)
{
Assert.Contains($"warning {diagnosticId}", output);
}
else
{
Assert.DoesNotContain(diagnosticId, output);
}
}
[ConditionalFact(typeof(CoreClrOnly), Reason = "Can't load a coreclr targeting generator on net framework / mono")]
public void TestGeneratorsCantTargetNetFramework()
{
var directory = Temp.CreateDirectory();
var src = directory.CreateFile("test.cs").WriteAllText(@"
class C
{
}");
// core
var coreGenerator = emitGenerator(".NETCoreApp,Version=v5.0");
VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + coreGenerator });
// netstandard
var nsGenerator = emitGenerator(".NETStandard,Version=v2.0");
VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + nsGenerator });
// no target
var ntGenerator = emitGenerator(targetFramework: null);
VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + ntGenerator });
// framework
var frameworkGenerator = emitGenerator(".NETFramework,Version=v4.7.2");
var output = VerifyOutput(directory, src, expectedWarningCount: 2, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/analyzer:" + frameworkGenerator });
Assert.Contains("CS8850", output); // ref's net fx
Assert.Contains("CS8033", output); // no analyzers in assembly
// framework, suppressed
output = VerifyOutput(directory, src, expectedWarningCount: 1, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850", "/analyzer:" + frameworkGenerator });
Assert.Contains("CS8033", output);
VerifyOutput(directory, src, includeCurrentAssemblyAsAnalyzerReference: false, additionalFlags: new[] { "/nowarn:CS8850,CS8033", "/analyzer:" + frameworkGenerator });
string emitGenerator(string targetFramework)
{
string targetFrameworkAttributeText = targetFramework is object
? $"[assembly: System.Runtime.Versioning.TargetFramework(\"{targetFramework}\")]"
: string.Empty;
string generatorSource = $@"
using Microsoft.CodeAnalysis;
{targetFrameworkAttributeText}
[Generator]
public class Generator : ISourceGenerator
{{
public void Execute(GeneratorExecutionContext context) {{ }}
public void Initialize(GeneratorInitializationContext context) {{ }}
}}";
var directory = Temp.CreateDirectory();
var generatorPath = Path.Combine(directory.Path, "generator.dll");
var compilation = CSharpCompilation.Create($"generator",
new[] { CSharpSyntaxTree.ParseText(generatorSource) },
TargetFrameworkUtil.GetReferences(TargetFramework.Standard, new[] { MetadataReference.CreateFromAssemblyInternal(typeof(ISourceGenerator).Assembly) }),
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
compilation.VerifyDiagnostics();
var result = compilation.Emit(generatorPath);
Assert.True(result.Success);
return generatorPath;
}
}
[Theory]
[InlineData("a.txt", "b.txt", 2)]
[InlineData("a.txt", "a.txt", 1)]
[InlineData("abc/a.txt", "def/a.txt", 2)]
[InlineData("abc/a.txt", "abc/a.txt", 1)]
[InlineData("abc/a.txt", "abc/../a.txt", 2)]
[InlineData("abc/a.txt", "abc/./a.txt", 1)]
[InlineData("abc/a.txt", "abc/../abc/a.txt", 1)]
[InlineData("abc/a.txt", "abc/.././abc/a.txt", 1)]
[InlineData("abc/a.txt", "./abc/a.txt", 1)]
[InlineData("abc/a.txt", "../abc/../abc/a.txt", 2)]
[InlineData("abc/a.txt", "./abc/../abc/a.txt", 1)]
[InlineData("../abc/a.txt", "../abc/../abc/a.txt", 1)]
[InlineData("../abc/a.txt", "../abc/a.txt", 1)]
[InlineData("./abc/a.txt", "abc/a.txt", 1)]
public void TestDuplicateAdditionalFiles(string additionalFilePath1, string additionalFilePath2, int expectedCount)
{
var srcDirectory = Temp.CreateDirectory();
var srcFile = srcDirectory.CreateFile("a.cs").WriteAllText("class C { }");
// make sure any parent or sub dirs exist too
Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(srcDirectory.Path, additionalFilePath1)));
Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(srcDirectory.Path, additionalFilePath2)));
var additionalFile1 = srcDirectory.CreateFile(additionalFilePath1);
var additionalFile2 = expectedCount == 2 ? srcDirectory.CreateFile(additionalFilePath2) : null;
string path1 = additionalFile1.Path;
string path2 = additionalFile2?.Path ?? Path.Combine(srcDirectory.Path, additionalFilePath2);
int count = 0;
var generator = new PipelineCallbackGenerator(ctx =>
{
ctx.RegisterSourceOutput(ctx.AdditionalTextsProvider, (spc, t) =>
{
count++;
});
});
var output = VerifyOutput(srcDirectory, srcFile, includeCurrentAssemblyAsAnalyzerReference: false,
additionalFlags: new[] { "/additionalfile:" + path1, "/additionalfile:" + path2 },
generators: new[] { generator.AsSourceGenerator() });
Assert.Equal(expectedCount, count);
CleanupAllGeneratedFiles(srcDirectory.Path);
}
[ConditionalTheory(typeof(WindowsOnly))]
[InlineData("abc/a.txt", "abc\\a.txt", 1)]
[InlineData("abc\\a.txt", "abc\\a.txt", 1)]
[InlineData("abc/a.txt", "abc\\..\\a.txt", 2)]
[InlineData("abc/a.txt", "abc\\..\\abc\\a.txt", 1)]
[InlineData("abc/a.txt", "../abc\\../abc\\a.txt", 2)]
[InlineData("abc/a.txt", "./abc\\../abc\\a.txt", 1)]
[InlineData("../abc/a.txt", "../abc\\../abc\\a.txt", 1)]
[InlineData("a.txt", "A.txt", 1)]
[InlineData("abc/a.txt", "ABC\\a.txt", 1)]
[InlineData("abc/a.txt", "ABC\\A.txt", 1)]
public void TestDuplicateAdditionalFiles_Windows(string additionalFilePath1, string additionalFilePath2, int expectedCount) => TestDuplicateAdditionalFiles(additionalFilePath1, additionalFilePath2, expectedCount);
[ConditionalTheory(typeof(LinuxOnly))]
[InlineData("a.txt", "A.txt", 2)]
[InlineData("abc/a.txt", "abc/A.txt", 2)]
[InlineData("abc/a.txt", "ABC/a.txt", 2)]
[InlineData("abc/a.txt", "./../abc/A.txt", 2)]
[InlineData("abc/a.txt", "./../ABC/a.txt", 2)]
public void TestDuplicateAdditionalFiles_Linux(string additionalFilePath1, string additionalFilePath2, int expectedCount) => TestDuplicateAdditionalFiles(additionalFilePath1, additionalFilePath2, expectedCount);
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
internal abstract class CompilationStartedAnalyzer : DiagnosticAnalyzer
{
public abstract override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; }
public abstract void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context);
public override void Initialize(AnalysisContext context)
{
context.RegisterCompilationStartAction(CreateAnalyzerWithinCompilation);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
internal class HiddenDiagnosticAnalyzer : CompilationStartedAnalyzer
{
internal static readonly DiagnosticDescriptor Hidden01 = new DiagnosticDescriptor("Hidden01", "", "Throwing a diagnostic for #region", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor Hidden02 = new DiagnosticDescriptor("Hidden02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Hidden, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Hidden01, Hidden02);
}
}
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
context.ReportDiagnostic(Diagnostic.Create(Hidden01, context.Node.GetLocation()));
}
public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.RegionDirectiveTrivia);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
internal class InfoDiagnosticAnalyzer : CompilationStartedAnalyzer
{
internal static readonly DiagnosticDescriptor Info01 = new DiagnosticDescriptor("Info01", "", "Throwing a diagnostic for #pragma restore", "", DiagnosticSeverity.Info, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Info01);
}
}
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
if ((context.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.RestoreKeyword))
{
context.ReportDiagnostic(Diagnostic.Create(Info01, context.Node.GetLocation()));
}
}
public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.PragmaWarningDirectiveTrivia);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
internal class WarningDiagnosticAnalyzer : CompilationStartedAnalyzer
{
internal static readonly DiagnosticDescriptor Warning01 = new DiagnosticDescriptor("Warning01", "", "Throwing a diagnostic for types declared", "", DiagnosticSeverity.Warning, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Warning01);
}
}
public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context)
{
context.RegisterSymbolAction(
(symbolContext) =>
{
symbolContext.ReportDiagnostic(Diagnostic.Create(Warning01, symbolContext.Symbol.Locations.First()));
},
SymbolKind.NamedType);
}
}
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
internal class ErrorDiagnosticAnalyzer : CompilationStartedAnalyzer
{
internal static readonly DiagnosticDescriptor Error01 = new DiagnosticDescriptor("Error01", "", "Throwing a diagnostic for #pragma disable", "", DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor Error02 = new DiagnosticDescriptor("Error02", "", "Throwing a diagnostic for something else", "", DiagnosticSeverity.Error, isEnabledByDefault: true);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Error01, Error02);
}
}
public override void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext context)
{
context.RegisterSyntaxNodeAction(
(nodeContext) =>
{
if ((nodeContext.Node as PragmaWarningDirectiveTriviaSyntax).DisableOrRestoreKeyword.IsKind(SyntaxKind.DisableKeyword))
{
nodeContext.ReportDiagnostic(Diagnostic.Create(Error01, nodeContext.Node.GetLocation()));
}
},
SyntaxKind.PragmaWarningDirectiveTrivia
);
}
}
}
|
namespace GarboDev
{
using System;
using System.Collections.Generic;
using System.Text;
public partial class Renderer : IRenderer
{
private Memory memory;
private uint[] scanline = new uint[240];
private byte[] blend = new byte[240];
private byte[] windowCover = new byte[240];
private uint[] back = new uint[240 * 160];
//private uint[] front = new uint[240 * 160];
private const uint pitch = 240;
// Convenience variable as I use it everywhere, set once in RenderLine
private ushort dispCnt;
// Window helper variables
private byte win0x1, win0x2, win0y1, win0y2;
private byte win1x1, win1x2, win1y1, win1y2;
private byte win0Enabled, win1Enabled, winObjEnabled, winOutEnabled;
private bool winEnabled;
private byte blendSource, blendTarget;
private byte blendA, blendB, blendY;
private int blendType;
private int curLine = 0;
private static uint[] colorLUT;
static Renderer()
{
colorLUT = new uint[0x10000];
// Pre-calculate the color LUT
for (uint i = 0; i <= 0xFFFF; i++)
{
uint r = (i & 0x1FU);
uint g = (i & 0x3E0U) >> 5;
uint b = (i & 0x7C00U) >> 10;
r = (r << 3) | (r >> 2);
g = (g << 3) | (g >> 2);
b = (b << 3) | (b >> 2);
colorLUT[i] = (r << 16) | (g << 8) | b;
}
}
public Memory Memory
{
set { this.memory = value; }
}
public void Initialize(object data)
{
}
public void Reset()
{
}
public uint[] ShowFrame()
{
//Array.Copy(this.back, this.front, this.front.Length);
//return this.front;
return this.back;
}
public void RenderLine(int line)
{
this.curLine = line;
// Render the line
this.dispCnt = Memory.ReadU16(this.memory.IORam, Memory.DISPCNT);
if ((this.dispCnt & (1 << 7)) != 0)
{
uint bgColor = Renderer.GbaTo32((ushort)0x7FFF);
for (int i = 0; i < 240; i++) this.scanline[i] = bgColor;
}
else
{
this.winEnabled = false;
if ((this.dispCnt & (1 << 13)) != 0)
{
// Calculate window 0 information
ushort winy = Memory.ReadU16(this.memory.IORam, Memory.WIN0V);
this.win0y1 = (byte)(winy >> 8);
this.win0y2 = (byte)(winy & 0xff);
ushort winx = Memory.ReadU16(this.memory.IORam, Memory.WIN0H);
this.win0x1 = (byte)(winx >> 8);
this.win0x2 = (byte)(winx & 0xff);
if (this.win0x2 > 240 || this.win0x1 > this.win0x2)
{
this.win0x2 = 240;
}
if (this.win0y2 > 160 || this.win0y1 > this.win0y2)
{
this.win0y2 = 160;
}
this.win0Enabled = this.memory.IORam[Memory.WININ];
this.winEnabled = true;
}
if ((this.dispCnt & (1 << 14)) != 0)
{
// Calculate window 1 information
ushort winy = Memory.ReadU16(this.memory.IORam, Memory.WIN1V);
this.win1y1 = (byte)(winy >> 8);
this.win1y2 = (byte)(winy & 0xff);
ushort winx = Memory.ReadU16(this.memory.IORam, Memory.WIN1H);
this.win1x1 = (byte)(winx >> 8);
this.win1x2 = (byte)(winx & 0xff);
if (this.win1x2 > 240 || this.win1x1 > this.win1x2)
{
this.win1x2 = 240;
}
if (this.win1y2 > 160 || this.win1y1 > this.win1y2)
{
this.win1y2 = 160;
}
this.win1Enabled = this.memory.IORam[Memory.WININ + 1];
this.winEnabled = true;
}
if ((this.dispCnt & (1 << 15)) != 0 && (this.dispCnt & (1 << 12)) != 0)
{
// Object windows are enabled
this.winObjEnabled = this.memory.IORam[Memory.WINOUT + 1];
this.winEnabled = true;
}
if (this.winEnabled)
{
this.winOutEnabled = this.memory.IORam[Memory.WINOUT];
}
// Calculate blending information
ushort bldcnt = Memory.ReadU16(this.memory.IORam, Memory.BLDCNT);
this.blendType = (bldcnt >> 6) & 0x3;
this.blendSource = (byte)(bldcnt & 0x3F);
this.blendTarget = (byte)((bldcnt >> 8) & 0x3F);
ushort bldalpha = Memory.ReadU16(this.memory.IORam, Memory.BLDALPHA);
this.blendA = (byte)(bldalpha & 0x1F);
if (this.blendA > 0x10) this.blendA = 0x10;
this.blendB = (byte)((bldalpha >> 8) & 0x1F);
if (this.blendB > 0x10) this.blendB = 0x10;
this.blendY = (byte)(this.memory.IORam[Memory.BLDY] & 0x1F);
if (this.blendY > 0x10) this.blendY = 0x10;
switch (this.dispCnt & 0x7)
{
case 0: this.RenderMode0Line(); break;
case 1: this.RenderMode1Line(); break;
case 2: this.RenderMode2Line(); break;
case 3: this.RenderMode3Line(); break;
case 4: this.RenderMode4Line(); break;
case 5: this.RenderMode5Line(); break;
}
}
Array.Copy(this.scanline, 0, this.back, this.curLine * Renderer.pitch, Renderer.pitch);
}
private void DrawBackdrop()
{
byte[] palette = this.memory.PaletteRam;
// Initialize window coverage buffer if neccesary
if (this.winEnabled)
{
for (int i = 0; i < 240; i++)
{
this.windowCover[i] = this.winOutEnabled;
}
if ((this.dispCnt & (1 << 15)) != 0)
{
// Sprite window
this.DrawSpriteWindows();
}
if ((this.dispCnt & (1 << 14)) != 0)
{
// Window 1
if (this.curLine >= this.win1y1 && this.curLine < this.win1y2)
{
for (int i = this.win1x1; i < this.win1x2; i++)
{
this.windowCover[i] = this.win1Enabled;
}
}
}
if ((this.dispCnt & (1 << 13)) != 0)
{
// Window 0
if (this.curLine >= this.win0y1 && this.curLine < this.win0y2)
{
for (int i = this.win0x1; i < this.win0x2; i++)
{
this.windowCover[i] = this.win0Enabled;
}
}
}
}
// Draw backdrop first
uint bgColor = Renderer.GbaTo32((ushort)(palette[0] | (palette[1] << 8)));
uint modColor = bgColor;
if (this.blendType == 2 && (this.blendSource & (1 << 5)) != 0)
{
// Brightness increase
uint r = bgColor & 0xFF;
uint g = (bgColor >> 8) & 0xFF;
uint b = (bgColor >> 16) & 0xFF;
r = r + (((0xFF - r) * this.blendY) >> 4);
g = g + (((0xFF - g) * this.blendY) >> 4);
b = b + (((0xFF - b) * this.blendY) >> 4);
modColor = r | (g << 8) | (b << 16);
}
else if (this.blendType == 3 && (this.blendSource & (1 << 5)) != 0)
{
// Brightness decrease
uint r = bgColor & 0xFF;
uint g = (bgColor >> 8) & 0xFF;
uint b = (bgColor >> 16) & 0xFF;
r = r - ((r * this.blendY) >> 4);
g = g - ((g * this.blendY) >> 4);
b = b - ((b * this.blendY) >> 4);
modColor = r | (g << 8) | (b << 16);
}
if (this.winEnabled)
{
for (int i = 0; i < 240; i++)
{
if ((this.windowCover[i] & (1 << 5)) != 0)
{
this.scanline[i] = modColor;
}
else
{
this.scanline[i] = bgColor;
}
this.blend[i] = 1 << 5;
}
}
else
{
for (int i = 0; i < 240; i++)
{
this.scanline[i] = modColor;
this.blend[i] = 1 << 5;
}
}
}
private void RenderTextBg(int bg)
{
if (this.winEnabled)
{
switch (this.blendType)
{
case 0:
this.RenderTextBgWindow(bg);
break;
case 1:
if ((this.blendSource & (1 << bg)) != 0)
this.RenderTextBgWindowBlend(bg);
else
this.RenderTextBgWindow(bg);
break;
case 2:
if ((this.blendSource & (1 << bg)) != 0)
this.RenderTextBgWindowBrightInc(bg);
else
this.RenderTextBgWindow(bg);
break;
case 3:
if ((this.blendSource & (1 << bg)) != 0)
this.RenderTextBgWindowBrightDec(bg);
else
this.RenderTextBgWindow(bg);
break;
}
}
else
{
switch (this.blendType)
{
case 0:
this.RenderTextBgNormal(bg);
break;
case 1:
if ((this.blendSource & (1 << bg)) != 0)
this.RenderTextBgBlend(bg);
else
this.RenderTextBgNormal(bg);
break;
case 2:
if ((this.blendSource & (1 << bg)) != 0)
this.RenderTextBgBrightInc(bg);
else
this.RenderTextBgNormal(bg);
break;
case 3:
if ((this.blendSource & (1 << bg)) != 0)
this.RenderTextBgBrightDec(bg);
else
this.RenderTextBgNormal(bg);
break;
}
}
}
private void RenderRotScaleBg(int bg)
{
if (this.winEnabled)
{
switch (this.blendType)
{
case 0:
this.RenderRotScaleBgWindow(bg);
break;
case 1:
if ((this.blendSource & (1 << bg)) != 0)
this.RenderRotScaleBgWindowBlend(bg);
else
this.RenderRotScaleBgWindow(bg);
break;
case 2:
if ((this.blendSource & (1 << bg)) != 0)
this.RenderRotScaleBgWindowBrightInc(bg);
else
this.RenderRotScaleBgWindow(bg);
break;
case 3:
if ((this.blendSource & (1 << bg)) != 0)
this.RenderRotScaleBgWindowBrightDec(bg);
else
this.RenderRotScaleBgWindow(bg);
break;
}
}
else
{
switch (this.blendType)
{
case 0:
this.RenderRotScaleBgNormal(bg);
break;
case 1:
if ((this.blendSource & (1 << bg)) != 0)
this.RenderRotScaleBgBlend(bg);
else
this.RenderRotScaleBgNormal(bg);
break;
case 2:
if ((this.blendSource & (1 << bg)) != 0)
this.RenderRotScaleBgBrightInc(bg);
else
this.RenderRotScaleBgNormal(bg);
break;
case 3:
if ((this.blendSource & (1 << bg)) != 0)
this.RenderRotScaleBgBrightDec(bg);
else
this.RenderRotScaleBgNormal(bg);
break;
}
}
}
private void DrawSprites(int pri)
{
if (this.winEnabled)
{
switch (this.blendType)
{
case 0:
this.DrawSpritesWindow(pri);
break;
case 1:
if ((this.blendSource & (1 << 4)) != 0)
this.DrawSpritesWindowBlend(pri);
else
this.DrawSpritesWindow(pri);
break;
case 2:
if ((this.blendSource & (1 << 4)) != 0)
this.DrawSpritesWindowBrightInc(pri);
else
this.DrawSpritesWindow(pri);
break;
case 3:
if ((this.blendSource & (1 << 4)) != 0)
this.DrawSpritesWindowBrightDec(pri);
else
this.DrawSpritesWindow(pri);
break;
}
}
else
{
switch (this.blendType)
{
case 0:
this.DrawSpritesNormal(pri);
break;
case 1:
if ((this.blendSource & (1 << 4)) != 0)
this.DrawSpritesBlend(pri);
else
this.DrawSpritesNormal(pri);
break;
case 2:
if ((this.blendSource & (1 << 4)) != 0)
this.DrawSpritesBrightInc(pri);
else
this.DrawSpritesNormal(pri);
break;
case 3:
if ((this.blendSource & (1 << 4)) != 0)
this.DrawSpritesBrightDec(pri);
else
this.DrawSpritesNormal(pri);
break;
}
}
}
private void RenderMode0Line()
{
byte[] palette = this.memory.PaletteRam;
byte[] vram = this.memory.VideoRam;
this.DrawBackdrop();
for (int pri = 3; pri >= 0; pri--)
{
for (int i = 3; i >= 0; i--)
{
if ((this.dispCnt & (1 << (8 + i))) != 0)
{
ushort bgcnt = Memory.ReadU16(this.memory.IORam, Memory.BG0CNT + 0x2 * (uint)i);
if ((bgcnt & 0x3) == pri)
{
this.RenderTextBg(i);
}
}
}
this.DrawSprites(pri);
}
}
private void RenderMode1Line()
{
byte[] palette = this.memory.PaletteRam;
byte[] vram = this.memory.VideoRam;
this.DrawBackdrop();
for (int pri = 3; pri >= 0; pri--)
{
if ((this.dispCnt & (1 << (8 + 2))) != 0)
{
ushort bgcnt = Memory.ReadU16(this.memory.IORam, Memory.BG2CNT);
if ((bgcnt & 0x3) == pri)
{
this.RenderRotScaleBg(2);
}
}
for (int i = 1; i >= 0; i--)
{
if ((this.dispCnt & (1 << (8 + i))) != 0)
{
ushort bgcnt = Memory.ReadU16(this.memory.IORam, Memory.BG0CNT + 0x2 * (uint)i);
if ((bgcnt & 0x3) == pri)
{
this.RenderTextBg(i);
}
}
}
this.DrawSprites(pri);
}
}
private void RenderMode2Line()
{
byte[] palette = this.memory.PaletteRam;
byte[] vram = this.memory.VideoRam;
this.DrawBackdrop();
for (int pri = 3; pri >= 0; pri--)
{
for (int i = 3; i >= 2; i--)
{
if ((this.dispCnt & (1 << (8 + i))) != 0)
{
ushort bgcnt = Memory.ReadU16(this.memory.IORam, Memory.BG0CNT + 0x2 * (uint)i);
if ((bgcnt & 0x3) == pri)
{
this.RenderRotScaleBg(i);
}
}
}
this.DrawSprites(pri);
}
}
private void RenderMode3Line()
{
ushort bg2Cnt = Memory.ReadU16(this.memory.IORam, Memory.BG2CNT);
byte[] palette = this.memory.PaletteRam;
byte[] vram = this.memory.VideoRam;
this.DrawBackdrop();
byte blendMaskType = (byte)(1 << 2);
int bgPri = bg2Cnt & 0x3;
for (int pri = 3; pri > bgPri; pri--)
{
this.DrawSprites(pri);
}
if ((this.dispCnt & (1 << 10)) != 0)
{
// Background enabled, render it
int x = this.memory.Bgx[0];
int y = this.memory.Bgy[0];
short dx = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PA);
short dy = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PC);
for (int i = 0; i < 240; i++)
{
int ax = ((int)x) >> 8;
int ay = ((int)y) >> 8;
if (ax >= 0 && ax < 240 && ay >= 0 && ay < 160)
{
int curIdx = ((ay * 240) + ax) * 2;
this.scanline[i] = Renderer.GbaTo32((ushort)(vram[curIdx] | (vram[curIdx + 1] << 8)));
this.blend[i] = blendMaskType;
}
x += dx;
y += dy;
}
}
for (int pri = bgPri; pri >= 0; pri--)
{
this.DrawSprites(pri);
}
}
private void RenderMode4Line()
{
ushort bg2Cnt = Memory.ReadU16(this.memory.IORam, Memory.BG2CNT);
byte[] palette = this.memory.PaletteRam;
byte[] vram = this.memory.VideoRam;
this.DrawBackdrop();
byte blendMaskType = (byte)(1 << 2);
int bgPri = bg2Cnt & 0x3;
for (int pri = 3; pri > bgPri; pri--)
{
this.DrawSprites(pri);
}
if ((this.dispCnt & (1 << 10)) != 0)
{
// Background enabled, render it
int baseIdx = 0;
if ((this.dispCnt & (1 << 4)) == 1 << 4) baseIdx = 0xA000;
int x = this.memory.Bgx[0];
int y = this.memory.Bgy[0];
short dx = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PA);
short dy = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PC);
for (int i = 0; i < 240; i++)
{
int ax = ((int)x) >> 8;
int ay = ((int)y) >> 8;
if (ax >= 0 && ax < 240 && ay >= 0 && ay < 160)
{
int lookup = vram[baseIdx + (ay * 240) + ax];
if (lookup != 0)
{
this.scanline[i] = Renderer.GbaTo32((ushort)(palette[lookup * 2] | (palette[lookup * 2 + 1] << 8)));
this.blend[i] = blendMaskType;
}
}
x += dx;
y += dy;
}
}
for (int pri = bgPri; pri >= 0; pri--)
{
this.DrawSprites(pri);
}
}
private void RenderMode5Line()
{
ushort bg2Cnt = Memory.ReadU16(this.memory.IORam, Memory.BG2CNT);
byte[] palette = this.memory.PaletteRam;
byte[] vram = this.memory.VideoRam;
this.DrawBackdrop();
byte blendMaskType = (byte)(1 << 2);
int bgPri = bg2Cnt & 0x3;
for (int pri = 3; pri > bgPri; pri--)
{
this.DrawSprites(pri);
}
if ((this.dispCnt & (1 << 10)) != 0)
{
// Background enabled, render it
int baseIdx = 0;
if ((this.dispCnt & (1 << 4)) == 1 << 4) baseIdx += 160 * 128 * 2;
int x = this.memory.Bgx[0];
int y = this.memory.Bgy[0];
short dx = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PA);
short dy = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PC);
for (int i = 0; i < 240; i++)
{
int ax = ((int)x) >> 8;
int ay = ((int)y) >> 8;
if (ax >= 0 && ax < 160 && ay >= 0 && ay < 128)
{
int curIdx = (int)(ay * 160 + ax) * 2;
this.scanline[i] = Renderer.GbaTo32((ushort)(vram[baseIdx + curIdx] | (vram[baseIdx + curIdx + 1] << 8)));
this.blend[i] = blendMaskType;
}
x += dx;
y += dy;
}
}
for (int pri = bgPri; pri >= 0; pri--)
{
this.DrawSprites(pri);
}
}
private void DrawSpriteWindows()
{
byte[] palette = this.memory.PaletteRam;
byte[] vram = this.memory.VideoRam;
// OBJ must be enabled in this.dispCnt
if ((this.dispCnt & (1 << 12)) == 0) return;
for (int oamNum = 127; oamNum >= 0; oamNum--)
{
ushort attr0 = this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(oamNum * 8) + 0);
// Not an object window, so continue
if (((attr0 >> 10) & 3) != 2) continue;
ushort attr1 = this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(oamNum * 8) + 2);
ushort attr2 = this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(oamNum * 8) + 4);
int x = attr1 & 0x1FF;
int y = attr0 & 0xFF;
int width = -1, height = -1;
switch ((attr0 >> 14) & 3)
{
case 0:
// Square
switch ((attr1 >> 14) & 3)
{
case 0: width = 8; height = 8; break;
case 1: width = 16; height = 16; break;
case 2: width = 32; height = 32; break;
case 3: width = 64; height = 64; break;
}
break;
case 1:
// Horizontal Rectangle
switch ((attr1 >> 14) & 3)
{
case 0: width = 16; height = 8; break;
case 1: width = 32; height = 8; break;
case 2: width = 32; height = 16; break;
case 3: width = 64; height = 32; break;
}
break;
case 2:
// Vertical Rectangle
switch ((attr1 >> 14) & 3)
{
case 0: width = 8; height = 16; break;
case 1: width = 8; height = 32; break;
case 2: width = 16; height = 32; break;
case 3: width = 32; height = 64; break;
}
break;
}
// Check double size flag here
int rwidth = width, rheight = height;
if ((attr0 & (1 << 8)) != 0)
{
// Rot-scale on
if ((attr0 & (1 << 9)) != 0)
{
rwidth *= 2;
rheight *= 2;
}
}
else
{
// Invalid sprite
if ((attr0 & (1 << 9)) != 0)
width = -1;
}
if (width == -1)
{
// Invalid sprite
continue;
}
// Y clipping
if (y > ((y + rheight) & 0xff))
{
if (this.curLine >= ((y + rheight) & 0xff) && !(y < this.curLine)) continue;
}
else
{
if (this.curLine < y || this.curLine >= ((y + rheight) & 0xff)) continue;
}
int scale = 1;
if ((attr0 & (1 << 13)) != 0) scale = 2;
int spritey = this.curLine - y;
if (spritey < 0) spritey += 256;
if ((attr0 & (1 << 8)) == 0)
{
if ((attr1 & (1 << 13)) != 0) spritey = (height - 1) - spritey;
int baseSprite;
if ((this.dispCnt & (1 << 6)) != 0)
{
// 1 dimensional
baseSprite = (attr2 & 0x3FF) + ((spritey / 8) * (width / 8)) * scale;
}
else
{
// 2 dimensional
baseSprite = (attr2 & 0x3FF) + ((spritey / 8) * 0x20);
}
int baseInc = scale;
if ((attr1 & (1 << 12)) != 0)
{
baseSprite += ((width / 8) * scale) - scale;
baseInc = -baseInc;
}
if ((attr0 & (1 << 13)) != 0)
{
// 256 colors
for (int i = x; i < x + width; i++)
{
if ((i & 0x1ff) < 240)
{
int tx = (i - x) & 7;
if ((attr1 & (1 << 12)) != 0) tx = 7 - tx;
int curIdx = baseSprite * 32 + ((spritey & 7) * 8) + tx;
int lookup = vram[0x10000 + curIdx];
if (lookup != 0)
{
this.windowCover[i & 0x1ff] = this.winObjEnabled;
}
}
if (((i - x) & 7) == 7) baseSprite += baseInc;
}
}
else
{
// 16 colors
int palIdx = 0x200 + (((attr2 >> 12) & 0xF) * 16 * 2);
for (int i = x; i < x + width; i++)
{
if ((i & 0x1ff) < 240)
{
int tx = (i - x) & 7;
if ((attr1 & (1 << 12)) != 0) tx = 7 - tx;
int curIdx = baseSprite * 32 + ((spritey & 7) * 4) + (tx / 2);
int lookup = vram[0x10000 + curIdx];
if ((tx & 1) == 0)
{
lookup &= 0xf;
}
else
{
lookup >>= 4;
}
if (lookup != 0)
{
this.windowCover[i & 0x1ff] = this.winObjEnabled;
}
}
if (((i - x) & 7) == 7) baseSprite += baseInc;
}
}
}
else
{
int rotScaleParam = (attr1 >> 9) & 0x1F;
short dx = (short)this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(rotScaleParam * 8 * 4) + 0x6);
short dmx = (short)this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(rotScaleParam * 8 * 4) + 0xE);
short dy = (short)this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(rotScaleParam * 8 * 4) + 0x16);
short dmy = (short)this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(rotScaleParam * 8 * 4) + 0x1E);
int cx = rwidth / 2;
int cy = rheight / 2;
int baseSprite = attr2 & 0x3FF;
int pitch;
if ((this.dispCnt & (1 << 6)) != 0)
{
// 1 dimensional
pitch = (width / 8) * scale;
}
else
{
// 2 dimensional
pitch = 0x20;
}
short rx = (short)((dmx * (spritey - cy)) - (cx * dx) + (width << 7));
short ry = (short)((dmy * (spritey - cy)) - (cx * dy) + (height << 7));
// Draw a rot/scale sprite
if ((attr0 & (1 << 13)) != 0)
{
// 256 colors
for (int i = x; i < x + rwidth; i++)
{
int tx = rx >> 8;
int ty = ry >> 8;
if ((i & 0x1ff) < 240 && tx >= 0 && tx < width && ty >= 0 && ty < height)
{
int curIdx = (baseSprite + ((ty / 8) * pitch) + ((tx / 8) * scale)) * 32 + ((ty & 7) * 8) + (tx & 7);
int lookup = vram[0x10000 + curIdx];
if (lookup != 0)
{
this.windowCover[i & 0x1ff] = this.winObjEnabled;
}
}
rx += dx;
ry += dy;
}
}
else
{
// 16 colors
int palIdx = 0x200 + (((attr2 >> 12) & 0xF) * 16 * 2);
for (int i = x; i < x + rwidth; i++)
{
int tx = rx >> 8;
int ty = ry >> 8;
if ((i & 0x1ff) < 240 && tx >= 0 && tx < width && ty >= 0 && ty < height)
{
int curIdx = (baseSprite + ((ty / 8) * pitch) + ((tx / 8) * scale)) * 32 + ((ty & 7) * 4) + ((tx & 7) / 2);
int lookup = vram[0x10000 + curIdx];
if ((tx & 1) == 0)
{
lookup &= 0xf;
}
else
{
lookup >>= 4;
}
if (lookup != 0)
{
this.windowCover[i & 0x1ff] = this.winObjEnabled;
}
}
rx += dx;
ry += dy;
}
}
}
}
}
public static uint GbaTo32(ushort color)
{
// more accurate, but slower :(
// return colorLUT[color];
return ((color & 0x1FU) << 19) | ((color & 0x3E0U) << 6) | ((color & 0x7C00U) >> 7);
}
}
}
|
//---------------------------------------------------------------------
// <copyright file="DuplicateStream.cs" company="Microsoft Corporation">
// Copyright (c) 1999, Microsoft Corporation. All rights reserved.
// </copyright>
// <summary>
// Part of the Deployment Tools Foundation project.
// </summary>
//---------------------------------------------------------------------
namespace Microsoft.PackageManagement.Archivers.Internal.Compression
{
using System;
using System.IO;
/// <summary>
/// Duplicates a source stream by maintaining a separate position.
/// </summary>
/// <remarks>
/// WARNING: duplicate streams are not thread-safe with respect to each other or the original stream.
/// If multiple threads use duplicate copies of the same stream, they must synchronize for any operations.
/// </remarks>
public class DuplicateStream : Stream
{
private Stream source;
private long position;
/// <summary>
/// Creates a new duplicate of a stream.
/// </summary>
/// <param name="source">source of the duplicate</param>
public DuplicateStream(Stream source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
this.source = DuplicateStream.OriginalStream(source);
}
/// <summary>
/// Gets the original stream that was used to create the duplicate.
/// </summary>
public Stream Source
{
get
{
return this.source;
}
}
/// <summary>
/// Gets a value indicating whether the source stream supports reading.
/// </summary>
/// <value>true if the stream supports reading; otherwise, false.</value>
public override bool CanRead
{
get
{
return this.source.CanRead;
}
}
/// <summary>
/// Gets a value indicating whether the source stream supports writing.
/// </summary>
/// <value>true if the stream supports writing; otherwise, false.</value>
public override bool CanWrite
{
get
{
return this.source.CanWrite;
}
}
/// <summary>
/// Gets a value indicating whether the source stream supports seeking.
/// </summary>
/// <value>true if the stream supports seeking; otherwise, false.</value>
public override bool CanSeek
{
get
{
return this.source.CanSeek;
}
}
/// <summary>
/// Gets the length of the source stream.
/// </summary>
public override long Length
{
get
{
return this.source.Length;
}
}
/// <summary>
/// Gets or sets the position of the current stream,
/// ignoring the position of the source stream.
/// </summary>
public override long Position
{
get
{
return this.position;
}
set
{
this.position = value;
}
}
/// <summary>
/// Retrieves the original stream from a possible duplicate stream.
/// </summary>
/// <param name="stream">Possible duplicate stream.</param>
/// <returns>If the stream is a DuplicateStream, returns
/// the duplicate's source; otherwise returns the same stream.</returns>
public static Stream OriginalStream(Stream stream)
{
DuplicateStream dupStream = stream as DuplicateStream;
return dupStream != null ? dupStream.Source : stream;
}
/// <summary>
/// Flushes the source stream.
/// </summary>
public override void Flush()
{
this.source.Flush();
}
/// <summary>
/// Sets the length of the source stream.
/// </summary>
/// <param name="value">The desired length of the stream in bytes.</param>
public override void SetLength(long value)
{
this.source.SetLength(value);
}
#if !CORECLR
/// <summary>
/// Closes the underlying stream, effectively closing ALL duplicates.
/// </summary>
public override void Close()
{
this.source.Close();
}
#endif
/// <summary>
/// Disposes the stream
/// </summary>
/// <param name="disposing"></param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
this.source.Dispose();
}
}
/// <summary>
/// Reads from the source stream while maintaining a separate position
/// and not impacting the source stream's position.
/// </summary>
/// <param name="buffer">An array of bytes. When this method returns, the buffer
/// contains the specified byte array with the values between offset and
/// (offset + count - 1) replaced by the bytes read from the current source.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin
/// storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns>The total number of bytes read into the buffer. This can be less
/// than the number of bytes requested if that many bytes are not currently available,
/// or zero (0) if the end of the stream has been reached.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
long saveSourcePosition = this.source.Position;
this.source.Position = this.position;
int read = this.source.Read(buffer, offset, count);
this.position = this.source.Position;
this.source.Position = saveSourcePosition;
return read;
}
/// <summary>
/// Writes to the source stream while maintaining a separate position
/// and not impacting the source stream's position.
/// </summary>
/// <param name="buffer">An array of bytes. This method copies count
/// bytes from buffer to the current stream.</param>
/// <param name="offset">The zero-based byte offset in buffer at which
/// to begin copying bytes to the current stream.</param>
/// <param name="count">The number of bytes to be written to the
/// current stream.</param>
public override void Write(byte[] buffer, int offset, int count)
{
long saveSourcePosition = this.source.Position;
this.source.Position = this.position;
this.source.Write(buffer, offset, count);
this.position = this.source.Position;
this.source.Position = saveSourcePosition;
}
/// <summary>
/// Changes the position of this stream without impacting the
/// source stream's position.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">A value of type SeekOrigin indicating the reference
/// point used to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
long originPosition = 0;
if (origin == SeekOrigin.Current)
{
originPosition = this.position;
}
else if (origin == SeekOrigin.End)
{
originPosition = this.Length;
}
this.position = originPosition + offset;
return this.position;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
namespace TrueSync.Physics2D
{
// Original Code by Steven Lu - see http://www.box2d.org/forum/viewtopic.php?f=3&t=1688
// Ported to Farseer 3.0 by Nicolás Hormazábal
internal struct ShapeData
{
public Body Body;
public FP Max;
public FP Min; // absolute angles
}
/// <summary>
/// This is a comprarer used for
/// detecting angle difference between rays
/// </summary>
internal class RayDataComparer : IComparer<FP>
{
#region IComparer<FP> Members
int IComparer<FP>.Compare(FP a, FP b)
{
FP diff = (a - b);
if (diff > 0)
return 1;
if (diff < 0)
return -1;
return 0;
}
#endregion
}
/* Methodology:
* Force applied at a ray is inversely proportional to the square of distance from source
* AABB is used to query for shapes that may be affected
* For each RIGID BODY (not shape -- this is an optimization) that is matched, loop through its vertices to determine
* the extreme points -- if there is structure that contains outlining polygon, use that as an additional optimization
* Evenly cast a number of rays against the shape - number roughly proportional to the arc coverage
* - Something like every 3 degrees should do the trick although this can be altered depending on the distance (if really close don't need such a high density of rays)
* - There should be a minimum number of rays (3-5?) applied to each body so that small bodies far away are still accurately modeled
* - Be sure to have the forces of each ray be proportional to the average arc length covered by each.
* For each ray that actually intersects with the shape (non intersections indicate something blocking the path of explosion):
* - Apply the appropriate force dotted with the negative of the collision normal at the collision point
* - Optionally apply linear interpolation between aforementioned Normal force and the original explosion force in the direction of ray to simulate "surface friction" of sorts
*/
/// <summary>
/// Creates a realistic explosion based on raycasting. Objects in the open will be affected, but objects behind
/// static bodies will not. A body that is half in cover, half in the open will get half the force applied to the end in
/// the open.
/// </summary>
public sealed class RealExplosion : PhysicsLogic
{
/// <summary>
/// Two degrees: maximum angle from edges to first ray tested
/// </summary>
private static readonly FP MaxEdgeOffset = FP.Pi / 90;
/// <summary>
/// Ratio of arc length to angle from edges to first ray tested.
/// Defaults to 1/40.
/// </summary>
public FP EdgeRatio = 1.0f / 40.0f;
/// <summary>
/// Ignore Explosion if it happens inside a shape.
/// Default value is false.
/// </summary>
public bool IgnoreWhenInsideShape = false;
/// <summary>
/// Max angle between rays (used when segment is large).
/// Defaults to 15 degrees
/// </summary>
public FP MaxAngle = FP.Pi / 15;
/// <summary>
/// Maximum number of shapes involved in the explosion.
/// Defaults to 100
/// </summary>
public int MaxShapes = 100;
/// <summary>
/// How many rays per shape/body/segment.
/// Defaults to 5
/// </summary>
public int MinRays = 5;
private List<ShapeData> _data = new List<ShapeData>();
private RayDataComparer _rdc;
public RealExplosion(World world)
: base(world, PhysicsLogicType.Explosion)
{
_rdc = new RayDataComparer();
_data = new List<ShapeData>();
}
/// <summary>
/// Activate the explosion at the specified position.
/// </summary>
/// <param name="pos">The position where the explosion happens </param>
/// <param name="radius">The explosion radius </param>
/// <param name="maxForce">The explosion force at the explosion point (then is inversely proportional to the square of the distance)</param>
/// <returns>A list of bodies and the amount of force that was applied to them.</returns>
public Dictionary<Fixture, TSVector2> Activate(TSVector2 pos, FP radius, FP maxForce)
{
AABB aabb;
aabb.LowerBound = pos + new TSVector2(-radius, -radius);
aabb.UpperBound = pos + new TSVector2(radius, radius);
Fixture[] shapes = new Fixture[MaxShapes];
// More than 5 shapes in an explosion could be possible, but still strange.
Fixture[] containedShapes = new Fixture[5];
bool exit = false;
int shapeCount = 0;
int containedShapeCount = 0;
// Query the world for overlapping shapes.
World.QueryAABB(
fixture =>
{
if (fixture.TestPoint(ref pos))
{
if (IgnoreWhenInsideShape)
{
exit = true;
return false;
}
containedShapes[containedShapeCount++] = fixture;
}
else
{
shapes[shapeCount++] = fixture;
}
// Continue the query.
return true;
}, ref aabb);
if (exit)
return new Dictionary<Fixture, TSVector2>();
Dictionary<Fixture, TSVector2> exploded = new Dictionary<Fixture, TSVector2>(shapeCount + containedShapeCount);
// Per shape max/min angles for now.
FP[] vals = new FP[shapeCount * 2];
int valIndex = 0;
for (int i = 0; i < shapeCount; ++i)
{
PolygonShape ps;
CircleShape cs = shapes[i].Shape as CircleShape;
if (cs != null)
{
// We create a "diamond" approximation of the circle
Vertices v = new Vertices();
TSVector2 vec = TSVector2.zero + new TSVector2(cs.Radius, 0);
v.Add(vec);
vec = TSVector2.zero + new TSVector2(0, cs.Radius);
v.Add(vec);
vec = TSVector2.zero + new TSVector2(-cs.Radius, cs.Radius);
v.Add(vec);
vec = TSVector2.zero + new TSVector2(0, -cs.Radius);
v.Add(vec);
ps = new PolygonShape(v, 0);
}
else
ps = shapes[i].Shape as PolygonShape;
if ((shapes[i].Body.BodyType == BodyType.Dynamic) && ps != null)
{
TSVector2 toCentroid = shapes[i].Body.GetWorldPoint(ps.MassData.Centroid) - pos;
FP angleToCentroid = FP.Atan2(toCentroid.y, toCentroid.x);
FP min = FP.MaxValue;
FP max = FP.MinValue;
FP minAbsolute = 0.0f;
FP maxAbsolute = 0.0f;
for (int j = 0; j < ps.Vertices.Count; ++j)
{
TSVector2 toVertex = (shapes[i].Body.GetWorldPoint(ps.Vertices[j]) - pos);
FP newAngle = FP.Atan2(toVertex.y, toVertex.x);
FP diff = (newAngle - angleToCentroid);
diff = (diff - FP.Pi) % (2 * FP.Pi);
// the minus pi is important. It means cutoff for going other direction is at 180 deg where it needs to be
if (diff < 0.0f)
diff += 2 * FP.Pi; // correction for not handling negs
diff -= FP.Pi;
if (FP.Abs(diff) > FP.Pi)
continue; // Something's wrong, point not in shape but exists angle diff > 180
if (diff > max)
{
max = diff;
maxAbsolute = newAngle;
}
if (diff < min)
{
min = diff;
minAbsolute = newAngle;
}
}
vals[valIndex] = minAbsolute;
++valIndex;
vals[valIndex] = maxAbsolute;
++valIndex;
}
}
Array.Sort(vals, 0, valIndex, _rdc);
_data.Clear();
bool rayMissed = true;
for (int i = 0; i < valIndex; ++i)
{
Fixture fixture = null;
FP midpt;
int iplus = (i == valIndex - 1 ? 0 : i + 1);
if (vals[i] == vals[iplus])
continue;
if (i == valIndex - 1)
{
// the single edgecase
midpt = (vals[0] + FP.PiTimes2 + vals[i]);
}
else
{
midpt = (vals[i + 1] + vals[i]);
}
midpt = midpt / 2;
TSVector2 p1 = pos;
TSVector2 p2 = radius * new TSVector2(FP.Cos(midpt), FP.Sin(midpt)) + pos;
// RaycastOne
bool hitClosest = false;
World.RayCast((f, p, n, fr) =>
{
Body body = f.Body;
if (!IsActiveOn(body))
return 0;
hitClosest = true;
fixture = f;
return fr;
}, p1, p2);
//draws radius points
if ((hitClosest) && (fixture.Body.BodyType == BodyType.Dynamic))
{
if ((_data.Any()) && (_data.Last().Body == fixture.Body) && (!rayMissed))
{
int laPos = _data.Count - 1;
ShapeData la = _data[laPos];
la.Max = vals[iplus];
_data[laPos] = la;
}
else
{
// make new
ShapeData d;
d.Body = fixture.Body;
d.Min = vals[i];
d.Max = vals[iplus];
_data.Add(d);
}
if ((_data.Count > 1)
&& (i == valIndex - 1)
&& (_data.Last().Body == _data.First().Body)
&& (_data.Last().Max == _data.First().Min))
{
ShapeData fi = _data[0];
fi.Min = _data.Last().Min;
_data.RemoveAt(_data.Count - 1);
_data[0] = fi;
while (_data.First().Min >= _data.First().Max)
{
fi.Min -= FP.PiTimes2;
_data[0] = fi;
}
}
int lastPos = _data.Count - 1;
ShapeData last = _data[lastPos];
while ((_data.Count > 0)
&& (_data.Last().Min >= _data.Last().Max)) // just making sure min<max
{
last.Min = _data.Last().Min - FP.PiTimes2;
_data[lastPos] = last;
}
rayMissed = false;
}
else
{
rayMissed = true; // raycast did not find a shape
}
}
for (int i = 0; i < _data.Count; ++i)
{
if (!IsActiveOn(_data[i].Body))
continue;
FP arclen = _data[i].Max - _data[i].Min;
FP first = TSMath.Min(MaxEdgeOffset, EdgeRatio * arclen);
int insertedRays = FP.Ceiling((((arclen - 2.0f * first) - (MinRays - 1) * MaxAngle) / MaxAngle)).AsInt();
if (insertedRays < 0)
insertedRays = 0;
FP offset = (arclen - first * 2.0f) / ((FP)MinRays + insertedRays - 1);
//Note: This loop can go into infinite as it operates on FPs.
//Added FPEquals with a large epsilon.
for (FP j = _data[i].Min + first;
j < _data[i].Max || MathUtils.FPEquals(j, _data[i].Max, 0.0001f);
j += offset)
{
TSVector2 p1 = pos;
TSVector2 p2 = pos + radius * new TSVector2(FP.Cos(j), FP.Sin(j));
TSVector2 hitpoint = TSVector2.zero;
FP minlambda = FP.MaxValue;
List<Fixture> fl = _data[i].Body.FixtureList;
for (int x = 0; x < fl.Count; x++)
{
Fixture f = fl[x];
RayCastInput ri;
ri.Point1 = p1;
ri.Point2 = p2;
ri.MaxFraction = 50f;
RayCastOutput ro;
if (f.RayCast(out ro, ref ri, 0))
{
if (minlambda > ro.Fraction)
{
minlambda = ro.Fraction;
hitpoint = ro.Fraction * p2 + (1 - ro.Fraction) * p1;
}
}
// the force that is to be applied for this particular ray.
// offset is angular coverage. lambda*length of segment is distance.
FP impulse = (arclen / (MinRays + insertedRays)) * maxForce * 180.0f / FP.Pi * (1.0f - TrueSync.TSMath.Min(FP.One, minlambda));
// We Apply the impulse!!!
TSVector2 vectImp = TSVector2.Dot(impulse * new TSVector2(FP.Cos(j), FP.Sin(j)), -ro.Normal) * new TSVector2(FP.Cos(j), FP.Sin(j));
_data[i].Body.ApplyLinearImpulse(ref vectImp, ref hitpoint);
// We gather the fixtures for returning them
if (exploded.ContainsKey(f))
exploded[f] += vectImp;
else
exploded.Add(f, vectImp);
if (minlambda > 1.0f)
hitpoint = p2;
}
}
}
// We check contained shapes
for (int i = 0; i < containedShapeCount; ++i)
{
Fixture fix = containedShapes[i];
if (!IsActiveOn(fix.Body))
continue;
FP impulse = MinRays * maxForce * 180.0f / FP.Pi;
TSVector2 hitPoint;
CircleShape circShape = fix.Shape as CircleShape;
if (circShape != null)
{
hitPoint = fix.Body.GetWorldPoint(circShape.Position);
}
else
{
PolygonShape shape = fix.Shape as PolygonShape;
hitPoint = fix.Body.GetWorldPoint(shape.MassData.Centroid);
}
TSVector2 vectImp = impulse * (hitPoint - pos);
fix.Body.ApplyLinearImpulse(ref vectImp, ref hitPoint);
if (!exploded.ContainsKey(fix))
exploded.Add(fix, vectImp);
}
return exploded;
}
}
} |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
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.Collections.Generic;
using System.Diagnostics;
using System;
namespace Orleans.Runtime
{
internal class Constants
{
// This needs to be first, as GrainId static initializers reference it. Otherwise, GrainId actually see a uninitialized (ie Zero) value for that "constant"!
public static readonly TimeSpan INFINITE_TIMESPAN = TimeSpan.FromMilliseconds(-1);
// We assume that clock skew between silos and between clients and silos is always less than 1 second
public static readonly TimeSpan MAXIMUM_CLOCK_SKEW = TimeSpan.FromSeconds(1);
public const string DEFAULT_STORAGE_PROVIDER_NAME = "Default";
public const string MEMORY_STORAGE_PROVIDER_NAME = "MemoryStore";
public const string DATA_CONNECTION_STRING_NAME = "DataConnectionString";
public static readonly GrainId DirectoryServiceId = GrainId.GetSystemTargetGrainId(10);
public static readonly GrainId DirectoryCacheValidatorId = GrainId.GetSystemTargetGrainId(11);
public static readonly GrainId SiloControlId = GrainId.GetSystemTargetGrainId(12);
public static readonly GrainId ClientObserverRegistrarId = GrainId.GetSystemTargetGrainId(13);
public static readonly GrainId CatalogId = GrainId.GetSystemTargetGrainId(14);
public static readonly GrainId MembershipOracleId = GrainId.GetSystemTargetGrainId(15);
public static readonly GrainId ReminderServiceId = GrainId.GetSystemTargetGrainId(16);
public static readonly GrainId TypeManagerId = GrainId.GetSystemTargetGrainId(17);
public static readonly GrainId ProviderManagerSystemTargetId = GrainId.GetSystemTargetGrainId(19);
public static readonly GrainId DeploymentLoadPublisherSystemTargetId = GrainId.GetSystemTargetGrainId(22);
public const int PULLING_AGENTS_MANAGER_SYSTEM_TARGET_TYPE_CODE = 254;
public const int PULLING_AGENT_SYSTEM_TARGET_TYPE_CODE = 255;
public static readonly GrainId SystemMembershipTableId = GrainId.GetSystemGrainId(new Guid("01145FEC-C21E-11E0-9105-D0FB4724019B"));
public static readonly GrainId SiloDirectConnectionId = GrainId.GetSystemGrainId(new Guid("01111111-1111-1111-1111-111111111111"));
internal const long ReminderTableGrainId = 12345;
/// <summary>
/// The default timeout before a request is assumed to have failed.
/// </summary>
public static readonly TimeSpan DEFAULT_RESPONSE_TIMEOUT = Debugger.IsAttached ? TimeSpan.FromMinutes(30) : TimeSpan.FromSeconds(30);
/// <summary>
/// Minimum period for registering a reminder ... we want to enforce a lower bound
/// </summary>
public static readonly TimeSpan MinReminderPeriod = TimeSpan.FromMinutes(1); // increase this period, reminders are supposed to be less frequent ... we use 2 seconds just to reduce the running time of the unit tests
/// <summary>
/// Refresh local reminder list to reflect the global reminder table every 'REFRESH_REMINDER_LIST' period
/// </summary>
public static readonly TimeSpan RefreshReminderList = TimeSpan.FromMinutes(5);
public const int LARGE_OBJECT_HEAP_THRESHOLD = 85000;
public const bool DEFAULT_PROPAGATE_E2E_ACTIVITY_ID = false;
public const int DEFAULT_LOGGER_BULK_MESSAGE_LIMIT = 5;
public static readonly bool USE_BLOCKING_COLLECTION = true;
private static readonly Dictionary<GrainId, string> singletonSystemTargetNames = new Dictionary<GrainId, string>
{
{DirectoryServiceId, "DirectoryService"},
{DirectoryCacheValidatorId, "DirectoryCacheValidator"},
{SiloControlId,"SiloControl"},
{ClientObserverRegistrarId,"ClientObserverRegistrar"},
{CatalogId,"Catalog"},
{MembershipOracleId,"MembershipOracle"},
{ReminderServiceId,"ReminderService"},
{TypeManagerId,"TypeManagerId"},
{ProviderManagerSystemTargetId, "ProviderManagerSystemTarget"},
{DeploymentLoadPublisherSystemTargetId, "DeploymentLoadPublisherSystemTarge"},
};
private static readonly Dictionary<int, string> nonSingletonSystemTargetNames = new Dictionary<int, string>
{
{PULLING_AGENT_SYSTEM_TARGET_TYPE_CODE, "PullingAgentSystemTarget"},
{PULLING_AGENTS_MANAGER_SYSTEM_TARGET_TYPE_CODE, "PullingAgentsManagerSystemTarget"},
};
public static string SystemTargetName(GrainId id)
{
string name;
if (singletonSystemTargetNames.TryGetValue(id, out name)) return name;
if (nonSingletonSystemTargetNames.TryGetValue(id.GetTypeCode(), out name)) return name;
return String.Empty;
}
public static bool IsSingletonSystemTarget(GrainId id)
{
return singletonSystemTargetNames.ContainsKey(id);
}
private static readonly Dictionary<GrainId, string> systemGrainNames = new Dictionary<GrainId, string>
{
{SystemMembershipTableId, "MembershipTableGrain"},
{SiloDirectConnectionId, "SiloDirectConnectionId"}
};
public static bool TryGetSystemGrainName(GrainId id, out string name)
{
return systemGrainNames.TryGetValue(id, out name);
}
public static bool IsSystemGrain(GrainId grain)
{
return systemGrainNames.ContainsKey(grain);
}
}
}
|
//
// FastTemplate
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Jeff Panici
// 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.Globalization;
namespace PaniciSoftware.FastTemplate.Common
{
public class UIntType : PrimitiveType
{
public UIntType()
{
}
public UIntType(Int64 i)
{
Value = (UInt64) i;
}
public override Type UnderlyingType
{
get { return typeof (UInt64); }
}
public override object RawValue
{
get { return Value; }
}
public UInt64 Value { get; set; }
public static explicit operator UIntType(UInt64 i)
{
return new UIntType((Int64) i);
}
public override object ApplyBinary(Operator op, ITemplateType rhs)
{
switch (op)
{
case Operator.Div:
{
var uIntType = rhs as UIntType;
if (uIntType != null)
{
return Value/(uIntType).Value;
}
var doubleType = rhs as DoubleType;
if (doubleType != null)
{
return Value/(doubleType).Value;
}
var decimalType = rhs as DecimalType;
if (decimalType != null)
{
return Value/(decimalType).Value;
}
break;
}
case Operator.EQ:
{
var uIntType = rhs as UIntType;
if (uIntType != null)
{
return Value == (uIntType).Value;
}
var doubleType = rhs as DoubleType;
if (doubleType != null)
{
return Value == (doubleType).Value;
}
var decimalType = rhs as DecimalType;
if (decimalType != null)
{
return Value == (decimalType).Value;
}
if (rhs is NullType)
{
return Value == default(ulong);
}
break;
}
case Operator.GE:
{
var uIntType = rhs as UIntType;
if (uIntType != null)
{
return Value >= (uIntType).Value;
}
var doubleType = rhs as DoubleType;
if (doubleType != null)
{
return Value >= (doubleType).Value;
}
var decimalType = rhs as DecimalType;
if (decimalType != null)
{
return Value >= (decimalType).Value;
}
break;
}
case Operator.GT:
{
var uIntType = rhs as UIntType;
if (uIntType != null)
{
return Value > (uIntType).Value;
}
var doubleType = rhs as DoubleType;
if (doubleType != null)
{
return Value > (doubleType).Value;
}
var decimalType = rhs as DecimalType;
if (decimalType != null)
{
return Value > (decimalType).Value;
}
break;
}
case Operator.LE:
{
var uIntType = rhs as UIntType;
if (uIntType != null)
{
return Value <= (uIntType).Value;
}
var doubleType = rhs as DoubleType;
if (doubleType != null)
{
return Value <= (doubleType).Value;
}
var decimalType = rhs as DecimalType;
if (decimalType != null)
{
return Value <= (decimalType).Value;
}
break;
}
case Operator.LT:
{
var uIntType = rhs as UIntType;
if (uIntType != null)
{
return Value < (uIntType).Value;
}
var doubleType = rhs as DoubleType;
if (doubleType != null)
{
return Value < (doubleType).Value;
}
var decimalType = rhs as DecimalType;
if (decimalType != null)
{
return Value < (decimalType).Value;
}
break;
}
case Operator.Minus:
{
var uIntType = rhs as UIntType;
if (uIntType != null)
{
return Value - (uIntType).Value;
}
var doubleType = rhs as DoubleType;
if (doubleType != null)
{
return Value - (doubleType).Value;
}
var decimalType = rhs as DecimalType;
if (decimalType != null)
{
return Value - (decimalType).Value;
}
break;
}
case Operator.Mod:
{
var uIntType = rhs as UIntType;
if (uIntType != null)
{
return Value%(uIntType).Value;
}
var doubleType = rhs as DoubleType;
if (doubleType != null)
{
return Value%(doubleType).Value;
}
var decimalType = rhs as DecimalType;
if (decimalType != null)
{
return Value%(decimalType).Value;
}
break;
}
case Operator.Mul:
{
var uIntType = rhs as UIntType;
if (uIntType != null)
{
return Value*(uIntType).Value;
}
var doubleType = rhs as DoubleType;
if (doubleType != null)
{
return Value*(doubleType).Value;
}
var decimalType = rhs as DecimalType;
if (decimalType != null)
{
return Value*(decimalType).Value;
}
break;
}
case Operator.NEQ:
{
var uIntType = rhs as UIntType;
if (uIntType != null)
{
return Value != (uIntType).Value;
}
var doubleType = rhs as DoubleType;
if (doubleType != null)
{
return Value != (doubleType).Value;
}
var decimalType = rhs as DecimalType;
if (decimalType != null)
{
return Value != (decimalType).Value;
}
if (rhs is NullType)
{
return Value != default(ulong);
}
break;
}
case Operator.Plus:
{
var uIntType = rhs as UIntType;
if (uIntType != null)
{
return Value + (uIntType).Value;
}
var doubleType = rhs as DoubleType;
if (doubleType != null)
{
return Value + (doubleType).Value;
}
var stringType = rhs as StringType;
if (stringType != null)
{
return string.Format(
"{0}{1}", Value, (stringType).Value);
}
var decimalType = rhs as DecimalType;
if (decimalType != null)
{
return Value + (decimalType).Value;
}
break;
}
}
throw new InvalidTypeException(
op.ToString(), UnderlyingType, rhs.UnderlyingType);
}
public override bool TryConvert<T>(out T o)
{
try
{
var type = typeof (T);
if (type == typeof (string))
{
o = (T) (object) Value.ToString(CultureInfo.InvariantCulture);
return true;
}
if (type == typeof (double))
{
o = (T) (object) Convert.ToDouble(Value);
return true;
}
if (type == typeof (UInt64))
{
o = (T) (object) Value;
return true;
}
if (type == typeof (Int64))
{
o = (T) (object) Convert.ToInt64(Value);
return true;
}
if (type == typeof (decimal))
{
o = (T) (object) Convert.ToDecimal(Value);
return true;
}
}
catch (Exception)
{
o = default(T);
return false;
}
o = default(T);
return false;
}
public override object ApplyUnary(Operator op)
{
switch (op)
{
case Operator.Plus:
{
return +Value;
}
}
throw new InvalidTypeException(
op.ToString(), UnderlyingType);
}
}
} |
using Microsoft.Diagnostics.Tracing;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Management.Automation;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading;
namespace EtwStream.PowerShell
{
[Cmdlet(VerbsCommon.Get, "TraceEventStream", DefaultParameterSetName = "nameOrGuid")]
public class GetTraceEvent : PSCmdlet
{
private CompositeDisposable disposable = new CompositeDisposable();
[Parameter(Position = 0, ParameterSetName = "nameOrGuid", Mandatory = true, ValueFromPipeline = true)]
public string[] NameOrGuid { get; set; }
[ValidateSet(
nameof(WellKnownEventSources.AspNetEventSource),
nameof(WellKnownEventSources.ConcurrentCollectionsEventSource),
nameof(WellKnownEventSources.FrameworkEventSource),
nameof(WellKnownEventSources.PinnableBufferCacheEventSource),
nameof(WellKnownEventSources.PlinqEventSource),
nameof(WellKnownEventSources.SqlEventSource),
nameof(WellKnownEventSources.SynchronizationEventSource),
nameof(WellKnownEventSources.TplEventSource))]
[Parameter(Position = 0, ParameterSetName = "wellKnown", Mandatory = true, ValueFromPipeline = true)]
public string[] WellKnownEventSource { get; set; }
[ValidateSet(
nameof(IISEventSources.AspDotNetEvents),
nameof(IISEventSources.HttpEvent),
nameof(IISEventSources.HttpLog),
nameof(IISEventSources.HttpService),
nameof(IISEventSources.IISAppHostSvc),
nameof(IISEventSources.IISLogging),
nameof(IISEventSources.IISW3Svc),
nameof(IISEventSources.RuntimeWebApi),
nameof(IISEventSources.RuntimeWebHttp))]
[Parameter(Position = 0, ParameterSetName = "IIS", Mandatory = true, ValueFromPipeline = true)]
public string[] IISEventSource { get; set; }
[Parameter]
public SwitchParameter DumpWithColor { get; set; }
[Parameter]
public TraceEventLevel TraceLevel { get; set; } = TraceEventLevel.Verbose;
private IObservable<TraceEvent> listener = Observable.Empty<TraceEvent>();
protected override void ProcessRecord()
{
switch (ParameterSetName)
{
case "wellKnown":
listener = listener.Merge(WellKnownEventSource.Select(x => GetWellKnownEventListener(x)).Merge());
break;
case "IIS":
listener = listener.Merge(IISEventSource.Select(x => GetIISEventListener(x)).Merge());
break;
default:
listener = listener.Merge(NameOrGuid.Select(x => ObservableEventListener.FromTraceEvent(x)).Merge());
break;
}
}
protected override void EndProcessing()
{
var q = new BlockingCollection<Action>();
Exception exception = null;
var d = listener
.Where(x => Process.GetCurrentProcess().Id != x.ProcessID)
.Where(x => x.Level <= TraceLevel)
.Subscribe(
x =>
{
q.Add(() =>
{
var item = new PSTraceEvent(x, Host.UI);
if (DumpWithColor.IsPresent)
{
item.DumpWithColor();
}
else
{
WriteObject(item);
}
WriteVerbose(item.DumpPayloadOrMessage());
});
},
e =>
{
exception = e;
q.CompleteAdding();
}, q.CompleteAdding);
disposable.Add(d);
var cts = new CancellationTokenSource();
disposable.Add(new CancellationDisposable(cts));
foreach (var act in q.GetConsumingEnumerable(cts.Token))
{
act();
}
if (exception != null)
{
ThrowTerminatingError(new ErrorRecord(exception, "1", ErrorCategory.OperationStopped, null));
}
}
protected override void StopProcessing()
{
disposable.Dispose();
}
private IObservable<TraceEvent> GetWellKnownEventListener(string wellKnownEventSource)
{
switch (wellKnownEventSource)
{
case nameof(WellKnownEventSources.AspNetEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.AspNetEventSource);
case nameof(WellKnownEventSources.ConcurrentCollectionsEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.ConcurrentCollectionsEventSource);
case nameof(WellKnownEventSources.FrameworkEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.FrameworkEventSource);
case nameof(WellKnownEventSources.PinnableBufferCacheEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.PinnableBufferCacheEventSource);
case nameof(WellKnownEventSources.PlinqEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.PlinqEventSource);
case nameof(WellKnownEventSources.SqlEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.SqlEventSource);
case nameof(WellKnownEventSources.SynchronizationEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.SynchronizationEventSource);
case nameof(WellKnownEventSources.TplEventSource):
return ObservableEventListener.FromTraceEvent(WellKnownEventSources.TplEventSource);
default:
return Observable.Empty<TraceEvent>();
}
}
private IObservable<TraceEvent> GetIISEventListener(string iisEventSource)
{
switch (iisEventSource)
{
case nameof(IISEventSources.AspDotNetEvents):
return ObservableEventListener.FromTraceEvent(IISEventSources.AspDotNetEvents);
case nameof(IISEventSources.HttpEvent):
return ObservableEventListener.FromTraceEvent(IISEventSources.HttpEvent);
case nameof(IISEventSources.HttpLog):
return ObservableEventListener.FromTraceEvent(IISEventSources.HttpLog);
case nameof(IISEventSources.HttpService):
return ObservableEventListener.FromTraceEvent(IISEventSources.HttpService);
case nameof(IISEventSources.IISAppHostSvc):
return ObservableEventListener.FromTraceEvent(IISEventSources.IISAppHostSvc);
case nameof(IISEventSources.IISLogging):
return ObservableEventListener.FromTraceEvent(IISEventSources.IISLogging);
case nameof(IISEventSources.IISW3Svc):
return ObservableEventListener.FromTraceEvent(IISEventSources.IISW3Svc);
case nameof(IISEventSources.RuntimeWebApi):
return ObservableEventListener.FromTraceEvent(IISEventSources.RuntimeWebApi);
case nameof(IISEventSources.RuntimeWebHttp):
return ObservableEventListener.FromTraceEvent(IISEventSources.RuntimeWebHttp);
default:
return Observable.Empty<TraceEvent>();
}
}
}
}
|
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace CSharpGL
{
public partial class GL
{
#region OpenGL 2.0
// Constants
///// <summary>
/////
///// </summary>
//public const uint GL_BLEND_EQUATION_RGB = 0x8009;
///// <summary>
/////
///// </summary>
//public const uint GL_VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622;
///// <summary>
/////
///// </summary>
//public const uint GL_VERTEX_ATTRIB_ARRAY_SIZE = 0x8623;
///// <summary>
/////
///// </summary>
//public const uint GL_VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624;
///// <summary>
/////
///// </summary>
//public const uint GL_VERTEX_ATTRIB_ARRAY_TYPE = 0x8625;
///// <summary>
/////
///// </summary>
//public const uint GL_CURRENT_VERTEX_ATTRIB = 0x8626;
/// <summary>
///
/// </summary>
public const uint GL_VERTEX_PROGRAM_POINT_SIZE = 0x8642;
///// <summary>
/////
///// </summary>
//public const uint GL_VERTEX_ATTRIB_ARRAY_POINTER = 0x8645;
///// <summary>
/////
///// </summary>
//public const uint GL_STENCIL_BACK_FUNC = 0x8800;
///// <summary>
/////
///// </summary>
//public const uint GL_STENCIL_BACK_FAIL = 0x8801;
///// <summary>
/////
///// </summary>
//public const uint GL_STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802;
///// <summary>
/////
///// </summary>
//public const uint GL_STENCIL_BACK_PASS_DEPTH_PASS = 0x8803;
///// <summary>
/////
///// </summary>
//public const uint GL_MAX_DRAW_BUFFERS = 0x8824;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER0 = 0x8825;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER1 = 0x8826;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER2 = 0x8827;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER3 = 0x8828;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER4 = 0x8829;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER5 = 0x882A;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER6 = 0x882B;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER7 = 0x882C;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER8 = 0x882D;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER9 = 0x882E;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER10 = 0x882F;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER11 = 0x8830;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER12 = 0x8831;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER13 = 0x8832;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER14 = 0x8833;
///// <summary>
/////
///// </summary>
//public const uint GL_DRAW_BUFFER15 = 0x8834;
///// <summary>
/////
///// </summary>
//public const uint GL_BLEND_EQUATION_ALPHA = 0x883D;
///// <summary>
/////
///// </summary>
//public const uint GL_MAX_VERTEX_ATTRIBS = 0x8869;
///// <summary>
/////
///// </summary>
//public const uint GL_VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886A;
///// <summary>
/////
///// </summary>
//public const uint GL_MAX_TEXTURE_IMAGE_UNITS = 0x8872;
/// <summary>
///
/// </summary>
public const uint GL_FRAGMENT_SHADER = 0x8B30;
/// <summary>
///
/// </summary>
public const uint GL_VERTEX_SHADER = 0x8B31;
/// <summary>
///
/// </summary>
public const uint GL_TESS_CONTROL_SHADER = 0x8E88;
/// <summary>
///
/// </summary>
public const uint GL_TESS_EVALUATION_SHADER = 0x8E87;
/// <summary>
///
/// </summary>
public const uint GL_MAX_FRAGMENT_UNIFORM_COMPONENTS = 0x8B49;
/// <summary>
///
/// </summary>
public const uint GL_MAX_VERTEX_UNIFORM_COMPONENTS = 0x8B4A;
/// <summary>
///
/// </summary>
public const uint GL_MAX_VARYING_FLOATS = 0x8B4B;
/// <summary>
///
/// </summary>
public const uint GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8B4C;
/// <summary>
///
/// </summary>
public const uint GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8B4D;
/// <summary>
///
/// </summary>
public const uint GL_SHADER_TYPE = 0x8B4F;
/// <summary>
///
/// </summary>
public const uint GL_FLOAT_VEC2 = 0x8B50;
/// <summary>
///
/// </summary>
public const uint GL_FLOAT_VEC3 = 0x8B51;
/// <summary>
///
/// </summary>
public const uint GL_FLOAT_VEC4 = 0x8B52;
/// <summary>
///
/// </summary>
public const uint GL_INT_VEC2 = 0x8B53;
/// <summary>
///
/// </summary>
public const uint GL_INT_VEC3 = 0x8B54;
/// <summary>
///
/// </summary>
public const uint GL_INT_VEC4 = 0x8B55;
/// <summary>
///
/// </summary>
public const uint GL_BOOL = 0x8B56;
/// <summary>
///
/// </summary>
public const uint GL_BOOL_VEC2 = 0x8B57;
/// <summary>
///
/// </summary>
public const uint GL_BOOL_VEC3 = 0x8B58;
/// <summary>
///
/// </summary>
public const uint GL_BOOL_VEC4 = 0x8B59;
/// <summary>
///
/// </summary>
public const uint GL_FLOAT_MAT2 = 0x8B5A;
/// <summary>
///
/// </summary>
public const uint GL_FLOAT_MAT3 = 0x8B5B;
/// <summary>
///
/// </summary>
public const uint GL_FLOAT_MAT4 = 0x8B5C;
/// <summary>
///
/// </summary>
public const uint GL_SAMPLER_1D = 0x8B5D;
/// <summary>
///
/// </summary>
public const uint GL_SAMPLER_2D = 0x8B5E;
/// <summary>
///
/// </summary>
public const uint GL_SAMPLER_3D = 0x8B5F;
/// <summary>
///
/// </summary>
public const uint GL_SAMPLER_CUBE = 0x8B60;
/// <summary>
///
/// </summary>
public const uint GL_SAMPLER_1D_SHADOW = 0x8B61;
/// <summary>
///
/// </summary>
public const uint GL_SAMPLER_2D_SHADOW = 0x8B62;
/// <summary>
///
/// </summary>
public const uint GL_DELETE_STATUS = 0x8B80;
/// <summary>
///
/// </summary>
public const uint GL_COMPILE_STATUS = 0x8B81;
/// <summary>
///
/// </summary>
public const uint GL_LINK_STATUS = 0x8B82;
/// <summary>
///
/// </summary>
public const uint GL_VALIDATE_STATUS = 0x8B83;
/// <summary>
///
/// </summary>
public const uint GL_INFO_LOG_LENGTH = 0x8B84;
/// <summary>
///
/// </summary>
public const uint GL_ATTACHED_SHADERS = 0x8B85;
/// <summary>
///
/// </summary>
public const uint GL_ACTIVE_UNIFORMS = 0x8B86;
/// <summary>
///
/// </summary>
public const uint GL_ACTIVE_UNIFORM_MAX_LENGTH = 0x8B87;
/// <summary>
///
/// </summary>
public const uint GL_SHADER_SOURCE_LENGTH = 0x8B88;
/// <summary>
///
/// </summary>
public const uint GL_ACTIVE_ATTRIBUTES = 0x8B89;
/// <summary>
///
/// </summary>
public const uint GL_ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8B8A;
/// <summary>
///
/// </summary>
public const uint GL_FRAGMENT_SHADER_DERIVATIVE_HINT = 0x8B8B;
/// <summary>
///
/// </summary>
public const uint GL_SHADING_LANGUAGE_VERSION = 0x8B8C;
/// <summary>
///
/// </summary>
public const uint GL_CURRENT_PROGRAM = 0x8B8D;
/// <summary>
///
/// </summary>
public const uint GL_POINT_SPRITE_COORD_ORIGIN = 0x8CA0;
/// <summary>
///
/// </summary>
public const uint GL_LOWER_LEFT = 0x8CA1;
/// <summary>
///
/// </summary>
public const uint GL_UPPER_LEFT = 0x8CA2;
/// <summary>
///
/// </summary>
public const uint GL_STENCIL_BACK_REF = 0x8CA3;
/// <summary>
///
/// </summary>
public const uint GL_STENCIL_BACK_VALUE_MASK = 0x8CA4;
/// <summary>
///
/// </summary>
public const uint GL_STENCIL_BACK_WRITEMASK = 0x8CA5;
#endregion OpenGL 2.0
}
} |
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
#nullable disable
namespace StyleCop.Analyzers.OrderingRules
{
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using StyleCop.Analyzers.Helpers;
using StyleCop.Analyzers.Settings.ObjectModel;
/// <summary>
/// A constant field is placed beneath a non-constant field.
/// </summary>
/// <remarks>
/// <para>A violation of this rule occurs when a constant field is placed beneath a non-constant field. Constants
/// should be placed above fields to indicate that the two are fundamentally different types of elements with
/// different considerations for the compiler, different naming requirements, etc.</para>
/// </remarks>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal class SA1203ConstantsMustAppearBeforeFields : DiagnosticAnalyzer
{
/// <summary>
/// The ID for diagnostics produced by the <see cref="SA1203ConstantsMustAppearBeforeFields"/> analyzer.
/// </summary>
public const string DiagnosticId = "SA1203";
private const string HelpLink = "https://github.com/DotNetAnalyzers/StyleCopAnalyzers/blob/master/documentation/SA1203.md";
private static readonly LocalizableString Title = new LocalizableResourceString(nameof(OrderingResources.SA1203Title), OrderingResources.ResourceManager, typeof(OrderingResources));
private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(OrderingResources.SA1203MessageFormat), OrderingResources.ResourceManager, typeof(OrderingResources));
private static readonly LocalizableString Description = new LocalizableResourceString(nameof(OrderingResources.SA1203Description), OrderingResources.ResourceManager, typeof(OrderingResources));
private static readonly DiagnosticDescriptor Descriptor =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, AnalyzerCategory.OrderingRules, DiagnosticSeverity.Warning, AnalyzerConstants.EnabledByDefault, Description, HelpLink);
private static readonly ImmutableArray<SyntaxKind> TypeDeclarationKinds =
ImmutableArray.Create(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration);
private static readonly Action<SyntaxNodeAnalysisContext, StyleCopSettings> TypeDeclarationAction = HandleTypeDeclaration;
/// <inheritdoc/>
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
ImmutableArray.Create(Descriptor);
/// <inheritdoc/>
public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterSyntaxNodeAction(TypeDeclarationAction, TypeDeclarationKinds);
}
private static void HandleTypeDeclaration(SyntaxNodeAnalysisContext context, StyleCopSettings settings)
{
var elementOrder = settings.OrderingRules.ElementOrder;
int constantIndex = elementOrder.IndexOf(OrderingTrait.Constant);
if (constantIndex < 0)
{
return;
}
var typeDeclaration = (TypeDeclarationSyntax)context.Node;
var members = typeDeclaration.Members;
var previousFieldConstant = true;
var previousFieldStatic = false;
var previousFieldReadonly = false;
var previousAccessLevel = AccessLevel.NotSpecified;
foreach (var member in members)
{
if (!(member is FieldDeclarationSyntax field))
{
continue;
}
AccessLevel currentAccessLevel = MemberOrderHelper.GetAccessLevelForOrdering(field, field.Modifiers);
bool currentFieldConstant = field.Modifiers.Any(SyntaxKind.ConstKeyword);
bool currentFieldReadonly = currentFieldConstant || field.Modifiers.Any(SyntaxKind.ReadOnlyKeyword);
bool currentFieldStatic = currentFieldConstant || field.Modifiers.Any(SyntaxKind.StaticKeyword);
bool compareConst = true;
for (int j = 0; compareConst && j < constantIndex; j++)
{
switch (elementOrder[j])
{
case OrderingTrait.Accessibility:
if (currentAccessLevel != previousAccessLevel)
{
compareConst = false;
}
continue;
case OrderingTrait.Readonly:
if (currentFieldReadonly != previousFieldReadonly)
{
compareConst = false;
}
continue;
case OrderingTrait.Static:
if (currentFieldStatic != previousFieldStatic)
{
compareConst = false;
}
continue;
case OrderingTrait.Kind:
// Only fields may be marked const, and all fields have the same kind.
continue;
case OrderingTrait.Constant:
default:
continue;
}
}
if (compareConst)
{
if (!previousFieldConstant && currentFieldConstant)
{
context.ReportDiagnostic(Diagnostic.Create(Descriptor, NamedTypeHelpers.GetNameOrIdentifierLocation(member)));
}
}
previousFieldConstant = currentFieldConstant;
previousFieldReadonly = currentFieldReadonly;
previousFieldStatic = currentFieldStatic;
previousAccessLevel = currentAccessLevel;
}
}
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Profiler.cs" company="Kephas Software SRL">
// Copyright (c) Kephas Software SRL. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
// Provides operations for profiling the code.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Kephas.Diagnostics
{
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Kephas.Logging;
using Kephas.Operations;
using Kephas.Threading.Tasks;
/// <summary>
/// Provides operations for profiling the code.
/// </summary>
public static class Profiler
{
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Warning"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithWarningStopwatch(
this Action action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Warning, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Warning"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithWarningStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Warning, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Info"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithInfoStopwatch(
this Action action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Info, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Info"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithInfoStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Info, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Debug"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithDebugStopwatch(
this Action action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Debug, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Debug"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithDebugStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Debug, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Trace"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithTraceStopwatch(
this Action action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Trace, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at <see cref="LogLevel.Trace"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithTraceStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatch(action, logger, LogLevel.Trace, memberName);
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at the indicated log level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="logLevel">The log level.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult WithStopwatch(
this Action action,
ILogger? logger = null,
LogLevel logLevel = LogLevel.Debug,
[CallerMemberName] string? memberName = null)
{
var result = new OperationResult();
if (action == null)
{
return result.MergeMessage($"No action provided for {memberName}.");
}
result.MergeMessage($"{memberName}. Started at: {DateTime.Now:s}.");
logger?.Log(logLevel, "{operation}. Started at: {startedAt:s}.", memberName, DateTime.Now);
var stopwatch = new Stopwatch();
stopwatch.Start();
action();
stopwatch.Stop();
result
.MergeMessage($"{memberName}. Ended at: {DateTime.Now:s}. Elapsed: {stopwatch.Elapsed:c}.")
.Complete(stopwatch.Elapsed);
logger?.Log(logLevel, "{operation}. Ended at: {endedAt:s}. Elapsed: {elapsed:c}.", memberName, DateTime.Now, stopwatch.Elapsed);
return result;
}
/// <summary>
/// Executes the action with a stopwatch, optionally logging the elapsed time at the indicated
/// log level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">Optional. The logger.</param>
/// <param name="logLevel">Optional. The log level.</param>
/// <param name="memberName">Optional. Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static IOperationResult<T> WithStopwatch<T>(
this Func<T> action,
ILogger? logger = null,
LogLevel logLevel = LogLevel.Debug,
[CallerMemberName] string? memberName = null)
{
var result = new OperationResult<T>();
if (action == null)
{
return result.MergeMessage($"No action provided for {memberName}.");
}
result.MergeMessage($"{memberName}. Started at: {DateTime.Now:s}.");
logger?.Log(logLevel, "{operation}. Started at: {startedAt:s}.", memberName, DateTime.Now);
var stopwatch = new Stopwatch();
stopwatch.Start();
result.Value = action();
stopwatch.Stop();
result
.MergeMessage($"{memberName}. Ended at: {DateTime.Now:s}. Elapsed: {stopwatch.Elapsed:c}.")
.Complete(stopwatch.Elapsed);
logger?.Log(logLevel, "{operation}. Ended at: {endedAt:s}. Elapsed: {elapsed:c}.", memberName, DateTime.Now, stopwatch.Elapsed);
return result;
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Warning"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult> WithWarningStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Warning, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Warning"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult<T>> WithWarningStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Warning, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Info"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult> WithInfoStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Info, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Info"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult<T>> WithInfoStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Info, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Debug"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult> WithDebugStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Debug, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Debug"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult<T>> WithDebugStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Debug, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Trace"/> level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult> WithTraceStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync(action, logger, LogLevel.Trace, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at <see cref="LogLevel.Trace"/> level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static Task<IOperationResult<T>> WithTraceStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
[CallerMemberName] string? memberName = null)
{
return WithStopwatchAsync<T>(action, logger, LogLevel.Trace, memberName);
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed time at the indicated log level.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="logger">The logger.</param>
/// <param name="logLevel">The log level.</param>
/// <param name="memberName">Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static async Task<IOperationResult> WithStopwatchAsync(
this Func<Task> action,
ILogger? logger = null,
LogLevel logLevel = LogLevel.Debug,
[CallerMemberName] string? memberName = null)
{
var result = new OperationResult();
if (action == null)
{
return result.MergeMessage($"No action provided for {memberName}.");
}
result.MergeMessage($"{memberName}. Started at: {DateTime.Now:s}.");
logger?.Log(logLevel, "{operation}. Started at: {startedAt:s}.", memberName, DateTime.Now);
var stopwatch = new Stopwatch();
stopwatch.Start();
await action().PreserveThreadContext();
stopwatch.Stop();
result
.MergeMessage($"{memberName}. Ended at: {DateTime.Now:s}. Elapsed: {stopwatch.Elapsed:c}.")
.Complete(stopwatch.Elapsed);
logger?.Log(logLevel, "{operation}. Ended at: {endedAt:s}. Elapsed: {elapsed:c}.", memberName, DateTime.Now, stopwatch.Elapsed);
return result;
}
/// <summary>
/// Executes the action with a stopwatch for asynchronous actions, optionally logging the elapsed
/// time at the indicated log level.
/// </summary>
/// <typeparam name="T">The operation return type.</typeparam>
/// <param name="action">The action.</param>
/// <param name="logger">Optional. The logger.</param>
/// <param name="logLevel">Optional. The log level.</param>
/// <param name="memberName">Optional. Name of the member.</param>
/// <returns>
/// The elapsed time.
/// </returns>
public static async Task<IOperationResult<T>> WithStopwatchAsync<T>(
this Func<Task<T>> action,
ILogger? logger = null,
LogLevel logLevel = LogLevel.Debug,
[CallerMemberName] string? memberName = null)
{
var result = new OperationResult<T>();
if (action == null)
{
return result.MergeMessage($"No action provided for {memberName}.");
}
result.MergeMessage($"{memberName}. Started at: {DateTime.Now:s}.");
logger?.Log(logLevel, "{operation}. Started at: {startedAt:s}.", memberName, DateTime.Now);
var stopwatch = new Stopwatch();
stopwatch.Start();
result.Value = await action().PreserveThreadContext();
stopwatch.Stop();
result
.MergeMessage($"{memberName}. Ended at: {DateTime.Now:s}. Elapsed: {stopwatch.Elapsed:c}.")
.Complete(stopwatch.Elapsed);
logger?.Log(logLevel, "{operation}. Ended at: {endedAt:s}. Elapsed: {elapsed:c}.", memberName, DateTime.Now, stopwatch.Elapsed);
return result;
}
}
} |
// -----------------------------------------------------------
//
// This file was generated, please do not modify.
//
// -----------------------------------------------------------
namespace EmptyKeys.UserInterface.Generated {
using System;
using System.CodeDom.Compiler;
using System.Collections.ObjectModel;
using EmptyKeys.UserInterface;
using EmptyKeys.UserInterface.Charts;
using EmptyKeys.UserInterface.Data;
using EmptyKeys.UserInterface.Controls;
using EmptyKeys.UserInterface.Controls.Primitives;
using EmptyKeys.UserInterface.Input;
using EmptyKeys.UserInterface.Interactions.Core;
using EmptyKeys.UserInterface.Interactivity;
using EmptyKeys.UserInterface.Media;
using EmptyKeys.UserInterface.Media.Effects;
using EmptyKeys.UserInterface.Media.Animation;
using EmptyKeys.UserInterface.Media.Imaging;
using EmptyKeys.UserInterface.Shapes;
using EmptyKeys.UserInterface.Renderers;
using EmptyKeys.UserInterface.Themes;
[GeneratedCodeAttribute("Empty Keys UI Generator", "3.1.0.0")]
public sealed class Dictionary : ResourceDictionary {
private static Dictionary singleton = new Dictionary();
public Dictionary() {
this.InitializeResources();
}
public static Dictionary Instance {
get {
return singleton;
}
}
private void InitializeResources() {
// Resource - [buttonAnimStyle] Style
var r_0_s_bo = this[typeof(Button)];
Style r_0_s = new Style(typeof(Button), r_0_s_bo as Style);
Setter r_0_s_S_0 = new Setter(Button.WidthProperty, 200F);
r_0_s.Setters.Add(r_0_s_S_0);
Setter r_0_s_S_1 = new Setter(Button.MarginProperty, new Thickness(0F, 1F, 0F, 1F));
r_0_s.Setters.Add(r_0_s_S_1);
Setter r_0_s_S_2 = new Setter(Button.SnapsToDevicePixelsProperty, false);
r_0_s.Setters.Add(r_0_s_S_2);
EventTrigger r_0_s_ET_0 = new EventTrigger(Button.MouseEnterEvent);
r_0_s.Triggers.Add(r_0_s_ET_0);
BeginStoryboard r_0_s_ET_0_AC_0 = new BeginStoryboard();
r_0_s_ET_0_AC_0.Name = "r_0_s_ET_0_AC_0";
r_0_s_ET_0.AddAction(r_0_s_ET_0_AC_0);
Storyboard r_0_s_ET_0_AC_0_SB = new Storyboard();
r_0_s_ET_0_AC_0.Storyboard = r_0_s_ET_0_AC_0_SB;
r_0_s_ET_0_AC_0_SB.Name = "r_0_s_ET_0_AC_0_SB";
ThicknessAnimation r_0_s_ET_0_AC_0_SB_TL_0 = new ThicknessAnimation();
r_0_s_ET_0_AC_0_SB_TL_0.Name = "r_0_s_ET_0_AC_0_SB_TL_0";
r_0_s_ET_0_AC_0_SB_TL_0.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 500));
r_0_s_ET_0_AC_0_SB_TL_0.From = new Thickness(0F, 1F, 0F, 1F);
r_0_s_ET_0_AC_0_SB_TL_0.To = new Thickness(0F, 5F, 0F, 5F);
SineEase r_0_s_ET_0_AC_0_SB_TL_0_EA = new SineEase();
r_0_s_ET_0_AC_0_SB_TL_0.EasingFunction = r_0_s_ET_0_AC_0_SB_TL_0_EA;
Storyboard.SetTargetProperty(r_0_s_ET_0_AC_0_SB_TL_0, Button.MarginProperty);
r_0_s_ET_0_AC_0_SB.Children.Add(r_0_s_ET_0_AC_0_SB_TL_0);
FloatAnimation r_0_s_ET_0_AC_0_SB_TL_1 = new FloatAnimation();
r_0_s_ET_0_AC_0_SB_TL_1.Name = "r_0_s_ET_0_AC_0_SB_TL_1";
r_0_s_ET_0_AC_0_SB_TL_1.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 500));
r_0_s_ET_0_AC_0_SB_TL_1.To = 220F;
SineEase r_0_s_ET_0_AC_0_SB_TL_1_EA = new SineEase();
r_0_s_ET_0_AC_0_SB_TL_1.EasingFunction = r_0_s_ET_0_AC_0_SB_TL_1_EA;
Storyboard.SetTargetProperty(r_0_s_ET_0_AC_0_SB_TL_1, Button.WidthProperty);
r_0_s_ET_0_AC_0_SB.Children.Add(r_0_s_ET_0_AC_0_SB_TL_1);
EventTrigger r_0_s_ET_1 = new EventTrigger(Button.MouseLeaveEvent);
r_0_s.Triggers.Add(r_0_s_ET_1);
BeginStoryboard r_0_s_ET_1_AC_0 = new BeginStoryboard();
r_0_s_ET_1_AC_0.Name = "r_0_s_ET_1_AC_0";
r_0_s_ET_1.AddAction(r_0_s_ET_1_AC_0);
Storyboard r_0_s_ET_1_AC_0_SB = new Storyboard();
r_0_s_ET_1_AC_0.Storyboard = r_0_s_ET_1_AC_0_SB;
r_0_s_ET_1_AC_0_SB.Name = "r_0_s_ET_1_AC_0_SB";
ThicknessAnimation r_0_s_ET_1_AC_0_SB_TL_0 = new ThicknessAnimation();
r_0_s_ET_1_AC_0_SB_TL_0.Name = "r_0_s_ET_1_AC_0_SB_TL_0";
r_0_s_ET_1_AC_0_SB_TL_0.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 500));
r_0_s_ET_1_AC_0_SB_TL_0.From = new Thickness(0F, 5F, 0F, 5F);
r_0_s_ET_1_AC_0_SB_TL_0.To = new Thickness(0F, 1F, 0F, 1F);
SineEase r_0_s_ET_1_AC_0_SB_TL_0_EA = new SineEase();
r_0_s_ET_1_AC_0_SB_TL_0.EasingFunction = r_0_s_ET_1_AC_0_SB_TL_0_EA;
Storyboard.SetTargetProperty(r_0_s_ET_1_AC_0_SB_TL_0, Button.MarginProperty);
r_0_s_ET_1_AC_0_SB.Children.Add(r_0_s_ET_1_AC_0_SB_TL_0);
FloatAnimation r_0_s_ET_1_AC_0_SB_TL_1 = new FloatAnimation();
r_0_s_ET_1_AC_0_SB_TL_1.Name = "r_0_s_ET_1_AC_0_SB_TL_1";
r_0_s_ET_1_AC_0_SB_TL_1.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 500));
r_0_s_ET_1_AC_0_SB_TL_1.To = 200F;
SineEase r_0_s_ET_1_AC_0_SB_TL_1_EA = new SineEase();
r_0_s_ET_1_AC_0_SB_TL_1.EasingFunction = r_0_s_ET_1_AC_0_SB_TL_1_EA;
Storyboard.SetTargetProperty(r_0_s_ET_1_AC_0_SB_TL_1, Button.WidthProperty);
r_0_s_ET_1_AC_0_SB.Children.Add(r_0_s_ET_1_AC_0_SB_TL_1);
this.Add("buttonAnimStyle", r_0_s);
// Resource - [buttonStyle] Style
var r_1_s_bo = this[typeof(Button)];
Style r_1_s = new Style(typeof(Button), r_1_s_bo as Style);
Setter r_1_s_S_0 = new Setter(Button.BackgroundProperty, new SolidColorBrush(new ColorW(255, 140, 0, 255)));
r_1_s.Setters.Add(r_1_s_S_0);
Setter r_1_s_S_1 = new Setter(Button.WidthProperty, 200F);
r_1_s.Setters.Add(r_1_s_S_1);
Setter r_1_s_S_2 = new Setter(Button.PaddingProperty, new Thickness(2F));
r_1_s.Setters.Add(r_1_s_S_2);
this.Add("buttonStyle", r_1_s);
// Resource - [logoEmptyKeys] BitmapImage
BitmapImage r_2_bm = new BitmapImage();
r_2_bm.TextureAsset = "Images/EmptyKeysLogoTextSmall";
this.Add("logoEmptyKeys", r_2_bm);
// Resource - [MessageBoxButtonYes] String
this.Add("MessageBoxButtonYes", "Yes!");
// Resource - [Sounds] SoundSourceCollection
var r_4_sounds = new SoundSourceCollection();
SoundManager.Instance.AddSound("Click");
r_4_sounds.Add(new SoundSource { SoundType = SoundType.ButtonsClick, SoundAsset = "Click", Volume = 1f });
SoundManager.Instance.AddSound("KeyPress");
r_4_sounds.Add(new SoundSource { SoundType = SoundType.TextBoxKeyPress, SoundAsset = "KeyPress", Volume = 1f });
SoundManager.Instance.AddSound("Move");
r_4_sounds.Add(new SoundSource { SoundType = SoundType.TabControlMove, SoundAsset = "Move", Volume = 1f });
SoundManager.Instance.AddSound("Select");
r_4_sounds.Add(new SoundSource { SoundType = SoundType.TabControlSelect, SoundAsset = "Select", Volume = 1f });
this.Add("Sounds", r_4_sounds);
// Resource - [TitleResource] String
this.Add("TitleResource", "Basic UI Example");
// Resource - [ToolTipText] String
this.Add("ToolTipText", "Click to open message box");
ImageManager.Instance.AddImage("Images/EmptyKeysLogoTextSmall");
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Scoring;
using osu.Game.Rulesets.UI;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModBlinds : Mod, IApplicableToRulesetContainer<OsuHitObject>, IApplicableToScoreProcessor
{
public override string Name => "Blinds";
public override string Description => "Play with blinds on your screen.";
public override string Acronym => "BL";
public override FontAwesome Icon => FontAwesome.fa_adjust;
public override ModType Type => ModType.DifficultyIncrease;
public override bool Ranked => false;
public override double ScoreMultiplier => 1.12;
private DrawableOsuBlinds blinds;
public void ApplyToRulesetContainer(RulesetContainer<OsuHitObject> rulesetContainer)
{
rulesetContainer.Overlays.Add(blinds = new DrawableOsuBlinds(rulesetContainer.Playfield.HitObjectContainer, rulesetContainer.Beatmap));
}
public void ApplyToScoreProcessor(ScoreProcessor scoreProcessor)
{
scoreProcessor.Health.ValueChanged += health => { blinds.AnimateClosedness((float)health.NewValue); };
}
/// <summary>
/// Element for the Blinds mod drawing 2 black boxes covering the whole screen which resize inside a restricted area with some leniency.
/// </summary>
public class DrawableOsuBlinds : Container
{
/// <summary>
/// Black background boxes behind blind panel textures.
/// </summary>
private Box blackBoxLeft, blackBoxRight;
private Drawable panelLeft, panelRight, bgPanelLeft, bgPanelRight;
private readonly Beatmap<OsuHitObject> beatmap;
/// <summary>
/// Value between 0 and 1 setting a maximum "closedness" for the blinds.
/// Useful for animating how far the blinds can be opened while keeping them at the original position if they are wider open than this.
/// </summary>
private const float target_clamp = 1;
private readonly float targetBreakMultiplier = 0;
private readonly float easing = 1;
private readonly CompositeDrawable restrictTo;
/// <summary>
/// <para>
/// Percentage of playfield to extend blinds over. Basically moves the origin points where the blinds start.
/// </para>
/// <para>
/// -1 would mean the blinds always cover the whole screen no matter health.
/// 0 would mean the blinds will only ever be on the edge of the playfield on 0% health.
/// 1 would mean the blinds are fully outside the playfield on 50% health.
/// Infinity would mean the blinds are always outside the playfield except on 100% health.
/// </para>
/// </summary>
private const float leniency = 0.1f;
public DrawableOsuBlinds(CompositeDrawable restrictTo, Beatmap<OsuHitObject> beatmap)
{
this.restrictTo = restrictTo;
this.beatmap = beatmap;
}
[BackgroundDependencyLoader]
private void load()
{
RelativeSizeAxes = Axes.Both;
Children = new[]
{
blackBoxLeft = new Box
{
Anchor = Anchor.TopLeft,
Origin = Anchor.TopLeft,
Colour = Color4.Black,
RelativeSizeAxes = Axes.Y,
},
blackBoxRight = new Box
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Colour = Color4.Black,
RelativeSizeAxes = Axes.Y,
},
bgPanelLeft = new ModBlindsPanel
{
Origin = Anchor.TopRight,
Colour = Color4.Gray,
},
panelLeft = new ModBlindsPanel { Origin = Anchor.TopRight, },
bgPanelRight = new ModBlindsPanel { Colour = Color4.Gray },
panelRight = new ModBlindsPanel()
};
}
private float calculateGap(float value) => MathHelper.Clamp(value, 0, target_clamp) * targetBreakMultiplier;
// lagrange polinominal for (0,0) (0.6,0.4) (1,1) should make a good curve
private static float applyAdjustmentCurve(float value) => 0.6f * value * value + 0.4f * value;
protected override void Update()
{
float start = Parent.ToLocalSpace(restrictTo.ScreenSpaceDrawQuad.TopLeft).X;
float end = Parent.ToLocalSpace(restrictTo.ScreenSpaceDrawQuad.TopRight).X;
float rawWidth = end - start;
start -= rawWidth * leniency * 0.5f;
end += rawWidth * leniency * 0.5f;
float width = (end - start) * 0.5f * applyAdjustmentCurve(calculateGap(easing));
// different values in case the playfield ever moves from center to somewhere else.
blackBoxLeft.Width = start + width;
blackBoxRight.Width = DrawWidth - end + width;
panelLeft.X = start + width;
panelRight.X = end - width;
bgPanelLeft.X = start;
bgPanelRight.X = end;
}
protected override void LoadComplete()
{
const float break_open_early = 500;
const float break_close_late = 250;
base.LoadComplete();
var firstObj = beatmap.HitObjects[0];
var startDelay = firstObj.StartTime - firstObj.TimePreempt;
using (BeginAbsoluteSequence(startDelay + break_close_late, true))
leaveBreak();
foreach (var breakInfo in beatmap.Breaks)
{
if (breakInfo.HasEffect)
{
using (BeginAbsoluteSequence(breakInfo.StartTime - break_open_early, true))
{
enterBreak();
using (BeginDelayedSequence(breakInfo.Duration + break_open_early + break_close_late, true))
leaveBreak();
}
}
}
}
private void enterBreak() => this.TransformTo(nameof(targetBreakMultiplier), 0f, 1000, Easing.OutSine);
private void leaveBreak() => this.TransformTo(nameof(targetBreakMultiplier), 1f, 2500, Easing.OutBounce);
/// <summary>
/// 0 is open, 1 is closed.
/// </summary>
public void AnimateClosedness(float value) => this.TransformTo(nameof(easing), value, 200, Easing.OutQuint);
public class ModBlindsPanel : Sprite
{
[BackgroundDependencyLoader]
private void load(TextureStore textures)
{
Texture = textures.Get("Play/osu/blinds-panel");
}
}
}
}
}
|
/*
The MIT License (MIT)
Copyright (c) 2014 Banbury & Play-Em
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 UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
using System.IO;
#endif
namespace SpritesAndBones.Editor
{
[CustomEditor(typeof(Skin2D))]
public class Skin2DEditor : UnityEditor.Editor
{
private Skin2D skin;
private float baseSelectDistance = 0.1f;
private float changedBaseSelectDistance = 0.1f;
private int selectedIndex = -1;
private Color handleColor = Color.green;
private void OnEnable()
{
skin = (Skin2D)target;
}
public override void OnInspectorGUI()
{
DrawDefaultInspector();
EditorGUILayout.Separator();
if (GUILayout.Button("Toggle Mesh Outline"))
{
Skin2D.showMeshOutline = !Skin2D.showMeshOutline;
}
EditorGUILayout.Separator();
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Save as Prefab"))
{
skin.SaveAsPrefab();
}
EditorGUILayout.Separator();
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Recalculate Bone Weights"))
{
skin.RecalculateBoneWeights();
}
EditorGUILayout.Separator();
handleColor = EditorGUILayout.ColorField("Handle Color", handleColor);
changedBaseSelectDistance = EditorGUILayout.Slider("Handle Size", baseSelectDistance, 0, 1);
if (baseSelectDistance != changedBaseSelectDistance)
{
baseSelectDistance = changedBaseSelectDistance;
EditorUtility.SetDirty(this);
SceneView.RepaintAll();
}
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Create Control Points"))
{
skin.CreateControlPoints(skin.GetComponent<SkinnedMeshRenderer>());
}
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Reset Control Points"))
{
skin.ResetControlPointPositions();
}
if (skin.points != null && skin.controlPoints != null && skin.controlPoints.Length > 0
&& selectedIndex != -1 && GUILayout.Button("Reset Selected Control Point"))
{
if (skin.controlPoints[selectedIndex].originalPosition != skin.GetComponent<MeshFilter>().sharedMesh.vertices[selectedIndex])
{
skin.controlPoints[selectedIndex].originalPosition = skin.GetComponent<MeshFilter>().sharedMesh.vertices[selectedIndex];
}
skin.controlPoints[selectedIndex].ResetPosition();
skin.points.SetPoint(skin.controlPoints[selectedIndex]);
}
if (GUILayout.Button("Remove Control Points"))
{
skin.RemoveControlPoints();
}
EditorGUILayout.Separator();
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null && GUILayout.Button("Generate Mesh Asset"))
{
#if UNITY_EDITOR
// Check if the Meshes directory exists, if not, create it.
if (!Directory.Exists("Assets/Meshes"))
{
AssetDatabase.CreateFolder("Assets", "Meshes");
AssetDatabase.Refresh();
}
Mesh mesh = new Mesh();
mesh.name = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.name.Replace(".SkinnedMesh", ".Mesh"); ;
mesh.vertices = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.vertices;
mesh.triangles = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.triangles;
mesh.normals = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.normals;
mesh.uv = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.uv;
mesh.uv2 = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.uv2;
mesh.bounds = skin.GetComponent<SkinnedMeshRenderer>().sharedMesh.bounds;
ScriptableObjectUtility.CreateAsset(mesh, "Meshes/" + skin.gameObject.name + ".Mesh");
#endif
}
if (skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial != null && GUILayout.Button("Generate Material Asset"))
{
#if UNITY_EDITOR
Material material = new Material(skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial);
material.CopyPropertiesFromMaterial(skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial);
skin.GetComponent<SkinnedMeshRenderer>().sharedMaterial = material;
if (!Directory.Exists("Assets/Materials"))
{
AssetDatabase.CreateFolder("Assets", "Materials");
AssetDatabase.Refresh();
}
AssetDatabase.CreateAsset(material, "Assets/Materials/" + material.mainTexture.name + ".mat");
Debug.Log("Created material " + material.mainTexture.name + " for " + skin.gameObject.name);
#endif
}
}
private void OnSceneGUI()
{
if (skin != null && skin.GetComponent<SkinnedMeshRenderer>().sharedMesh != null
&& skin.controlPoints != null && skin.controlPoints.Length > 0 && skin.points != null)
{
Event e = Event.current;
Handles.matrix = skin.transform.localToWorldMatrix;
EditorGUI.BeginChangeCheck();
Ray r = HandleUtility.GUIPointToWorldRay(e.mousePosition);
Vector2 mousePos = r.origin;
float selectDistance = HandleUtility.GetHandleSize(mousePos) * baseSelectDistance;
#region Draw vertex handles
Handles.color = handleColor;
for (int i = 0; i < skin.controlPoints.Length; i++)
{
if (Handles.Button(skin.points.GetPoint(skin.controlPoints[i]), Quaternion.identity, selectDistance, selectDistance, Handles.CircleCap))
{
selectedIndex = i;
}
if (selectedIndex == i)
{
EditorGUI.BeginChangeCheck();
skin.controlPoints[i].position = Handles.DoPositionHandle(skin.points.GetPoint(skin.controlPoints[i]), Quaternion.identity);
if (EditorGUI.EndChangeCheck())
{
skin.points.SetPoint(skin.controlPoints[i]);
Undo.RecordObject(skin, "Changed Control Point");
Undo.RecordObject(skin.points, "Changed Control Point");
EditorUtility.SetDirty(this);
}
}
}
#endregion Draw vertex handles
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using BohFoundation.ApplicantsRepository.Repositories.Implementations;
using BohFoundation.AzureStorage.TableStorage.Implementations.Essay.Entities;
using BohFoundation.AzureStorage.TableStorage.Interfaces.Essay;
using BohFoundation.AzureStorage.TableStorage.Interfaces.Essay.Helpers;
using BohFoundation.Domain.Dtos.Applicant.Essay;
using BohFoundation.Domain.Dtos.Applicant.Notifications;
using BohFoundation.Domain.Dtos.Common.AzureQueuryObjects;
using BohFoundation.Domain.EntityFrameworkModels.Applicants;
using BohFoundation.Domain.EntityFrameworkModels.Common;
using BohFoundation.Domain.EntityFrameworkModels.Persons;
using BohFoundation.EntityFrameworkBaseClass;
using BohFoundation.TestHelpers;
using EntityFramework.Extensions;
using FakeItEasy;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace BohFoundation.ApplicantsRepository.Tests.IntegrationTests
{
[TestClass]
public class ApplicantsEssayRepositoryIntegrationTests
{
private static IEssayRowKeyGenerator _rowKeyGenerator;
private static IAzureEssayRepository _azureAzureEssayRepository;
private static ApplicantsEssayRepository _applicantsEssayRepository;
private static ApplicantsesNotificationRepository _applicantsesNotification;
[ClassInitialize]
public static void InitializeClass(TestContext ctx)
{
Setup();
FirstTestOfNotifications();
FirstUpsert();
SecondUpsert();
SecondTestOfNotifications();
}
#region SettingUp
private static void Setup()
{
TestHelpersCommonFields.InitializeFields();
TestHelpersCommonFakes.InitializeFakes();
ApplicantsGuid = Guid.NewGuid();
Prompt = "prompt" + ApplicantsGuid;
TitleOfEssay = "title" + ApplicantsGuid;
_azureAzureEssayRepository = A.Fake<IAzureEssayRepository>();
_rowKeyGenerator = A.Fake<IEssayRowKeyGenerator>();
CreateEssayTopicAndApplicant();
SetupFakes();
_applicantsesNotification = new ApplicantsesNotificationRepository(TestHelpersCommonFields.DatabaseName,
TestHelpersCommonFakes.ClaimsInformationGetters, TestHelpersCommonFakes.DeadlineUtilities);
_applicantsEssayRepository = new ApplicantsEssayRepository(TestHelpersCommonFields.DatabaseName,
TestHelpersCommonFakes.ClaimsInformationGetters, _azureAzureEssayRepository, _rowKeyGenerator);
}
private static void CreateEssayTopicAndApplicant()
{
var random = new Random();
GraduatingYear = random.Next();
var subject = new EssayTopic
{
EssayPrompt = Prompt,
TitleOfEssay = TitleOfEssay,
RevisionDateTime = DateTime.UtcNow
};
var subject2 = new EssayTopic
{
EssayPrompt = Prompt + 2,
TitleOfEssay = TitleOfEssay + 2,
RevisionDateTime = DateTime.UtcNow
};
var subject3 = new EssayTopic
{
EssayPrompt = "SHOULD NOT SHOW UP IN LIST",
TitleOfEssay = "REALLY SHOULDN't SHOW up",
RevisionDateTime = DateTime.UtcNow,
};
var graduatingYear = new GraduatingClass
{
GraduatingYear = GraduatingYear,
EssayTopics = new List<EssayTopic> { subject, subject2 }
};
var applicant = new Applicant
{
Person = new Person { Guid = ApplicantsGuid, DateCreated = DateTime.UtcNow },
ApplicantPersonalInformation =
new ApplicantPersonalInformation
{
GraduatingClass = graduatingYear,
Birthdate = DateTime.UtcNow,
LastUpdated = DateTime.UtcNow
}
};
using (var context = GetRootContext())
{
context.EssayTopics.Add(subject3);
context.GraduatingClasses.Add(graduatingYear);
context.Applicants.Add(applicant);
context.EssayTopics.Add(subject);
context.SaveChanges();
EssayTopicId = context.EssayTopics.First(topic => topic.EssayPrompt == Prompt).Id;
EssayTopicId2 = context.EssayTopics.First(topic => topic.EssayPrompt == Prompt + 2).Id;
}
}
private static int EssayTopicId2 { get; set; }
private static void SetupFakes()
{
RowKey = "THISISTHEROWKEYFORTHEAPPLICANT";
A.CallTo(() => TestHelpersCommonFakes.ClaimsInformationGetters.GetApplicantsGraduatingYear())
.Returns(GraduatingYear);
A.CallTo(() => TestHelpersCommonFakes.ClaimsInformationGetters.GetUsersGuid()).Returns(ApplicantsGuid);
A.CallTo(() => _rowKeyGenerator.CreateRowKeyForEssay(ApplicantsGuid, EssayTopicId)).Returns(RowKey);
}
private static string RowKey { get; set; }
private static int GraduatingYear { get; set; }
private static string TitleOfEssay { get; set; }
private static string Prompt { get; set; }
private static Guid ApplicantsGuid { get; set; }
#endregion
#region FirstNotifications
private static void FirstTestOfNotifications()
{
FirstNotificationResult = _applicantsesNotification.GetApplicantNotifications();
}
private static ApplicantNotificationsDto FirstNotificationResult { get; set; }
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_FirstGetNotifications_Should_Have_Two_EssayTopics()
{
Assert.AreEqual(2, FirstNotificationResult.EssayNotifications.Count);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_FirstGetNotifications_EssayTopics_Should_Have_No_LastUpdated()
{
foreach (var essayTopic in FirstNotificationResult.EssayNotifications)
{
Assert.IsNull(essayTopic.RevisionDateTime);
}
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_FirstGetNotifications_EssayTopics_Should_Have_Right_EssayTopic()
{
foreach (var essayTopic in FirstNotificationResult.EssayNotifications)
{
if (essayTopic.EssayPrompt == Prompt)
{
Assert.AreEqual(TitleOfEssay, essayTopic.TitleOfEssay);
}
else
{
Assert.AreEqual(TitleOfEssay + 2, essayTopic.TitleOfEssay);
}
}
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_FirstGetNotifications_EssayTopics_Should_Have_Right_Ids()
{
foreach (var essayTopic in FirstNotificationResult.EssayNotifications)
{
Assert.AreEqual(essayTopic.EssayPrompt == Prompt ? EssayTopicId : EssayTopicId2, essayTopic.EssayTopicId);
}
}
#endregion
#region FirstUpsert
private static void FirstUpsert()
{
Essay = "Essay";
var dto = new EssayDto {Essay = Essay + 1, EssayPrompt = Prompt, EssayTopicId = EssayTopicId};
_applicantsEssayRepository.UpsertEssay(dto);
using (var context = GetRootContext())
{
EssayUpsertResult1 =
context.Essays.First(
essay => essay.EssayTopic.Id == EssayTopicId && essay.Applicant.Person.Guid == ApplicantsGuid);
}
}
private static Essay EssayUpsertResult1 { get; set; }
private static string Essay { get; set; }
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_FirstUpsert_Should_Have_6_Characters()
{
Assert.AreEqual(6, EssayUpsertResult1.CharacterLength);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_FirstUpsert_Should_Have_Have_RecentUpdated()
{
TestHelpersTimeAsserts.RecentTime(EssayUpsertResult1.RevisionDateTime);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_FirstUpsert_Should_Have_Have_Correct_RowKey()
{
Assert.AreEqual(RowKey, EssayUpsertResult1.RowKey);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_FirstUpsert_Should_Have_Have_Correct_PartitionKey()
{
Assert.AreEqual(GraduatingYear.ToString(), EssayUpsertResult1.PartitionKey);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_FirstUpsert_Should_Have_Positive_Id()
{
TestHelpersCommonAsserts.IsGreaterThanZero(EssayUpsertResult1.Id);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_FirstUpsert_Should_Call_CreateRowKey()
{
A.CallTo(() => _rowKeyGenerator.CreateRowKeyForEssay(ApplicantsGuid, EssayTopicId)).MustHaveHappened();
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_FirstUpsert_Should_Call_UpsertEssay()
{
//Not checking time. It just isn't coming up. I did an in class check to see if it worked. It did.
A.CallTo(() => _azureAzureEssayRepository.UpsertEssay(A<EssayAzureTableEntityDto>
.That.Matches(x =>
x.Essay == Essay + 1 &&
x.EssayPrompt == Prompt &&
x.EssayTopicId == EssayTopicId &&
x.PartitionKey == GraduatingYear.ToString() &&
x.RowKey == RowKey
))).MustHaveHappened();
}
#endregion
#region SecondUpsert
private static void SecondUpsert()
{
var dto = new EssayDto {Essay = Essay + Essay + Essay, EssayPrompt = Prompt, EssayTopicId = EssayTopicId};
_applicantsEssayRepository.UpsertEssay(dto);
using (var context = GetRootContext())
{
EssayUpsertResult2 =
context.Essays.First(
essay => essay.EssayTopic.Id == EssayTopicId && essay.Applicant.Person.Guid == ApplicantsGuid);
}
}
private static Essay EssayUpsertResult2 { get; set; }
private static int EssayTopicId { get; set; }
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Have_15_Characters()
{
Assert.AreEqual(15, EssayUpsertResult2.CharacterLength);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Have_Have_RecentUpdated_More_Recent_Than_First()
{
TestHelpersTimeAsserts.IsGreaterThanOrEqual(EssayUpsertResult2.RevisionDateTime,
EssayUpsertResult1.RevisionDateTime);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Have_Have_Correct_RowKey()
{
Assert.AreEqual(RowKey, EssayUpsertResult2.RowKey);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Have_Have_Correct_PartitionKey()
{
Assert.AreEqual(GraduatingYear.ToString(), EssayUpsertResult2.PartitionKey);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Have_Equal_Id_To_First()
{
Assert.AreEqual(EssayUpsertResult1.Id, EssayUpsertResult2.Id);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Call_CreateRowKey()
{
A.CallTo(() => _rowKeyGenerator.CreateRowKeyForEssay(ApplicantsGuid, EssayTopicId))
.MustHaveHappened(Repeated.AtLeast.Times(3));
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_SecondUpsert_Should_Call_UpsertEssay()
{
//Not checking time. It just isn't coming up. I did an in class check to see if it worked. It did.
A.CallTo(() => _azureAzureEssayRepository.UpsertEssay(A<EssayAzureTableEntityDto>
.That.Matches(x =>
x.Essay == Essay + Essay + Essay &&
x.EssayPrompt == Prompt &&
x.EssayTopicId == EssayTopicId &&
x.PartitionKey == GraduatingYear.ToString() &&
x.RowKey == RowKey
))).MustHaveHappened();
}
#endregion
#region SecondNotifications
private static void SecondTestOfNotifications()
{
SecondNotificationResult = _applicantsesNotification.GetApplicantNotifications();
}
private static ApplicantNotificationsDto SecondNotificationResult { get; set; }
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_SecondGetNotifications_Should_Have_Two_EssayTopics()
{
Assert.AreEqual(2, SecondNotificationResult.EssayNotifications.Count);
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_SecondGetNotifications_EssayTopics_Should_Have_No_LastUpdated()
{
foreach (var essayTopic in SecondNotificationResult.EssayNotifications)
{
if (essayTopic.EssayPrompt == Prompt)
{
Assert.AreEqual(EssayUpsertResult2.RevisionDateTime, essayTopic.RevisionDateTime);
}
else
{
Assert.IsNull(essayTopic.RevisionDateTime);
}
}
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_SecondGetNotifications_EssayTopics_Should_Have_Right_EssayTopic()
{
foreach (var essayTopic in SecondNotificationResult.EssayNotifications)
{
if (essayTopic.EssayPrompt == Prompt)
{
Assert.AreEqual(TitleOfEssay, essayTopic.TitleOfEssay);
}
else
{
Assert.AreEqual(TitleOfEssay + 2, essayTopic.TitleOfEssay);
}
}
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsNotificationRepository_SecondGetNotifications_EssayTopics_Should_Have_Right_Ids()
{
foreach (var essayTopic in SecondNotificationResult.EssayNotifications)
{
Assert.AreEqual(essayTopic.EssayPrompt == Prompt ? EssayTopicId : EssayTopicId2, essayTopic.EssayTopicId);
}
}
#endregion
#region Utilities
private static DatabaseRootContext GetRootContext()
{
return new DatabaseRootContext(TestHelpersCommonFields.DatabaseName);
}
[ClassCleanup]
public static void CleanDb()
{
using (var context = new DatabaseRootContext(TestHelpersCommonFields.DatabaseName))
{
context.Essays.Where(essay => essay.Id > 0).Delete();
context.EssayTopics.Where(essayTopic => essayTopic.Id > 0).Delete();
context.ApplicantPersonalInformations.Where(info => info.Id > 0).Delete();
context.GraduatingClasses.Where(gradClass => gradClass.Id > 0).Delete();
}
}
#endregion
#region GetEssay
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_GetEssay_Should_Call_CreateRowKeyForEssay()
{
GetEssay();
A.CallTo(() => _rowKeyGenerator.CreateRowKeyForEssay(ApplicantsGuid, EssayTopicId)).MustHaveHappened();
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_GetEssay_Should_Call_AzureEssayRepository()
{
GetEssay();
A.CallTo(
() =>
_azureAzureEssayRepository.GetEssay(
A<AzureTableStorageEntityKeyDto>.That.Matches(
x => x.PartitionKey == GraduatingYear.ToString() && x.RowKey == RowKey))).MustHaveHappened();
}
[TestMethod, TestCategory("Integration")]
public void ApplicantsEssayRepository_GetEssay_Should_Return_Whatever_TheAzureRepoReturns()
{
var essayDto = new EssayDto();
A.CallTo(() => _azureAzureEssayRepository.GetEssay(A<AzureTableStorageEntityKeyDto>.Ignored))
.Returns(essayDto);
Assert.AreSame(essayDto, GetEssay());
}
private EssayDto GetEssay()
{
return _applicantsEssayRepository.GetEssay(EssayTopicId);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Web.UI;
using System.Web.UI.WebControls;
using Vevo;
using Vevo.Domain.DataInterfaces;
using Vevo.Shared.Utilities;
using Vevo.WebAppLib;
using Vevo.Base.Domain;
public partial class Components_SearchFilterNew : Vevo.WebUI.International.BaseLanguageUserControl, ISearchFilter
{
private NameValueCollection FieldTypes
{
get
{
if (ViewState["FieldTypes"] == null)
ViewState["FieldTypes"] = new NameValueCollection();
return (NameValueCollection) ViewState["FieldTypes"];
}
}
private string GenerateShowHideScript( bool textPanel, bool boolPanel, bool valueRangePanel, bool dateRangePanel )
{
string script;
if (textPanel)
script = String.Format( "document.getElementById('{0}').style.display = '';", uxTextPanel.ClientID );
else
script = String.Format( "document.getElementById('{0}').style.display = 'none';", uxTextPanel.ClientID );
if (boolPanel)
script += String.Format( "document.getElementById('{0}').style.display = '';", uxBooleanPanel.ClientID );
else
script += String.Format( "document.getElementById('{0}').style.display = 'none';", uxBooleanPanel.ClientID );
if (valueRangePanel)
script += String.Format( "document.getElementById('{0}').style.display = '';", uxValueRangePanel.ClientID );
else
script += String.Format( "document.getElementById('{0}').style.display = 'none';", uxValueRangePanel.ClientID );
if (dateRangePanel)
script += String.Format( "document.getElementById('{0}').style.display = '';", uxDateRangePanel.ClientID );
else
script += String.Format( "document.getElementById('{0}').style.display = 'none';", uxDateRangePanel.ClientID );
return script;
}
private void ShowTextFilterInput()
{
uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "" );
uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
}
private void ShowBooleanFilterInput()
{
uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "" );
uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
}
private void ShowValueRangeFilterInput()
{
uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "" );
uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
}
private void ShowDateRangeFilterInput()
{
uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "" );
}
private void HideAllInput()
{
uxTextPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxBooleanPanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxValueRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
uxDateRangePanel.Style.Add( HtmlTextWriterStyle.Display, "none" );
}
private void RegisterDropDownPostback()
{
string script = "if(this.value == ''){ javascript:__doPostBack('" + uxFilterDrop.UniqueID + "',''); }";
foreach (ListItem item in uxFilterDrop.Items)
{
switch (ParseSearchType( FieldTypes[item.Value] ))
{
case SearchFilter.SearchFilterType.Text:
script += "if(this.value == '" + item.Value + "'){" + GenerateShowHideScript( true, false, false, false ) + "}";
break;
case SearchFilter.SearchFilterType.Boolean:
script += "if(this.value == '" + item.Value + "'){" + GenerateShowHideScript( false, true, false, false ) + "}";
break;
case SearchFilter.SearchFilterType.ValueRange:
script += "if(this.value == '" + item.Value + "'){" + GenerateShowHideScript( false, false, true, false ) + "}";
break;
case SearchFilter.SearchFilterType.Date:
script += "if(this.value == '" + item.Value + "'){" + GenerateShowHideScript( false, false, false, true ) + "}";
break;
}
}
script += "document.getElementById( '" + uxValueText.ClientID + "' ).value = '';";
script += "document.getElementById( '" + uxBooleanDrop.ClientID + "' ).value = 'True';";
script += "document.getElementById( '" + uxLowerText.ClientID + "' ).value = '';";
script += "document.getElementById( '" + uxUpperText.ClientID + "' ).value = '';";
script += "document.getElementById( '" + uxStartDateText.ClientID + "' ).value = '';";
script += "document.getElementById( '" + uxEndDateText.ClientID + "' ).value = '';";
uxFilterDrop.Attributes.Add( "onchange", script );
}
private string GetFilterType( Type dataType )
{
string type;
if (dataType == Type.GetType( "System.Byte" ) ||
dataType == Type.GetType( "System.SByte" ) ||
dataType == Type.GetType( "System.Char" ) ||
dataType == Type.GetType( "System.String" ))
{
type = SearchFilter.SearchFilterType.Text.ToString();
}
else if (dataType == Type.GetType( "System.Boolean" ))
{
type = SearchFilter.SearchFilterType.Boolean.ToString();
}
else if (
dataType == Type.GetType( "System.Decimal" ) ||
dataType == Type.GetType( "System.Double" ) ||
dataType == Type.GetType( "System.Int16" ) ||
dataType == Type.GetType( "System.Int32" ) ||
dataType == Type.GetType( "System.Int64" ) ||
dataType == Type.GetType( "System.UInt16" ) ||
dataType == Type.GetType( "System.UInt32" ) ||
dataType == Type.GetType( "System.UInt64" ))
{
type = SearchFilter.SearchFilterType.ValueRange.ToString();
}
else if (dataType == Type.GetType( "System.DateTime" ))
{
type = SearchFilter.SearchFilterType.Date.ToString();
}
else
{
type = String.Empty;
}
return type;
}
private SearchFilter.SearchFilterType ParseSearchType( string searchFilterType )
{
SearchFilter.SearchFilterType type;
if (String.Compare( searchFilterType, SearchFilter.SearchFilterType.Text.ToString(), true ) == 0)
type = SearchFilter.SearchFilterType.Text;
else if (String.Compare( searchFilterType, SearchFilter.SearchFilterType.Boolean.ToString(), true ) == 0)
type = SearchFilter.SearchFilterType.Boolean;
else if (String.Compare( searchFilterType, SearchFilter.SearchFilterType.ValueRange.ToString(), true ) == 0)
type = SearchFilter.SearchFilterType.ValueRange;
else if (String.Compare( searchFilterType, SearchFilter.SearchFilterType.Date.ToString(), true ) == 0)
type = SearchFilter.SearchFilterType.Date;
else
type = SearchFilter.SearchFilterType.None;
return type;
}
private void RemoveSearchFilter()
{
SearchFilterObj = SearchFilter.GetFactory()
.Create();
uxMessageLabel.Text = String.Empty;
}
private void TieTextBoxesWithButtons()
{
WebUtilities.TieButton( this.Page, uxValueText, uxTextSearchImageButton );
WebUtilities.TieButton( this.Page, uxLowerText, uxValueRangeSearchImageButton );
WebUtilities.TieButton( this.Page, uxUpperText, uxValueRangeSearchImageButton );
WebUtilities.TieButton( this.Page, uxStartDateText, uxDateRangeImageButton );
WebUtilities.TieButton( this.Page, uxEndDateText, uxDateRangeImageButton );
}
private void DisplayTextSearchMessage( string fieldName, string value )
{
if (!String.IsNullOrEmpty( value ))
{
uxMessageLabel.Text =
String.Format( Resources.SearchFilterMessages.TextMessage,
value, fieldName );
}
}
private void DisplayBooleanSearchMessage( string fieldName, string value )
{
bool boolValue;
if (Boolean.TryParse( value, out boolValue ))
{
uxMessageLabel.Text =
String.Format( Resources.SearchFilterMessages.BooleanMessage,
ConvertUtilities.ToYesNo( boolValue ), fieldName );
}
}
private void DisplayValueRangeMessage( string fieldName, string value1, string value2 )
{
if (!String.IsNullOrEmpty( value1 ) && !String.IsNullOrEmpty( value2 ))
{
uxMessageLabel.Text =
String.Format( Resources.SearchFilterMessages.ValueRangeBothMessage,
value1, value2, fieldName );
}
else if (!String.IsNullOrEmpty( value1 ))
{
uxMessageLabel.Text =
String.Format( Resources.SearchFilterMessages.ValueRangeLowerOnlyMessage,
value1, fieldName );
}
else if (!String.IsNullOrEmpty( value2 ))
{
uxMessageLabel.Text =
String.Format( Resources.SearchFilterMessages.ValueRangeUpperOnlyMessage,
value2, fieldName );
}
}
private void RestoreControls()
{
uxFilterDrop.SelectedValue = SearchFilterObj.FieldName;
switch (SearchFilterObj.FilterType)
{
case SearchFilter.SearchFilterType.Text:
uxValueText.Text = SearchFilterObj.Value1;
DisplayTextSearchMessage( SearchFilterObj.FieldName, SearchFilterObj.Value1 );
break;
case SearchFilter.SearchFilterType.Boolean:
uxBooleanDrop.SelectedValue = ConvertUtilities.ToBoolean( SearchFilterObj.Value1 ).ToString();
DisplayBooleanSearchMessage( SearchFilterObj.FieldName, SearchFilterObj.Value1 );
break;
case SearchFilter.SearchFilterType.ValueRange:
uxLowerText.Text = SearchFilterObj.Value1;
uxUpperText.Text = SearchFilterObj.Value2;
DisplayValueRangeMessage( SearchFilterObj.FieldName, SearchFilterObj.Value1, SearchFilterObj.Value2 );
break;
case SearchFilter.SearchFilterType.Date:
uxStartDateText.Text = ConvertUtilities.ToDateTime( SearchFilterObj.Value1 ).ToString( "MMMM d,yyyy" );
uxEndDateText.Text = ConvertUtilities.ToDateTime( SearchFilterObj.Value2 ).ToString( "MMMM d,yyyy" );
DisplayValueRangeMessage( SearchFilterObj.FieldName, uxStartDateText.Text, uxEndDateText.Text );
break;
}
}
private void ShowSelectedInput( SearchFilter.SearchFilterType filterType )
{
switch (filterType)
{
case SearchFilter.SearchFilterType.Text:
ShowTextFilterInput();
break;
case SearchFilter.SearchFilterType.Boolean:
ShowBooleanFilterInput();
break;
case SearchFilter.SearchFilterType.ValueRange:
ShowValueRangeFilterInput();
break;
case SearchFilter.SearchFilterType.Date:
ShowDateRangeFilterInput();
break;
default:
HideAllInput();
RemoveSearchFilter();
break;
}
}
private bool IsShowAllSelected()
{
return String.IsNullOrEmpty( uxFilterDrop.SelectedValue );
}
private void LoadDefaultFromQuery()
{
ShowSelectedInput( SearchFilterObj.FilterType );
RestoreControls();
}
protected void Page_Load( object sender, EventArgs e )
{
TieTextBoxesWithButtons();
if (!IsPostBack)
{
LoadDefaultFromQuery();
}
}
protected void uxFilterDrop_SelectedIndexChanged( object sender, EventArgs e )
{
ShowSelectedInput( ParseSearchType( FieldTypes[uxFilterDrop.SelectedValue] ) );
if (IsShowAllSelected())
OnBubbleEvent( e );
}
protected void uxTextSearchButton_Click( object sender, EventArgs e )
{
PopulateValueFilter(
SearchFilter.SearchFilterType.Text,
uxFilterDrop.SelectedValue,
uxValueText.Text,
e );
}
protected void uxBooleanSearchButton_Click( object sender, EventArgs e )
{
PopulateValueFilter(
SearchFilter.SearchFilterType.Boolean,
uxFilterDrop.SelectedValue,
uxBooleanDrop.SelectedValue,
e );
}
protected void uxValueRangeSearchButton_Click( object sender, EventArgs e )
{
PopulateValueRangeFilter(
SearchFilter.SearchFilterType.ValueRange,
uxFilterDrop.SelectedValue,
uxLowerText.Text,
uxUpperText.Text,
e );
}
protected void uxDateRangeButton_Click( object sender, EventArgs e )
{
PopulateValueRangeFilter(
SearchFilter.SearchFilterType.Date,
uxFilterDrop.SelectedValue,
uxStartDateText.Text,
uxEndDateText.Text,
e );
}
private void PopulateValueFilter( SearchFilter.SearchFilterType typeField,
string value, string val1, EventArgs e )
{
SearchFilterObj = SearchFilter.GetFactory()
.WithFilterType( typeField )
.WithFieldName( value )
.WithValue1( val1 )
.Create();
if (typeField == SearchFilter.SearchFilterType.Text)
DisplayTextSearchMessage( SearchFilterObj.FieldName, SearchFilterObj.Value1 );
else if (typeField == SearchFilter.SearchFilterType.Boolean)
DisplayBooleanSearchMessage( SearchFilterObj.FieldName, SearchFilterObj.Value1 );
// Propagate event to parent
OnBubbleEvent( e );
}
private void PopulateValueRangeFilter( SearchFilter.SearchFilterType typeField,
string value, string val1, string val2, EventArgs e )
{
SearchFilterObj = SearchFilter.GetFactory()
.WithFilterType( typeField )
.WithFieldName( value )
.WithValue1( val1 )
.WithValue2( val2 )
.Create();
DisplayValueRangeMessage( SearchFilterObj.FieldName, SearchFilterObj.Value1, SearchFilterObj.Value2 );
// Propagate event to parent
OnBubbleEvent( e );
}
public void SetUpSchema(
IList<TableSchemaItem> columnList,
params string[] excludingColumns )
{
uxFilterDrop.Items.Clear();
FieldTypes.Clear();
uxFilterDrop.Items.Add( new ListItem( Resources.SearchFilterMessages.FilterShowAll, String.Empty ) );
FieldTypes[Resources.SearchFilterMessages.FilterShowAll] = SearchFilter.SearchFilterType.None.ToString();
for (int i = 0; i < columnList.Count; i++)
{
if (!StringUtilities.IsStringInArray( excludingColumns, columnList[i].ColumnName, true ))
{
string type = GetFilterType( columnList[i].DataType );
if (!String.IsNullOrEmpty( type ))
{
uxFilterDrop.Items.Add( columnList[i].ColumnName );
FieldTypes[columnList[i].ColumnName] = type;
}
}
}
RegisterDropDownPostback();
}
public void SetUpSchema(
IList<TableSchemaItem> columnList,
NameValueCollection renameList,
params string[] excludingColumns )
{
SetUpSchema( columnList, excludingColumns );
for (int i = 0; i < renameList.Count; i++)
{
for (int j = 0; j < columnList.Count; j++)
{
if (renameList.AllKeys[i].ToString() == columnList[j].ColumnName)
{
string type = GetFilterType( columnList[j].DataType );
if (!String.IsNullOrEmpty( type ))
{
uxFilterDrop.Items[j + 1].Text = renameList[i].ToString();
uxFilterDrop.Items[j + 1].Value = renameList.AllKeys[i].ToString();
FieldTypes[renameList[i].ToString()] = type;
}
}
}
}
RegisterDropDownPostback();
}
public SearchFilter SearchFilterObj
{
get
{
if (ViewState["SearchFilter"] == null)
return SearchFilter.GetFactory()
.Create();
else
return (SearchFilter) ViewState["SearchFilter"];
}
set
{
ViewState["SearchFilter"] = value;
}
}
public void ClearFilter()
{
RemoveSearchFilter();
uxFilterDrop.SelectedValue = "";
HideAllInput();
}
public void UpdateBrowseQuery( UrlQuery urlQuery )
{
urlQuery.RemoveQuery( "Type" );
urlQuery.RemoveQuery( "FieldName" );
urlQuery.RemoveQuery( "FieldValue" );
urlQuery.RemoveQuery( "Value1" );
urlQuery.RemoveQuery( "Value2" );
if (SearchFilterObj.FilterType != SearchFilter.SearchFilterType.None)
{
urlQuery.AddQuery( "Type", SearchFilterObj.FilterType.ToString() );
urlQuery.AddQuery( "FieldName", SearchFilterObj.FieldName );
urlQuery.AddQuery( "Value1", SearchFilterObj.Value1 );
if (!String.IsNullOrEmpty( SearchFilterObj.Value2 ))
urlQuery.AddQuery( "Value2", SearchFilterObj.Value2 );
}
}
}
|
//---------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.Windows.Automation.Peers;
using System.Windows.Media;
using System.Windows.Threading;
using MS.Internal.KnownBoxes;
namespace System.Windows.Controls.Primitives
{
/// <summary>
/// StatusBar is a visual indicator of the operational status of an application and/or
/// its components running in a window. StatusBar control consists of a series of zones
/// on a band that can display text, graphics, or other rich content. The control can
/// group items within these zones to emphasize relational similarities or functional
/// connections. The StatusBar can accommodate multiple sets of UI or functionality that
/// can be chosen even within the same application.
/// </summary>
[StyleTypedProperty(Property = "ItemContainerStyle", StyleTargetType = typeof(StatusBarItem))]
public class StatusBar : ItemsControl
{
//-------------------------------------------------------------------
//
// Constructors
//
//-------------------------------------------------------------------
#region Constructors
static StatusBar()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(StatusBar), new FrameworkPropertyMetadata(typeof(StatusBar)));
_dType = DependencyObjectType.FromSystemTypeInternal(typeof(StatusBar));
IsTabStopProperty.OverrideMetadata(typeof(StatusBar), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox));
ItemsPanelTemplate template = new ItemsPanelTemplate(new FrameworkElementFactory(typeof(DockPanel)));
template.Seal();
ItemsPanelProperty.OverrideMetadata(typeof(StatusBar), new FrameworkPropertyMetadata(template));
}
#endregion
#region Public Properties
/// <summary>
/// DependencyProperty for ItemContainerTemplateSelector property.
/// </summary>
public static readonly DependencyProperty ItemContainerTemplateSelectorProperty =
MenuBase.ItemContainerTemplateSelectorProperty.AddOwner(
typeof(StatusBar),
new FrameworkPropertyMetadata(new DefaultItemContainerTemplateSelector()));
/// <summary>
/// DataTemplateSelector property which provides the DataTemplate to be used to create an instance of the ItemContainer.
/// </summary>
public ItemContainerTemplateSelector ItemContainerTemplateSelector
{
get { return (ItemContainerTemplateSelector)GetValue(ItemContainerTemplateSelectorProperty); }
set { SetValue(ItemContainerTemplateSelectorProperty, value); }
}
/// <summary>
/// DependencyProperty for UsesItemContainerTemplate property.
/// </summary>
public static readonly DependencyProperty UsesItemContainerTemplateProperty =
MenuBase.UsesItemContainerTemplateProperty.AddOwner(typeof(StatusBar));
/// <summary>
/// UsesItemContainerTemplate property which says whether the ItemContainerTemplateSelector property is to be used.
/// </summary>
public bool UsesItemContainerTemplate
{
get { return (bool)GetValue(UsesItemContainerTemplateProperty); }
set { SetValue(UsesItemContainerTemplateProperty, value); }
}
#endregion
//-------------------------------------------------------------------
//
// Protected Methods
//
//-------------------------------------------------------------------
#region Protected Methods
private object _currentItem;
/// <summary>
/// Return true if the item is (or is eligible to be) its own ItemUI
/// </summary>
protected override bool IsItemItsOwnContainerOverride(object item)
{
bool ret = (item is StatusBarItem) || (item is Separator);
if (!ret)
{
_currentItem = item;
}
return ret;
}
protected override DependencyObject GetContainerForItemOverride()
{
object currentItem = _currentItem;
_currentItem = null;
if (UsesItemContainerTemplate)
{
DataTemplate itemContainerTemplate = ItemContainerTemplateSelector.SelectTemplate(currentItem, this);
if (itemContainerTemplate != null)
{
object itemContainer = itemContainerTemplate.LoadContent();
if (itemContainer is StatusBarItem || itemContainer is Separator)
{
return itemContainer as DependencyObject;
}
else
{
throw new InvalidOperationException(SR.Get(SRID.InvalidItemContainer, this.GetType().Name, typeof(StatusBarItem).Name, typeof(Separator).Name, itemContainer));
}
}
}
return new StatusBarItem();
}
/// <summary>
/// Prepare the element to display the item. This may involve
/// applying styles, setting bindings, etc.
/// </summary>
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);
Separator separator = element as Separator;
if (separator != null)
{
bool hasModifiers;
BaseValueSourceInternal vs = separator.GetValueSource(StyleProperty, null, out hasModifiers);
if (vs <= BaseValueSourceInternal.ImplicitReference)
separator.SetResourceReference(StyleProperty, SeparatorStyleKey);
separator.DefaultStyleKey = SeparatorStyleKey;
}
}
/// <summary>
/// Determine whether the ItemContainerStyle/StyleSelector should apply to the container
/// </summary>
/// <returns>false if item is a Separator, otherwise return true</returns>
protected override bool ShouldApplyItemContainerStyle(DependencyObject container, object item)
{
if (item is Separator)
{
return false;
}
else
{
return base.ShouldApplyItemContainerStyle(container, item);
}
}
#endregion
#region Accessibility
/// <summary>
/// Creates AutomationPeer (<see cref="UIElement.OnCreateAutomationPeer"/>)
/// </summary>
protected override AutomationPeer OnCreateAutomationPeer()
{
return new StatusBarAutomationPeer(this);
}
#endregion
#region DTypeThemeStyleKey
// Returns the DependencyObjectType for the registered ThemeStyleKey's default
// value. Controls will override this method to return approriate types.
internal override DependencyObjectType DTypeThemeStyleKey
{
get { return _dType; }
}
private static DependencyObjectType _dType;
#endregion DTypeThemeStyleKey
#region ItemsStyleKey
/// <summary>
/// Resource Key for the SeparatorStyle
/// </summary>
public static ResourceKey SeparatorStyleKey
{
get
{
return SystemResourceKey.StatusBarSeparatorStyleKey;
}
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Html;
namespace wwtlib
{
public class PlotTile : Tile
{
bool topDown = true;
protected PositionTexture[] bounds;
protected bool backslash = false;
List<PositionTexture> vertexList = null;
List<Triangle>[] childTriangleList = null;
protected float[] demArray;
protected void ComputeBoundingSphere()
{
InitializeGrids();
TopLeft = bounds[0 + 3 * 0].Position.Copy();
BottomRight = bounds[2 + 3 * 2].Position.Copy();
TopRight = bounds[2 + 3 * 0].Position.Copy();
BottomLeft = bounds[0 + 3 * 2].Position.Copy();
CalcSphere();
}
public override void RenderPart(RenderContext renderContext, int part, double opacity, bool combine)
{
if (renderContext.gl != null)
{
//todo draw in WebGL
}
else
{
if (part == 0)
{
foreach(Star star in stars)
{
double radDec = 25 / Math.Pow(1.6, star.Magnitude);
Planets.DrawPointPlanet(renderContext, star.Position, radDec, star.Col, false);
}
}
}
}
WebFile webFile;
public override void RequestImage()
{
if (!Downloading && !ReadyToRender)
{
Downloading = true;
webFile = new WebFile(Util.GetProxiedUrl(this.URL));
webFile.OnStateChange = FileStateChange;
webFile.Send();
}
}
public void FileStateChange()
{
if(webFile.State == StateType.Error)
{
Downloading = false;
ReadyToRender = false;
errored = true;
RequestPending = false;
TileCache.RemoveFromQueue(this.Key, true);
}
else if(webFile.State == StateType.Received)
{
texReady = true;
Downloading = false;
errored = false;
ReadyToRender = texReady && (DemReady || !demTile);
RequestPending = false;
TileCache.RemoveFromQueue(this.Key, true);
LoadData(webFile.GetText());
}
}
List<Star> stars = new List<Star>();
private void LoadData(string data)
{
string[] rows = data.Replace("\r\n","\n").Split("\n");
bool firstRow = true;
PointType type = PointType.Move;
Star star = null;
foreach (string row in rows)
{
if (firstRow)
{
firstRow = false;
continue;
}
if (row.Trim().Length > 5)
{
star = new Star(row);
star.Position = Coordinates.RADecTo3dAu(star.RA, star.Dec, 1);
stars.Add(star);
}
}
}
public override bool IsPointInTile(double lat, double lng)
{
if (Level == 0)
{
return true;
}
if (Level == 1)
{
if ((lng >= 0 && lng <= 90) && (tileX == 0 && tileY == 1))
{
return true;
}
if ((lng > 90 && lng <= 180) && (tileX == 1 && tileY == 1))
{
return true;
}
if ((lng < 0 && lng >= -90) && (tileX == 0 && tileY == 0))
{
return true;
}
if ((lng < -90 && lng >= -180) && (tileX == 1 && tileY == 0))
{
return true;
}
return false;
}
if (!this.DemReady || this.DemData == null)
{
return false;
}
Vector3d testPoint = Coordinates.GeoTo3dDouble(-lat, lng);
bool top = IsLeftOfHalfSpace(TopLeft.Copy(), TopRight.Copy(), testPoint);
bool right = IsLeftOfHalfSpace(TopRight.Copy(), BottomRight.Copy(), testPoint);
bool bottom = IsLeftOfHalfSpace(BottomRight.Copy(), BottomLeft.Copy(), testPoint);
bool left = IsLeftOfHalfSpace(BottomLeft.Copy(), TopLeft.Copy(), testPoint);
if (top && right && bottom && left)
{
// showSelected = true;
return true;
}
return false; ;
}
private bool IsLeftOfHalfSpace(Vector3d pntA, Vector3d pntB, Vector3d pntTest)
{
pntA.Normalize();
pntB.Normalize();
Vector3d cross = Vector3d.Cross(pntA, pntB);
double dot = Vector3d.Dot(cross, pntTest);
return dot < 0;
}
private void InitializeGrids()
{
vertexList = new List<PositionTexture>();
childTriangleList = new List<Triangle>[4];
childTriangleList[0] = new List<Triangle>();
childTriangleList[1] = new List<Triangle>();
childTriangleList[2] = new List<Triangle>();
childTriangleList[3] = new List<Triangle>();
bounds = new PositionTexture[9];
if (Level > 0)
{
// Set in constuctor now
//ToastTile parent = (ToastTile)TileCache.GetTile(level - 1, x / 2, y / 2, dataset, null);
if (Parent == null)
{
Parent = TileCache.GetTile(Level - 1, tileX / 2, tileY / 2, dataset, null);
}
PlotTile parent = (PlotTile)Parent;
int xIndex = tileX % 2;
int yIndex = tileY % 2;
if (Level > 1)
{
backslash = parent.backslash;
}
else
{
backslash = xIndex == 1 ^ yIndex == 1;
}
bounds[0 + 3 * 0] = parent.bounds[xIndex + 3 * yIndex].Copy();
bounds[1 + 3 * 0] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * yIndex]);
bounds[2 + 3 * 0] = parent.bounds[xIndex + 1 + 3 * yIndex].Copy();
bounds[0 + 3 * 1] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]);
if (backslash)
{
bounds[1 + 3 * 1] = Midpoint(parent.bounds[xIndex + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]);
}
else
{
bounds[1 + 3 * 1] = Midpoint(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 3 * (yIndex + 1)]);
}
bounds[2 + 3 * 1] = Midpoint(parent.bounds[xIndex + 1 + 3 * yIndex], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]);
bounds[0 + 3 * 2] = parent.bounds[xIndex + 3 * (yIndex + 1)].Copy();
bounds[1 + 3 * 2] = Midpoint(parent.bounds[xIndex + 3 * (yIndex + 1)], parent.bounds[xIndex + 1 + 3 * (yIndex + 1)]);
bounds[2 + 3 * 2] = parent.bounds[xIndex + 1 + 3 * (yIndex + 1)].Copy();
bounds[0 + 3 * 0].Tu = 0*uvMultiple;
bounds[0 + 3 * 0].Tv = 0 * uvMultiple;
bounds[1 + 3 * 0].Tu = .5f * uvMultiple;
bounds[1 + 3 * 0].Tv = 0 * uvMultiple;
bounds[2 + 3 * 0].Tu = 1 * uvMultiple;
bounds[2 + 3 * 0].Tv = 0 * uvMultiple;
bounds[0 + 3 * 1].Tu = 0 * uvMultiple;
bounds[0 + 3 * 1].Tv = .5f * uvMultiple;
bounds[1 + 3 * 1].Tu = .5f * uvMultiple;
bounds[1 + 3 * 1].Tv = .5f * uvMultiple;
bounds[2 + 3 * 1].Tu = 1 * uvMultiple;
bounds[2 + 3 * 1].Tv = .5f * uvMultiple;
bounds[0 + 3 * 2].Tu = 0 * uvMultiple;
bounds[0 + 3 * 2].Tv = 1 * uvMultiple;
bounds[1 + 3 * 2].Tu = .5f * uvMultiple;
bounds[1 + 3 * 2].Tv = 1 * uvMultiple;
bounds[2 + 3 * 2].Tu = 1 * uvMultiple;
bounds[2 + 3 * 2].Tv = 1 * uvMultiple;
}
else
{
bounds[0 + 3 * 0] = PositionTexture.Create(0, -1, 0, 0, 0);
bounds[1 + 3 * 0] = PositionTexture.Create(0, 0, 1, .5f, 0);
bounds[2 + 3 * 0] = PositionTexture.Create(0, -1, 0, 1, 0);
bounds[0 + 3 * 1] = PositionTexture.Create(-1, 0, 0, 0, .5f);
bounds[1 + 3 * 1] = PositionTexture.Create(0, 1, 0, .5f, .5f);
bounds[2 + 3 * 1] = PositionTexture.Create(1, 0, 0, 1, .5f);
bounds[0 + 3 * 2] = PositionTexture.Create(0, -1, 0, 0, 1);
bounds[1 + 3 * 2] = PositionTexture.Create(0, 0, -1, .5f, 1);
bounds[2 + 3 * 2] = PositionTexture.Create(0, -1, 0, 1, 1);
// Setup default matrix of points.
}
}
private PositionTexture Midpoint(PositionTexture positionNormalTextured, PositionTexture positionNormalTextured_2)
{
Vector3d a1 = Vector3d.Lerp(positionNormalTextured.Position, positionNormalTextured_2.Position, .5f);
Vector2d a1uv = Vector2d.Lerp(Vector2d.Create(positionNormalTextured.Tu, positionNormalTextured.Tv), Vector2d.Create(positionNormalTextured_2.Tu, positionNormalTextured_2.Tv), .5f);
a1.Normalize();
return PositionTexture.CreatePos(a1, a1uv.X, a1uv.Y);
}
int subDivisionLevel = 4;
bool subDivided = false;
public override bool CreateGeometry(RenderContext renderContext)
{
if (GeometryCreated)
{
return true;
}
GeometryCreated = true;
base.CreateGeometry(renderContext);
return true;
}
public PlotTile()
{
}
public static PlotTile Create(int level, int xc, int yc, Imageset dataset, Tile parent)
{
PlotTile temp = new PlotTile();
temp.Parent = parent;
temp.Level = level;
temp.tileX = xc;
temp.tileY = yc;
temp.dataset = dataset;
temp.topDown = !dataset.BottomsUp;
if (temp.tileX != (int)xc)
{
Script.Literal("alert('bad')");
}
//temp.ComputeQuadrant();
if (dataset.MeanRadius != 0)
{
temp.DemScaleFactor = dataset.MeanRadius;
}
else
{
if (dataset.DataSetType == ImageSetType.Earth)
{
temp.DemScaleFactor = 6371000;
}
else
{
temp.DemScaleFactor = 3396010;
}
}
temp.ComputeBoundingSphere();
return temp;
}
public override void CleanUp(bool removeFromParent)
{
base.CleanUp(removeFromParent);
if (vertexList != null)
{
vertexList = null;
}
if (childTriangleList != null)
{
childTriangleList = null;
}
subDivided = false;
demArray = null;
}
}
}
|
namespace QuanLySinhVien_GUI
{
partial class frmtimkiemdiemsinhvientheomasv
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmtimkiemdiemsinhvientheomasv));
this.btnThoat = new System.Windows.Forms.Button();
this.cmbMaMH = new System.Windows.Forms.ComboBox();
this.dgvKetQua = new System.Windows.Forms.DataGridView();
this.btnTim = new System.Windows.Forms.Button();
this.txtMaSV = new System.Windows.Forms.TextBox();
this.lblMaMH = new System.Windows.Forms.Label();
this.lblMaSV = new System.Windows.Forms.Label();
this.lblTittle = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dgvKetQua)).BeginInit();
this.SuspendLayout();
//
// btnThoat
//
this.btnThoat.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnThoat.BackgroundImage")));
this.btnThoat.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.btnThoat.Location = new System.Drawing.Point(580, 418);
this.btnThoat.Name = "btnThoat";
this.btnThoat.Size = new System.Drawing.Size(72, 30);
this.btnThoat.TabIndex = 32;
this.btnThoat.Text = " Thoát";
this.btnThoat.UseVisualStyleBackColor = true;
//
// cmbMaMH
//
this.cmbMaMH.FormattingEnabled = true;
this.cmbMaMH.Location = new System.Drawing.Point(382, 109);
this.cmbMaMH.Name = "cmbMaMH";
this.cmbMaMH.Size = new System.Drawing.Size(121, 21);
this.cmbMaMH.TabIndex = 31;
//
// dgvKetQua
//
this.dgvKetQua.AllowUserToAddRows = false;
this.dgvKetQua.AllowUserToDeleteRows = false;
this.dgvKetQua.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvKetQua.Location = new System.Drawing.Point(96, 183);
this.dgvKetQua.Name = "dgvKetQua";
this.dgvKetQua.ReadOnly = true;
this.dgvKetQua.Size = new System.Drawing.Size(537, 214);
this.dgvKetQua.TabIndex = 30;
//
// btnTim
//
this.btnTim.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("btnTim.BackgroundImage")));
this.btnTim.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None;
this.btnTim.Location = new System.Drawing.Point(580, 105);
this.btnTim.Name = "btnTim";
this.btnTim.Size = new System.Drawing.Size(72, 30);
this.btnTim.TabIndex = 29;
this.btnTim.Text = " Tìm";
this.btnTim.UseVisualStyleBackColor = true;
//
// txtMaSV
//
this.txtMaSV.Location = new System.Drawing.Point(114, 111);
this.txtMaSV.Name = "txtMaSV";
this.txtMaSV.Size = new System.Drawing.Size(125, 20);
this.txtMaSV.TabIndex = 28;
//
// lblMaMH
//
this.lblMaMH.AutoSize = true;
this.lblMaMH.Location = new System.Drawing.Point(302, 111);
this.lblMaMH.Name = "lblMaMH";
this.lblMaMH.Size = new System.Drawing.Size(60, 13);
this.lblMaMH.TabIndex = 26;
this.lblMaMH.Text = "Mã Học Kỳ";
//
// lblMaSV
//
this.lblMaSV.AutoSize = true;
this.lblMaSV.Location = new System.Drawing.Point(43, 111);
this.lblMaSV.Name = "lblMaSV";
this.lblMaSV.Size = new System.Drawing.Size(39, 13);
this.lblMaSV.TabIndex = 27;
this.lblMaSV.Text = "Mã SV";
//
// lblTittle
//
this.lblTittle.AutoSize = true;
this.lblTittle.Font = new System.Drawing.Font("Times New Roman", 20.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblTittle.ForeColor = System.Drawing.Color.Red;
this.lblTittle.Location = new System.Drawing.Point(151, 30);
this.lblTittle.Name = "lblTittle";
this.lblTittle.Size = new System.Drawing.Size(408, 31);
this.lblTittle.TabIndex = 25;
this.lblTittle.Text = "Tìm Kiếm Điểm Theo Mã Sinh Viên";
//
// frmtimkiemdiemsinhvientheomasv
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(695, 479);
this.Controls.Add(this.btnThoat);
this.Controls.Add(this.cmbMaMH);
this.Controls.Add(this.dgvKetQua);
this.Controls.Add(this.btnTim);
this.Controls.Add(this.txtMaSV);
this.Controls.Add(this.lblMaMH);
this.Controls.Add(this.lblMaSV);
this.Controls.Add(this.lblTittle);
this.Name = "frmtimkiemdiemsinhvientheomasv";
this.Text = "TÌM KIẾM ĐIỂM SINH VIÊN";
((System.ComponentModel.ISupportInitialize)(this.dgvKetQua)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button btnThoat;
private System.Windows.Forms.ComboBox cmbMaMH;
private System.Windows.Forms.DataGridView dgvKetQua;
private System.Windows.Forms.Button btnTim;
private System.Windows.Forms.TextBox txtMaSV;
private System.Windows.Forms.Label lblMaMH;
private System.Windows.Forms.Label lblMaSV;
private System.Windows.Forms.Label lblTittle;
}
} |
//---------------------------------------------------------------------------
//
// <copyright file="ByteAnimationUsingKeyFrames.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This class is used to animate a Byte property value along a set
/// of key frames.
/// </summary>
[ContentProperty("KeyFrames")]
public class ByteAnimationUsingKeyFrames : ByteAnimationBase, IKeyFrameAnimation, IAddChild
{
#region Data
private ByteKeyFrameCollection _keyFrames;
private ResolvedKeyFrameEntry[] _sortedResolvedKeyFrames;
private bool _areKeyTimesValid;
#endregion
#region Constructors
/// <Summary>
/// Creates a new KeyFrameByteAnimation.
/// </Summary>
public ByteAnimationUsingKeyFrames()
: base()
{
_areKeyTimesValid = true;
}
#endregion
#region Freezable
/// <summary>
/// Creates a copy of this KeyFrameByteAnimation.
/// </summary>
/// <returns>The copy</returns>
public new ByteAnimationUsingKeyFrames Clone()
{
return (ByteAnimationUsingKeyFrames)base.Clone();
}
/// <summary>
/// Returns a version of this class with all its base property values
/// set to the current animated values and removes the animations.
/// </summary>
/// <returns>
/// Since this class isn't animated, this method will always just return
/// this instance of the class.
/// </returns>
public new ByteAnimationUsingKeyFrames CloneCurrentValue()
{
return (ByteAnimationUsingKeyFrames)base.CloneCurrentValue();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>.
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
canFreeze &= Freezable.Freeze(_keyFrames, isChecking);
if (canFreeze & !_areKeyTimesValid)
{
ResolveKeyTimes();
}
return canFreeze;
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.OnChanged">Freezable.OnChanged</see>.
/// </summary>
protected override void OnChanged()
{
_areKeyTimesValid = false;
base.OnChanged();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new ByteAnimationUsingKeyFrames();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>.
/// </summary>
protected override void CloneCore(Freezable sourceFreezable)
{
ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) sourceFreezable;
base.CloneCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>.
/// </summary>
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>.
/// </summary>
protected override void GetAsFrozenCore(Freezable source)
{
ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) source;
base.GetAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ false);
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>.
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable source)
{
ByteAnimationUsingKeyFrames sourceAnimation = (ByteAnimationUsingKeyFrames) source;
base.GetCurrentValueAsFrozenCore(source);
CopyCommon(sourceAnimation, /* isCurrentValueClone = */ true);
}
/// <summary>
/// Helper used by the four Freezable clone methods to copy the resolved key times and
/// key frames. The Get*AsFrozenCore methods are implemented the same as the Clone*Core
/// methods; Get*AsFrozen at the top level will recursively Freeze so it's not done here.
/// </summary>
/// <param name="sourceAnimation"></param>
/// <param name="isCurrentValueClone"></param>
private void CopyCommon(ByteAnimationUsingKeyFrames sourceAnimation, bool isCurrentValueClone)
{
_areKeyTimesValid = sourceAnimation._areKeyTimesValid;
if ( _areKeyTimesValid
&& sourceAnimation._sortedResolvedKeyFrames != null)
{
// _sortedResolvedKeyFrames is an array of ResolvedKeyFrameEntry so the notion of CurrentValueClone doesn't apply
_sortedResolvedKeyFrames = (ResolvedKeyFrameEntry[])sourceAnimation._sortedResolvedKeyFrames.Clone();
}
if (sourceAnimation._keyFrames != null)
{
if (isCurrentValueClone)
{
_keyFrames = (ByteKeyFrameCollection)sourceAnimation._keyFrames.CloneCurrentValue();
}
else
{
_keyFrames = (ByteKeyFrameCollection)sourceAnimation._keyFrames.Clone();
}
OnFreezablePropertyChanged(null, _keyFrames);
}
}
#endregion // Freezable
#region IAddChild interface
/// <summary>
/// Adds a child object to this KeyFrameAnimation.
/// </summary>
/// <param name="child">
/// The child object to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation only accepts a KeyFrame of the proper type as
/// a child.
/// </remarks>
void IAddChild.AddChild(object child)
{
WritePreamble();
if (child == null)
{
throw new ArgumentNullException("child");
}
AddChild(child);
WritePostscript();
}
/// <summary>
/// Implemented to allow KeyFrames to be direct children
/// of KeyFrameAnimations in markup.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddChild(object child)
{
ByteKeyFrame keyFrame = child as ByteKeyFrame;
if (keyFrame != null)
{
KeyFrames.Add(keyFrame);
}
else
{
throw new ArgumentException(SR.Get(SRID.Animation_ChildMustBeKeyFrame), "child");
}
}
/// <summary>
/// Adds a text string as a child of this KeyFrameAnimation.
/// </summary>
/// <param name="childText">
/// The text to add.
/// </param>
/// <remarks>
/// A KeyFrameAnimation does not accept text as a child, so this method will
/// raise an InvalididOperationException unless a derived class has
/// overridden the behavior to add text.
/// </remarks>
/// <exception cref="ArgumentNullException">The childText parameter is
/// null.</exception>
void IAddChild.AddText(string childText)
{
if (childText == null)
{
throw new ArgumentNullException("childText");
}
AddText(childText);
}
/// <summary>
/// This method performs the core functionality of the AddText()
/// method on the IAddChild interface. For a KeyFrameAnimation this means
/// throwing and InvalidOperationException because it doesn't
/// support adding text.
/// </summary>
/// <remarks>
/// This method is the only core implementation. It does not call
/// WritePreamble() or WritePostscript(). It also doesn't throw an
/// ArgumentNullException if the childText parameter is null. These tasks
/// are performed by the interface implementation. Therefore, it's OK
/// for a derived class to override this method and call the base
/// class implementation only if they determine that it's the right
/// course of action. The derived class can rely on KeyFrameAnimation's
/// implementation of IAddChild.AddChild or implement their own
/// following the Freezable pattern since that would be a public
/// method.
/// </remarks>
/// <param name="childText">A string representing the child text that
/// should be added. If this is a KeyFrameAnimation an exception will be
/// thrown.</param>
/// <exception cref="InvalidOperationException">Timelines have no way
/// of adding text.</exception>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void AddText(string childText)
{
throw new InvalidOperationException(SR.Get(SRID.Animation_NoTextChildren));
}
#endregion
#region ByteAnimationBase
/// <summary>
/// Calculates the value this animation believes should be the current value for the property.
/// </summary>
/// <param name="defaultOriginValue">
/// This value is the suggested origin value provided to the animation
/// to be used if the animation does not have its own concept of a
/// start value. If this animation is the first in a composition chain
/// this value will be the snapshot value if one is available or the
/// base property value if it is not; otherise this value will be the
/// value returned by the previous animation in the chain with an
/// animationClock that is not Stopped.
/// </param>
/// <param name="defaultDestinationValue">
/// This value is the suggested destination value provided to the animation
/// to be used if the animation does not have its own concept of an
/// end value. This value will be the base value if the animation is
/// in the first composition layer of animations on a property;
/// otherwise this value will be the output value from the previous
/// composition layer of animations for the property.
/// </param>
/// <param name="animationClock">
/// This is the animationClock which can generate the CurrentTime or
/// CurrentProgress value to be used by the animation to generate its
/// output value.
/// </param>
/// <returns>
/// The value this animation believes should be the current value for the property.
/// </returns>
protected sealed override Byte GetCurrentValueCore(
Byte defaultOriginValue,
Byte defaultDestinationValue,
AnimationClock animationClock)
{
Debug.Assert(animationClock.CurrentState != ClockState.Stopped);
if (_keyFrames == null)
{
return defaultDestinationValue;
}
// We resolved our KeyTimes when we froze, but also got notified
// of the frozen state and therefore invalidated ourselves.
if (!_areKeyTimesValid)
{
ResolveKeyTimes();
}
if (_sortedResolvedKeyFrames == null)
{
return defaultDestinationValue;
}
TimeSpan currentTime = animationClock.CurrentTime.Value;
Int32 keyFrameCount = _sortedResolvedKeyFrames.Length;
Int32 maxKeyFrameIndex = keyFrameCount - 1;
Byte currentIterationValue;
Debug.Assert(maxKeyFrameIndex >= 0, "maxKeyFrameIndex is less than zero which means we don't actually have any key frames.");
Int32 currentResolvedKeyFrameIndex = 0;
// Skip all the key frames with key times lower than the current time.
// currentResolvedKeyFrameIndex will be greater than maxKeyFrameIndex
// if we are past the last key frame.
while ( currentResolvedKeyFrameIndex < keyFrameCount
&& currentTime > _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
// If there are multiple key frames at the same key time, be sure to go to the last one.
while ( currentResolvedKeyFrameIndex < maxKeyFrameIndex
&& currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex + 1]._resolvedKeyTime)
{
currentResolvedKeyFrameIndex++;
}
if (currentResolvedKeyFrameIndex == keyFrameCount)
{
// Past the last key frame.
currentIterationValue = GetResolvedKeyFrameValue(maxKeyFrameIndex);
}
else if (currentTime == _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime)
{
// Exactly on a key frame.
currentIterationValue = GetResolvedKeyFrameValue(currentResolvedKeyFrameIndex);
}
else
{
// Between two key frames.
Double currentSegmentProgress = 0.0;
Byte fromValue;
if (currentResolvedKeyFrameIndex == 0)
{
// The current key frame is the first key frame so we have
// some special rules for determining the fromValue and an
// optimized method of calculating the currentSegmentProgress.
// If we're additive we want the base value to be a zero value
// so that if there isn't a key frame at time 0.0, we'll use
// the zero value for the time 0.0 value and then add that
// later to the base value.
if (IsAdditive)
{
fromValue = AnimatedTypeHelpers.GetZeroValueByte(defaultOriginValue);
}
else
{
fromValue = defaultOriginValue;
}
// Current segment time divided by the segment duration.
// Note: the reason this works is that we know that we're in
// the first segment, so we can assume:
//
// currentTime.TotalMilliseconds = current segment time
// _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds = current segment duration
currentSegmentProgress = currentTime.TotalMilliseconds
/ _sortedResolvedKeyFrames[0]._resolvedKeyTime.TotalMilliseconds;
}
else
{
Int32 previousResolvedKeyFrameIndex = currentResolvedKeyFrameIndex - 1;
TimeSpan previousResolvedKeyTime = _sortedResolvedKeyFrames[previousResolvedKeyFrameIndex]._resolvedKeyTime;
fromValue = GetResolvedKeyFrameValue(previousResolvedKeyFrameIndex);
TimeSpan segmentCurrentTime = currentTime - previousResolvedKeyTime;
TimeSpan segmentDuration = _sortedResolvedKeyFrames[currentResolvedKeyFrameIndex]._resolvedKeyTime - previousResolvedKeyTime;
currentSegmentProgress = segmentCurrentTime.TotalMilliseconds
/ segmentDuration.TotalMilliseconds;
}
currentIterationValue = GetResolvedKeyFrame(currentResolvedKeyFrameIndex).InterpolateValue(fromValue, currentSegmentProgress);
}
// If we're cumulative, we need to multiply the final key frame
// value by the current repeat count and add this to the return
// value.
if (IsCumulative)
{
Double currentRepeat = (Double)(animationClock.CurrentIteration - 1);
if (currentRepeat > 0.0)
{
currentIterationValue = AnimatedTypeHelpers.AddByte(
currentIterationValue,
AnimatedTypeHelpers.ScaleByte(GetResolvedKeyFrameValue(maxKeyFrameIndex), currentRepeat));
}
}
// If we're additive we need to add the base value to the return value.
if (IsAdditive)
{
return AnimatedTypeHelpers.AddByte(defaultOriginValue, currentIterationValue);
}
return currentIterationValue;
}
/// <summary>
/// Provide a custom natural Duration when the Duration property is set to Automatic.
/// </summary>
/// <param name="clock">
/// The Clock whose natural duration is desired.
/// </param>
/// <returns>
/// If the last KeyFrame of this animation is a KeyTime, then this will
/// be used as the NaturalDuration; otherwise it will be one second.
/// </returns>
protected override sealed Duration GetNaturalDurationCore(Clock clock)
{
return new Duration(LargestTimeSpanKeyTime);
}
#endregion
#region IKeyFrameAnimation
/// <summary>
/// Returns the ByteKeyFrameCollection used by this KeyFrameByteAnimation.
/// </summary>
IList IKeyFrameAnimation.KeyFrames
{
get
{
return KeyFrames;
}
set
{
KeyFrames = (ByteKeyFrameCollection)value;
}
}
/// <summary>
/// Returns the ByteKeyFrameCollection used by this KeyFrameByteAnimation.
/// </summary>
public ByteKeyFrameCollection KeyFrames
{
get
{
ReadPreamble();
// The reason we don't just set _keyFrames to the empty collection
// in the first place is that null tells us that the user has not
// asked for the collection yet. The first time they ask for the
// collection and we're unfrozen, policy dictates that we give
// them a new unfrozen collection. All subsequent times they will
// get whatever collection is present, whether frozen or unfrozen.
if (_keyFrames == null)
{
if (this.IsFrozen)
{
_keyFrames = ByteKeyFrameCollection.Empty;
}
else
{
WritePreamble();
_keyFrames = new ByteKeyFrameCollection();
OnFreezablePropertyChanged(null, _keyFrames);
WritePostscript();
}
}
return _keyFrames;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
WritePreamble();
if (value != _keyFrames)
{
OnFreezablePropertyChanged(_keyFrames, value);
_keyFrames = value;
WritePostscript();
}
}
}
/// <summary>
/// Returns true if we should serialize the KeyFrames, property for this Animation.
/// </summary>
/// <returns>True if we should serialize the KeyFrames property for this Animation; otherwise false.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool ShouldSerializeKeyFrames()
{
ReadPreamble();
return _keyFrames != null
&& _keyFrames.Count > 0;
}
#endregion
#region Public Properties
/// <summary>
/// If this property is set to true, this animation will add its value
/// to the base value or the value of the previous animation in the
/// composition chain. Another way of saying this is that the units
/// specified in the animation are relative to the base value rather
/// than absolute units.
/// </summary>
/// <remarks>
/// In the case where the first key frame's resolved key time is not
/// 0.0 there is slightly different behavior between KeyFrameByteAnimations
/// with IsAdditive set and without. Animations with the property set to false
/// will behave as if there is a key frame at time 0.0 with the value of the
/// base value. Animations with the property set to true will behave as if
/// there is a key frame at time 0.0 with a zero value appropriate to the type
/// of the animation. These behaviors provide the results most commonly expected
/// and can be overridden by simply adding a key frame at time 0.0 with the preferred value.
/// </remarks>
public bool IsAdditive
{
get
{
return (bool)GetValue(IsAdditiveProperty);
}
set
{
SetValueInternal(IsAdditiveProperty, BooleanBoxes.Box(value));
}
}
/// <summary>
/// If this property is set to true, the value of this animation will
/// accumulate over repeat cycles. For example, if this is a point
/// animation and your key frames describe something approximating and
/// arc, setting this property to true will result in an animation that
/// would appear to bounce the point across the screen.
/// </summary>
/// <remarks>
/// This property works along with the IsAdditive property. Setting
/// this value to true has no effect unless IsAdditive is also set
/// to true.
/// </remarks>
public bool IsCumulative
{
get
{
return (bool)GetValue(IsCumulativeProperty);
}
set
{
SetValueInternal(IsCumulativeProperty, BooleanBoxes.Box(value));
}
}
#endregion
#region Private Methods
private struct KeyTimeBlock
{
public int BeginIndex;
public int EndIndex;
}
private Byte GetResolvedKeyFrameValue(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrameValue");
return GetResolvedKeyFrame(resolvedKeyFrameIndex).Value;
}
private ByteKeyFrame GetResolvedKeyFrame(Int32 resolvedKeyFrameIndex)
{
Debug.Assert(_areKeyTimesValid, "The key frames must be resolved and sorted before calling GetResolvedKeyFrame");
return _keyFrames[_sortedResolvedKeyFrames[resolvedKeyFrameIndex]._originalKeyFrameIndex];
}
/// <summary>
/// Returns the largest time span specified key time from all of the key frames.
/// If there are not time span key times a time span of one second is returned
/// to match the default natural duration of the From/To/By animations.
/// </summary>
private TimeSpan LargestTimeSpanKeyTime
{
get
{
bool hasTimeSpanKeyTime = false;
TimeSpan largestTimeSpanKeyTime = TimeSpan.Zero;
if (_keyFrames != null)
{
Int32 keyFrameCount = _keyFrames.Count;
for (int index = 0; index < keyFrameCount; index++)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
if (keyTime.Type == KeyTimeType.TimeSpan)
{
hasTimeSpanKeyTime = true;
if (keyTime.TimeSpan > largestTimeSpanKeyTime)
{
largestTimeSpanKeyTime = keyTime.TimeSpan;
}
}
}
}
if (hasTimeSpanKeyTime)
{
return largestTimeSpanKeyTime;
}
else
{
return TimeSpan.FromSeconds(1.0);
}
}
}
private void ResolveKeyTimes()
{
Debug.Assert(!_areKeyTimesValid, "KeyFrameByteAnimaton.ResolveKeyTimes() shouldn't be called if the key times are already valid.");
int keyFrameCount = 0;
if (_keyFrames != null)
{
keyFrameCount = _keyFrames.Count;
}
if (keyFrameCount == 0)
{
_sortedResolvedKeyFrames = null;
_areKeyTimesValid = true;
return;
}
_sortedResolvedKeyFrames = new ResolvedKeyFrameEntry[keyFrameCount];
int index = 0;
// Initialize the _originalKeyFrameIndex.
for ( ; index < keyFrameCount; index++)
{
_sortedResolvedKeyFrames[index]._originalKeyFrameIndex = index;
}
// calculationDuration represents the time span we will use to resolve
// percent key times. This is defined as the value in the following
// precedence order:
// 1. The animation's duration, but only if it is a time span, not auto or forever.
// 2. The largest time span specified key time of all the key frames.
// 3. 1 second, to match the From/To/By animations.
TimeSpan calculationDuration = TimeSpan.Zero;
Duration duration = Duration;
if (duration.HasTimeSpan)
{
calculationDuration = duration.TimeSpan;
}
else
{
calculationDuration = LargestTimeSpanKeyTime;
}
int maxKeyFrameIndex = keyFrameCount - 1;
ArrayList unspecifiedBlocks = new ArrayList();
bool hasPacedKeyTimes = false;
//
// Pass 1: Resolve Percent and Time key times.
//
index = 0;
while (index < keyFrameCount)
{
KeyTime keyTime = _keyFrames[index].KeyTime;
switch (keyTime.Type)
{
case KeyTimeType.Percent:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.FromMilliseconds(
keyTime.Percent * calculationDuration.TotalMilliseconds);
index++;
break;
case KeyTimeType.TimeSpan:
_sortedResolvedKeyFrames[index]._resolvedKeyTime = keyTime.TimeSpan;
index++;
break;
case KeyTimeType.Paced:
case KeyTimeType.Uniform:
if (index == maxKeyFrameIndex)
{
// If the last key frame doesn't have a specific time
// associated with it its resolved key time will be
// set to the calculationDuration, which is the
// defined in the comments above where it is set.
// Reason: We only want extra time at the end of the
// key frames if the user specifically states that
// the last key frame ends before the animation ends.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = calculationDuration;
index++;
}
else if ( index == 0
&& keyTime.Type == KeyTimeType.Paced)
{
// Note: It's important that this block come after
// the previous if block because of rule precendence.
// If the first key frame in a multi-frame key frame
// collection is paced, we set its resolved key time
// to 0.0 for performance reasons. If we didn't, the
// resolved key time list would be dependent on the
// base value which can change every animation frame
// in many cases.
_sortedResolvedKeyFrames[index]._resolvedKeyTime = TimeSpan.Zero;
index++;
}
else
{
if (keyTime.Type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
KeyTimeBlock block = new KeyTimeBlock();
block.BeginIndex = index;
// NOTE: We don't want to go all the way up to the
// last frame because if it is Uniform or Paced its
// resolved key time will be set to the calculation
// duration using the logic above.
//
// This is why the logic is:
// ((++index) < maxKeyFrameIndex)
// instead of:
// ((++index) < keyFrameCount)
while ((++index) < maxKeyFrameIndex)
{
KeyTimeType type = _keyFrames[index].KeyTime.Type;
if ( type == KeyTimeType.Percent
|| type == KeyTimeType.TimeSpan)
{
break;
}
else if (type == KeyTimeType.Paced)
{
hasPacedKeyTimes = true;
}
}
Debug.Assert(index < keyFrameCount,
"The end index for a block of unspecified key frames is out of bounds.");
block.EndIndex = index;
unspecifiedBlocks.Add(block);
}
break;
}
}
//
// Pass 2: Resolve Uniform key times.
//
for (int j = 0; j < unspecifiedBlocks.Count; j++)
{
KeyTimeBlock block = (KeyTimeBlock)unspecifiedBlocks[j];
TimeSpan blockBeginTime = TimeSpan.Zero;
if (block.BeginIndex > 0)
{
blockBeginTime = _sortedResolvedKeyFrames[block.BeginIndex - 1]._resolvedKeyTime;
}
// The number of segments is equal to the number of key
// frames we're working on plus 1. Think about the case
// where we're working on a single key frame. There's a
// segment before it and a segment after it.
//
// Time known Uniform Time known
// ^ ^ ^
// | | |
// | (segment 1) | (segment 2) |
Int64 segmentCount = (block.EndIndex - block.BeginIndex) + 1;
TimeSpan uniformTimeStep = TimeSpan.FromTicks((_sortedResolvedKeyFrames[block.EndIndex]._resolvedKeyTime - blockBeginTime).Ticks / segmentCount);
index = block.BeginIndex;
TimeSpan resolvedTime = blockBeginTime + uniformTimeStep;
while (index < block.EndIndex)
{
_sortedResolvedKeyFrames[index]._resolvedKeyTime = resolvedTime;
resolvedTime += uniformTimeStep;
index++;
}
}
//
// Pass 3: Resolve Paced key times.
//
if (hasPacedKeyTimes)
{
ResolvePacedKeyTimes();
}
//
// Sort resolved key frame entries.
//
Array.Sort(_sortedResolvedKeyFrames);
_areKeyTimesValid = true;
return;
}
/// <summary>
/// This should only be called from ResolveKeyTimes and only at the
/// appropriate time.
/// </summary>
private void ResolvePacedKeyTimes()
{
Debug.Assert(_keyFrames != null && _keyFrames.Count > 2,
"Caller must guard against calling this method when there are insufficient keyframes.");
// If the first key frame is paced its key time has already
// been resolved, so we start at index 1.
int index = 1;
int maxKeyFrameIndex = _sortedResolvedKeyFrames.Length - 1;
do
{
if (_keyFrames[index].KeyTime.Type == KeyTimeType.Paced)
{
//
// We've found a paced key frame so this is the
// beginning of a paced block.
//
// The first paced key frame in this block.
int firstPacedBlockKeyFrameIndex = index;
// List of segment lengths for this paced block.
List<Double> segmentLengths = new List<Double>();
// The resolved key time for the key frame before this
// block which we'll use as our starting point.
TimeSpan prePacedBlockKeyTime = _sortedResolvedKeyFrames[index - 1]._resolvedKeyTime;
// The total of the segment lengths of the paced key
// frames in this block.
Double totalLength = 0.0;
// The key value of the previous key frame which will be
// used to determine the segment length of this key frame.
Byte prevKeyValue = _keyFrames[index - 1].Value;
do
{
Byte currentKeyValue = _keyFrames[index].Value;
// Determine the segment length for this key frame and
// add to the total length.
totalLength += AnimatedTypeHelpers.GetSegmentLengthByte(prevKeyValue, currentKeyValue);
// Temporarily store the distance into the total length
// that this key frame represents in the resolved
// key times array to be converted to a resolved key
// time outside of this loop.
segmentLengths.Add(totalLength);
// Prepare for the next iteration.
prevKeyValue = currentKeyValue;
index++;
}
while ( index < maxKeyFrameIndex
&& _keyFrames[index].KeyTime.Type == KeyTimeType.Paced);
// index is currently set to the index of the key frame
// after the last paced key frame. This will always
// be a valid index because we limit ourselves with
// maxKeyFrameIndex.
// We need to add the distance between the last paced key
// frame and the next key frame to get the total distance
// inside the key frame block.
totalLength += AnimatedTypeHelpers.GetSegmentLengthByte(prevKeyValue, _keyFrames[index].Value);
// Calculate the time available in the resolved key time space.
TimeSpan pacedBlockDuration = _sortedResolvedKeyFrames[index]._resolvedKeyTime - prePacedBlockKeyTime;
// Convert lengths in segmentLengths list to resolved
// key times for the paced key frames in this block.
for (int i = 0, currentKeyFrameIndex = firstPacedBlockKeyFrameIndex; i < segmentLengths.Count; i++, currentKeyFrameIndex++)
{
// The resolved key time for each key frame is:
//
// The key time of the key frame before this paced block
// + ((the percentage of the way through the total length)
// * the resolved key time space available for the block)
_sortedResolvedKeyFrames[currentKeyFrameIndex]._resolvedKeyTime = prePacedBlockKeyTime + TimeSpan.FromMilliseconds(
(segmentLengths[i] / totalLength) * pacedBlockDuration.TotalMilliseconds);
}
}
else
{
index++;
}
}
while (index < maxKeyFrameIndex);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
namespace HarmonyLib
{
/// <summary>Specifies the type of method</summary>
///
public enum MethodType
{
/// <summary>This is a normal method</summary>
Normal,
/// <summary>This is a getter</summary>
Getter,
/// <summary>This is a setter</summary>
Setter,
/// <summary>This is a constructor</summary>
Constructor,
/// <summary>This is a static constructor</summary>
StaticConstructor,
/// <summary>This targets the MoveNext method of the enumerator result</summary>
Enumerator
}
/// <summary>Specifies the type of argument</summary>
///
public enum ArgumentType
{
/// <summary>This is a normal argument</summary>
Normal,
/// <summary>This is a reference argument (ref)</summary>
Ref,
/// <summary>This is an out argument (out)</summary>
Out,
/// <summary>This is a pointer argument (&)</summary>
Pointer
}
/// <summary>Specifies the type of patch</summary>
///
public enum HarmonyPatchType
{
/// <summary>Any patch</summary>
All,
/// <summary>A prefix patch</summary>
Prefix,
/// <summary>A postfix patch</summary>
Postfix,
/// <summary>A transpiler</summary>
Transpiler,
/// <summary>A finalizer</summary>
Finalizer,
/// <summary>A reverse patch</summary>
ReversePatch
}
/// <summary>Specifies the type of reverse patch</summary>
///
public enum HarmonyReversePatchType
{
/// <summary>Use the unmodified original method (directly from IL)</summary>
Original,
/// <summary>Use the original as it is right now including previous patches but excluding future ones</summary>
Snapshot
}
/// <summary>Specifies the type of method call dispatching mechanics</summary>
///
public enum MethodDispatchType
{
/// <summary>Call the method using dynamic dispatching if method is virtual (including overriden)</summary>
/// <remarks>
/// <para>
/// This is the built-in form of late binding (a.k.a. dynamic binding) and is the default dispatching mechanic in C#.
/// This directly corresponds with the <see cref="System.Reflection.Emit.OpCodes.Callvirt"/> instruction.
/// </para>
/// <para>
/// For virtual (including overriden) methods, the instance type's most-derived/overriden implementation of the method is called.
/// For non-virtual (including static) methods, same behavior as <see cref="Call"/>: the exact specified method implementation is called.
/// </para>
/// <para>
/// Note: This is not a fully dynamic dispatch, since non-virtual (including static) methods are still called non-virtually.
/// A fully dynamic dispatch in C# involves using
/// the <see href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types#the-dynamic-type"><c>dynamic</c> type</see>
/// (actually a fully dynamic binding, since even the name and overload resolution happens at runtime), which <see cref="MethodDispatchType"/> does not support.
/// </para>
/// </remarks>
VirtualCall,
/// <summary>Call the method using static dispatching, regardless of whether method is virtual (including overriden) or non-virtual (including static)</summary>
/// <remarks>
/// <para>
/// a.k.a. non-virtual dispatching, early binding, or static binding.
/// This directly corresponds with the <see cref="System.Reflection.Emit.OpCodes.Call"/> instruction.
/// </para>
/// <para>
/// For both virtual (including overriden) and non-virtual (including static) methods, the exact specified method implementation is called, without virtual/override mechanics.
/// </para>
/// </remarks>
Call
}
/// <summary>The base class for all Harmony annotations (not meant to be used directly)</summary>
///
public class HarmonyAttribute : Attribute
{
/// <summary>The common information for all attributes</summary>
public HarmonyMethod info = new HarmonyMethod();
}
/// <summary>Annotation to define your Harmony patch methods</summary>
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Delegate | AttributeTargets.Method, AllowMultiple = true)]
public class HarmonyPatch : HarmonyAttribute
{
/// <summary>An empty annotation can be used together with TargetMethod(s)</summary>
///
public HarmonyPatch()
{
}
/// <summary>An annotation that specifies a class to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
///
public HarmonyPatch(Type declaringType)
{
info.declaringType = declaringType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="argumentTypes">The argument types of the method or constructor to patch</param>
///
public HarmonyPatch(Type declaringType, Type[] argumentTypes)
{
info.declaringType = declaringType;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
///
public HarmonyPatch(Type declaringType, string methodName)
{
info.declaringType = declaringType;
info.methodName = methodName;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(Type declaringType, string methodName, params Type[] argumentTypes)
{
info.declaringType = declaringType;
info.methodName = methodName;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">Array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.declaringType = declaringType;
info.methodName = methodName;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
///
public HarmonyPatch(Type declaringType, MethodType methodType)
{
info.declaringType = declaringType;
info.methodType = methodType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(Type declaringType, MethodType methodType, params Type[] argumentTypes)
{
info.declaringType = declaringType;
info.methodType = methodType;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">Array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(Type declaringType, MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.declaringType = declaringType;
info.methodType = methodType;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
///
public HarmonyPatch(Type declaringType, string methodName, MethodType methodType)
{
info.declaringType = declaringType;
info.methodName = methodName;
info.methodType = methodType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
///
public HarmonyPatch(string methodName)
{
info.methodName = methodName;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(string methodName, params Type[] argumentTypes)
{
info.methodName = methodName;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.methodName = methodName;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="methodType">The <see cref="MethodType"/></param>
///
public HarmonyPatch(string methodName, MethodType methodType)
{
info.methodName = methodName;
info.methodType = methodType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodType">The <see cref="MethodType"/></param>
///
public HarmonyPatch(MethodType methodType)
{
info.methodType = methodType;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodType">The <see cref="MethodType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(MethodType methodType, params Type[] argumentTypes)
{
info.methodType = methodType;
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodType">The <see cref="MethodType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.methodType = methodType;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyPatch(Type[] argumentTypes)
{
info.argumentTypes = argumentTypes;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyPatch(Type[] argumentTypes, ArgumentType[] argumentVariations)
{
ParseSpecialArguments(argumentTypes, argumentVariations);
}
void ParseSpecialArguments(Type[] argumentTypes, ArgumentType[] argumentVariations)
{
if (argumentVariations is null || argumentVariations.Length == 0)
{
info.argumentTypes = argumentTypes;
return;
}
if (argumentTypes.Length < argumentVariations.Length)
throw new ArgumentException("argumentVariations contains more elements than argumentTypes", nameof(argumentVariations));
var types = new List<Type>();
for (var i = 0; i < argumentTypes.Length; i++)
{
var type = argumentTypes[i];
switch (argumentVariations[i])
{
case ArgumentType.Normal:
break;
case ArgumentType.Ref:
case ArgumentType.Out:
type = type.MakeByRefType();
break;
case ArgumentType.Pointer:
type = type.MakePointerType();
break;
}
types.Add(type);
}
info.argumentTypes = types.ToArray();
}
}
/// <summary>Annotation to define the original method for delegate injection</summary>
///
[AttributeUsage(AttributeTargets.Delegate, AllowMultiple = true)]
public class HarmonyDelegate : HarmonyPatch
{
/// <summary>An annotation that specifies a class to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
///
public HarmonyDelegate(Type declaringType)
: base(declaringType) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="argumentTypes">The argument types of the method or constructor to patch</param>
///
public HarmonyDelegate(Type declaringType, Type[] argumentTypes)
: base(declaringType, argumentTypes) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
///
public HarmonyDelegate(Type declaringType, string methodName)
: base(declaringType, methodName) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(Type declaringType, string methodName, params Type[] argumentTypes)
: base(declaringType, methodName, argumentTypes) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">Array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(declaringType, methodName, argumentTypes, argumentVariations) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
///
public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType)
: base(declaringType, MethodType.Normal)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType, params Type[] argumentTypes)
: base(declaringType, MethodType.Normal, argumentTypes)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">Array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(Type declaringType, MethodDispatchType methodDispatchType, Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(declaringType, MethodType.Normal, argumentTypes, argumentVariations)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="declaringType">The declaring class/type</param>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
///
public HarmonyDelegate(Type declaringType, string methodName, MethodDispatchType methodDispatchType)
: base(declaringType, methodName, MethodType.Normal)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
///
public HarmonyDelegate(string methodName)
: base(methodName) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(string methodName, params Type[] argumentTypes)
: base(methodName, argumentTypes) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(methodName, argumentTypes, argumentVariations) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodName">The name of the method, property or constructor to patch</param>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
///
public HarmonyDelegate(string methodName, MethodDispatchType methodDispatchType)
: base(methodName, MethodType.Normal)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies call dispatching mechanics for the delegate</summary>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
///
public HarmonyDelegate(MethodDispatchType methodDispatchType)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(MethodDispatchType methodDispatchType, params Type[] argumentTypes)
: base(MethodType.Normal, argumentTypes)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="methodDispatchType">The <see cref="MethodDispatchType"/></param>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(MethodDispatchType methodDispatchType, Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(MethodType.Normal, argumentTypes, argumentVariations)
{
info.nonVirtualDelegate = methodDispatchType == MethodDispatchType.Call;
}
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
///
public HarmonyDelegate(Type[] argumentTypes)
: base(argumentTypes) { }
/// <summary>An annotation that specifies a method, property or constructor to patch</summary>
/// <param name="argumentTypes">An array of argument types to target overloads</param>
/// <param name="argumentVariations">An array of <see cref="ArgumentType"/></param>
///
public HarmonyDelegate(Type[] argumentTypes, ArgumentType[] argumentVariations)
: base(argumentTypes, argumentVariations) { }
}
/// <summary>Annotation to define your standin methods for reverse patching</summary>
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class HarmonyReversePatch : HarmonyAttribute
{
/// <summary>An annotation that specifies the type of reverse patching</summary>
/// <param name="type">The <see cref="HarmonyReversePatchType"/> of the reverse patch</param>
///
public HarmonyReversePatch(HarmonyReversePatchType type = HarmonyReversePatchType.Original)
{
info.reversePatchType = type;
}
}
/// <summary>A Harmony annotation to define that all methods in a class are to be patched</summary>
///
[AttributeUsage(AttributeTargets.Class)]
public class HarmonyPatchAll : HarmonyAttribute
{
}
/// <summary>A Harmony annotation</summary>
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyPriority : HarmonyAttribute
{
/// <summary>A Harmony annotation to define patch priority</summary>
/// <param name="priority">The priority</param>
///
public HarmonyPriority(int priority)
{
info.priority = priority;
}
}
/// <summary>A Harmony annotation</summary>
///
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyBefore : HarmonyAttribute
{
/// <summary>A Harmony annotation to define that a patch comes before another patch</summary>
/// <param name="before">The array of harmony IDs of the other patches</param>
///
public HarmonyBefore(params string[] before)
{
info.before = before;
}
}
/// <summary>A Harmony annotation</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyAfter : HarmonyAttribute
{
/// <summary>A Harmony annotation to define that a patch comes after another patch</summary>
/// <param name="after">The array of harmony IDs of the other patches</param>
///
public HarmonyAfter(params string[] after)
{
info.after = after;
}
}
/// <summary>A Harmony annotation</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyDebug : HarmonyAttribute
{
/// <summary>A Harmony annotation to debug a patch (output uses <see cref="FileLog"/> to log to your Desktop)</summary>
///
public HarmonyDebug()
{
info.debug = true;
}
}
/// <summary>Specifies the Prepare function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyPrepare : Attribute
{
}
/// <summary>Specifies the Cleanup function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyCleanup : Attribute
{
}
/// <summary>Specifies the TargetMethod function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyTargetMethod : Attribute
{
}
/// <summary>Specifies the TargetMethods function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyTargetMethods : Attribute
{
}
/// <summary>Specifies the Prefix function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyPrefix : Attribute
{
}
/// <summary>Specifies the Postfix function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyPostfix : Attribute
{
}
/// <summary>Specifies the Transpiler function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyTranspiler : Attribute
{
}
/// <summary>Specifies the Finalizer function in a patch class</summary>
///
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyFinalizer : Attribute
{
}
/// <summary>A Harmony annotation</summary>
///
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
public class HarmonyArgument : Attribute
{
/// <summary>The name of the original argument</summary>
///
public string OriginalName { get; private set; }
/// <summary>The index of the original argument</summary>
///
public int Index { get; private set; }
/// <summary>The new name of the original argument</summary>
///
public string NewName { get; private set; }
/// <summary>An annotation to declare injected arguments by name</summary>
///
public HarmonyArgument(string originalName) : this(originalName, null)
{
}
/// <summary>An annotation to declare injected arguments by index</summary>
/// <param name="index">Zero-based index</param>
///
public HarmonyArgument(int index) : this(index, null)
{
}
/// <summary>An annotation to declare injected arguments by renaming them</summary>
/// <param name="originalName">Name of the original argument</param>
/// <param name="newName">New name</param>
///
public HarmonyArgument(string originalName, string newName)
{
OriginalName = originalName;
Index = -1;
NewName = newName;
}
/// <summary>An annotation to declare injected arguments by index and renaming them</summary>
/// <param name="index">Zero-based index</param>
/// <param name="name">New name</param>
///
public HarmonyArgument(int index, string name)
{
OriginalName = null;
Index = index;
NewName = name;
}
}
}
|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using Mechanical3.Core;
namespace Mechanical3.IO.FileSystems
{
//// NOTE: For still more speed, you could ditch abstract file systems, file paths and streams alltogether, and just use byte arrays directly.
//// Obviously this is a compromize between performance and ease of use.
/// <summary>
/// Provides performant, semi thread-safe access to an in-memory copy of the contants of an <see cref="IFileSystemReader"/>.
/// Access to <see cref="IFileSystemReader"/> members is thread-safe.
/// <see cref="Stream"/> instances returned are NOT thread-safe, and they must not be used after they are closed or disposed (one of which should happen exactly one time).
/// </summary>
public class SemiThreadSafeMemoryFileSystemReader : IFileSystemReader
{
#region ByteArrayReaderStream
/// <summary>
/// Provides thread-safe, read-only access to the wrapped byte array.
/// </summary>
private class ByteArrayReaderStream : Stream
{
//// NOTE: the default asynchronous implementations call their synchronous versions.
//// NOTE: we don't use Store*, to save a few allocations
#region ObjectPool
internal static class ObjectPool
{
private static readonly ConcurrentBag<ByteArrayReaderStream> Pool = new ConcurrentBag<ByteArrayReaderStream>();
internal static ByteArrayReaderStream Get( byte[] data )
{
ByteArrayReaderStream stream;
if( !Pool.TryTake(out stream) )
stream = new ByteArrayReaderStream();
stream.OnInitialize(data);
return stream;
}
internal static void Put( ByteArrayReaderStream stream )
{
Pool.Add(stream);
}
internal static void Clear()
{
ByteArrayReaderStream stream;
while( true )
{
if( Pool.TryTake(out stream) )
GC.SuppressFinalize(stream);
else
break; // pool is empty
}
}
}
#endregion
#region Private Fields
private byte[] array;
private int position; // NOTE: (position == length) == EOF
private bool isOpen;
#endregion
#region Constructor
private ByteArrayReaderStream()
: base()
{
}
#endregion
#region Private Methods
private void OnInitialize( byte[] data )
{
this.array = data;
this.position = 0;
this.isOpen = true;
}
private void OnClose()
{
this.isOpen = false;
this.array = null;
this.position = -1;
}
private void ThrowIfClosed()
{
if( !this.isOpen )
throw new ObjectDisposedException(message: "The stream was already closed!", innerException: null);
}
#endregion
#region Stream
protected override void Dispose( bool disposing )
{
this.OnClose();
ObjectPool.Put(this);
if( !disposing )
{
// called from finalizer
GC.ReRegisterForFinalize(this);
}
}
public override bool CanRead
{
get
{
this.ThrowIfClosed();
return true;
}
}
public override bool CanSeek
{
get
{
this.ThrowIfClosed();
return true;
}
}
public override bool CanTimeout
{
get
{
this.ThrowIfClosed();
return false;
}
}
public override bool CanWrite
{
get
{
this.ThrowIfClosed();
return false;
}
}
public override long Length
{
get
{
this.ThrowIfClosed();
return this.array.Length;
}
}
public override long Position
{
get
{
this.ThrowIfClosed();
return this.position;
}
set
{
this.ThrowIfClosed();
if( value < 0 || this.array.Length < value )
throw new ArgumentOutOfRangeException();
this.position = (int)value;
}
}
public override long Seek( long offset, SeekOrigin origin )
{
this.ThrowIfClosed();
int newPosition;
switch( origin )
{
case SeekOrigin.Begin:
newPosition = (int)offset;
break;
case SeekOrigin.Current:
newPosition = this.position + (int)offset;
break;
case SeekOrigin.End:
newPosition = this.array.Length + (int)offset;
break;
default:
throw new ArgumentException("Invalid SeekOrigin!");
}
if( newPosition < 0
|| newPosition > this.array.Length )
throw new ArgumentOutOfRangeException();
this.position = newPosition;
return this.position;
}
public override int ReadByte()
{
this.ThrowIfClosed();
if( this.position == this.array.Length )
{
// end of stream
return -1;
}
else
{
return this.array[this.position++];
}
}
public override int Read( byte[] buffer, int offset, int bytesToRead )
{
this.ThrowIfClosed();
int bytesLeft = this.array.Length - this.position;
if( bytesLeft < bytesToRead ) bytesToRead = bytesLeft;
if( bytesToRead == 0 )
return 0;
Buffer.BlockCopy(src: this.array, srcOffset: this.position, dst: buffer, dstOffset: offset, count: bytesToRead);
this.position += bytesToRead;
return bytesToRead;
}
public override void Flush()
{
throw new NotSupportedException();
}
public override void SetLength( long value )
{
throw new NotSupportedException();
}
public override void WriteByte( byte value )
{
throw new NotSupportedException();
}
public override void Write( byte[] buffer, int offset, int count )
{
throw new NotSupportedException();
}
#endregion
}
#endregion
#region Private Fields
/* From MSDN:
* A Dictionary can support multiple readers concurrently, as long as the collection is not modified.
* Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the
* rare case where an enumeration contends with write accesses, the collection must be locked during
* the entire enumeration. To allow the collection to be accessed by multiple threads for reading
* and writing, you must implement your own synchronization.
*
* ... (or there is also ConcurrentDictionary)
*/
//// NOTE: since after they are filled, the dictionaries won't be modified, we are fine.
private readonly FilePath[] rootFolderEntries;
private readonly Dictionary<FilePath, FilePath[]> nonRootFolderEntries;
private readonly Dictionary<FilePath, byte[]> fileContents;
private readonly Dictionary<FilePath, string> hostPaths;
private readonly string rootHostPath;
#endregion
#region Constructors
/// <summary>
/// Copies the current contents of the specified <see cref="IFileSystemReader"/>
/// into a new <see cref="SemiThreadSafeMemoryFileSystemReader"/> instance.
/// </summary>
/// <param name="readerToCopy">The abstract file system to copy the current contents of, into memory.</param>
/// <returns>A new <see cref="SemiThreadSafeMemoryFileSystemReader"/> instance.</returns>
public static SemiThreadSafeMemoryFileSystemReader CopyFrom( IFileSystemReader readerToCopy )
{
return new SemiThreadSafeMemoryFileSystemReader(readerToCopy);
}
/// <summary>
/// Initializes a new instance of the <see cref="SemiThreadSafeMemoryFileSystemReader"/> class.
/// </summary>
/// <param name="readerToCopy">The abstract file system to copy the current contents of, into memory.</param>
private SemiThreadSafeMemoryFileSystemReader( IFileSystemReader readerToCopy )
{
this.rootFolderEntries = readerToCopy.GetPaths();
this.nonRootFolderEntries = new Dictionary<FilePath, FilePath[]>();
this.fileContents = new Dictionary<FilePath, byte[]>();
if( readerToCopy.SupportsToHostPath )
{
this.hostPaths = new Dictionary<FilePath, string>();
this.rootHostPath = readerToCopy.ToHostPath(null);
}
using( var tmpStream = new MemoryStream() )
{
foreach( var e in this.rootFolderEntries )
this.AddRecursively(e, readerToCopy, tmpStream);
}
}
#endregion
#region Private Methods
private void AddRecursively( FilePath entry, IFileSystemReader readerToCopy, MemoryStream tmpStream )
{
if( entry.IsDirectory )
{
var subEntries = readerToCopy.GetPaths(entry);
this.nonRootFolderEntries.Add(entry, subEntries);
foreach( var e in subEntries )
this.AddRecursively(e, readerToCopy, tmpStream);
}
else
{
this.fileContents.Add(entry, ReadFileContents(entry, readerToCopy, tmpStream));
}
if( this.SupportsToHostPath )
this.hostPaths.Add(entry, readerToCopy.ToHostPath(entry));
}
private static byte[] ReadFileContents( FilePath filePath, IFileSystemReader readerToCopy, MemoryStream tmpStream )
{
tmpStream.SetLength(0);
long? fileSize = null;
if( readerToCopy.SupportsGetFileSize )
{
fileSize = readerToCopy.GetFileSize(filePath);
ThrowIfFileTooBig(filePath, fileSize.Value);
}
using( var stream = readerToCopy.ReadFile(filePath) )
{
if( !fileSize.HasValue
&& stream.CanSeek )
{
fileSize = stream.Length;
ThrowIfFileTooBig(filePath, fileSize.Value);
}
stream.CopyTo(tmpStream);
if( !fileSize.HasValue )
ThrowIfFileTooBig(filePath, tmpStream.Length);
return tmpStream.ToArray();
}
}
private static void ThrowIfFileTooBig( FilePath filePath, long fileSize )
{
if( fileSize > int.MaxValue ) // that's the largest our stream implementation can support
throw new Exception("One of the files is too large!").Store(nameof(filePath), filePath).Store(nameof(fileSize), fileSize);
}
#endregion
#region IFileSystemBase
/// <summary>
/// Gets a value indicating whether the ToHostPath method is supported.
/// </summary>
/// <value><c>true</c> if the method is supported; otherwise, <c>false</c>.</value>
public bool SupportsToHostPath
{
get { return this.hostPaths.NotNullReference(); }
}
/// <summary>
/// Gets the string the underlying system uses to represent the specified file or directory.
/// </summary>
/// <param name="path">The path to the file or directory.</param>
/// <returns>The string the underlying system uses to represent the specified <paramref name="path"/>.</returns>
public string ToHostPath( FilePath path )
{
if( !this.SupportsToHostPath )
throw new NotSupportedException().StoreFileLine();
if( path.NullReference() )
return this.rootHostPath;
string result;
if( this.hostPaths.TryGetValue(path, out result) )
return result;
else
throw new FileNotFoundException("The specified file or directory was not found!").Store(nameof(path), path);
}
#endregion
#region IFileSystemReader
/// <summary>
/// Gets the paths to the direct children of the specified directory.
/// Subdirectories are not searched.
/// </summary>
/// <param name="directoryPath">The path specifying the directory to list the direct children of; or <c>null</c> to specify the root of this file system.</param>
/// <returns>The paths of the files and directories found.</returns>
public FilePath[] GetPaths( FilePath directoryPath = null )
{
if( directoryPath.NotNullReference()
&& !directoryPath.IsDirectory )
throw new ArgumentException("Argument is not a directory!").Store(nameof(directoryPath), directoryPath);
FilePath[] paths;
if( directoryPath.NullReference() )
{
paths = this.rootFolderEntries;
}
else
{
if( !this.nonRootFolderEntries.TryGetValue(directoryPath, out paths) )
throw new FileNotFoundException("The specified file or directory was not found!").Store(nameof(directoryPath), directoryPath);
}
// NOTE: Unfortunately we need to make a copy, since arrays are writable.
// TODO: return ImmutableArray from GetPaths.
var copy = new FilePath[paths.Length];
Array.Copy(sourceArray: paths, destinationArray: copy, length: paths.Length);
return copy;
}
/// <summary>
/// Opens the specified file for reading.
/// </summary>
/// <param name="filePath">The path specifying the file to open.</param>
/// <returns>A <see cref="Stream"/> representing the file opened.</returns>
public Stream ReadFile( FilePath filePath )
{
if( filePath.NullReference()
|| filePath.IsDirectory )
throw new ArgumentException("Argument is not a file!").Store(nameof(filePath), filePath);
byte[] bytes;
if( !this.fileContents.TryGetValue(filePath, out bytes) )
throw new FileNotFoundException("The specified file or directory was not found!").Store(nameof(filePath), filePath);
return ByteArrayReaderStream.ObjectPool.Get(bytes);
}
/// <summary>
/// Gets a value indicating whether the GetFileSize method is supported.
/// </summary>
/// <value><c>true</c> if the method is supported; otherwise, <c>false</c>.</value>
public bool SupportsGetFileSize
{
get { return true; }
}
/// <summary>
/// Gets the size, in bytes, of the specified file.
/// </summary>
/// <param name="filePath">The file to get the size of.</param>
/// <returns>The size of the specified file in bytes.</returns>
public long GetFileSize( FilePath filePath )
{
if( filePath.NullReference()
|| filePath.IsDirectory )
throw new ArgumentException("Argument is not a file!").Store(nameof(filePath), filePath);
byte[] bytes;
if( !this.fileContents.TryGetValue(filePath, out bytes) )
throw new FileNotFoundException("The specified file or directory was not found!").Store(nameof(filePath), filePath);
return bytes.Length;
}
#endregion
}
}
|
//#define USE_TOUCH_SCRIPT
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
/*
* ドラッグ操作でのカメラの移動コントロールクラス
* マウス&タッチ対応
*/
namespace GarageKit
{
[RequireComponent(typeof(Camera))]
public class FlyThroughCamera : MonoBehaviour
{
public static bool winTouch = false;
public static bool updateEnable = true;
// フライスルーのコントロールタイプ
public enum FLYTHROUGH_CONTROLL_TYPE
{
DRAG = 0,
DRAG_HOLD
}
public FLYTHROUGH_CONTROLL_TYPE controllType;
// 移動軸の方向
public enum FLYTHROUGH_MOVE_TYPE
{
XZ = 0,
XY
}
public FLYTHROUGH_MOVE_TYPE moveType;
public Collider groundCollider;
public Collider limitAreaCollider;
public bool useLimitArea = false;
public float moveBias = 1.0f;
public float moveSmoothTime = 0.1f;
public bool dragInvertX = false;
public bool dragInvertY = false;
public float rotateBias = 1.0f;
public float rotateSmoothTime = 0.1f;
public bool rotateInvert = false;
public OrbitCamera combinationOrbitCamera;
private GameObject flyThroughRoot;
public GameObject FlyThroughRoot { get{ return flyThroughRoot; } }
private GameObject shiftTransformRoot;
public Transform ShiftTransform { get{ return shiftTransformRoot.transform; } }
private bool inputLock;
public bool IsInputLock { get{ return inputLock; } }
private object lockObject;
private Vector3 defaultPos;
private Quaternion defaultRot;
private bool isFirstTouch;
private Vector3 oldScrTouchPos;
private Vector3 dragDelta;
private Vector3 velocitySmoothPos;
private Vector3 dampDragDelta = Vector3.zero;
private Vector3 pushMoveDelta = Vector3.zero;
private float velocitySmoothRot;
private float dampRotateDelta = 0.0f;
private float pushRotateDelta = 0.0f;
public Vector3 currentPos { get{ return flyThroughRoot.transform.position; } }
public Quaternion currentRot { get{ return flyThroughRoot.transform.rotation; } }
void Awake()
{
}
void Start()
{
// 設定ファイルより入力タイプを取得
if(!ApplicationSetting.Instance.GetBool("UseMouse"))
winTouch = true;
inputLock = false;
// 地面上視点位置に回転ルートを設定する
Ray ray = new Ray(this.transform.position, this.transform.forward);
RaycastHit hitInfo;
if(groundCollider.Raycast(ray, out hitInfo, float.PositiveInfinity))
{
flyThroughRoot = new GameObject(this.gameObject.name + " FlyThrough Root");
flyThroughRoot.transform.SetParent(this.gameObject.transform.parent, false);
flyThroughRoot.transform.position = hitInfo.point;
flyThroughRoot.transform.rotation = Quaternion.identity;
shiftTransformRoot = new GameObject(this.gameObject.name + " ShiftTransform Root");
shiftTransformRoot.transform.SetParent(flyThroughRoot.transform, true);
shiftTransformRoot.transform.localPosition = Vector3.zero;
shiftTransformRoot.transform.localRotation = Quaternion.identity;
this.gameObject.transform.SetParent(shiftTransformRoot.transform, true);
}
else
{
Debug.LogWarning("FlyThroughCamera :: not set the ground collider !!");
return;
}
// 初期値を保存
defaultPos = flyThroughRoot.transform.position;
defaultRot = flyThroughRoot.transform.rotation;
ResetInput();
}
void Update()
{
if(!inputLock && ButtonObjectEvent.PressBtnsTotal == 0)
GetInput();
else
ResetInput();
UpdateFlyThrough();
UpdateOrbitCombination();
}
private void ResetInput()
{
isFirstTouch = true;
oldScrTouchPos = Vector3.zero;
dragDelta = Vector3.zero;
}
private void GetInput()
{
// for Touch
if(Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer)
{
if(Input.touchCount == 1)
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = Input.GetTouch(0).position;
if(isFirstTouch)
{
oldScrTouchPos = currentScrTouchPos;
isFirstTouch = false;
return;
}
dragDelta = currentScrTouchPos - oldScrTouchPos;
if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)
oldScrTouchPos = currentScrTouchPos;
}
else
ResetInput();
}
#if UNITY_STANDALONE_WIN
else if(Application.platform == RuntimePlatform.WindowsPlayer && winTouch)
{
#if !USE_TOUCH_SCRIPT
if(Input.touchCount == 1)
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = Input.touches[0].position;
#else
if(TouchScript.TouchManager.Instance.PressedPointersCount == 1)
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = TouchScript.TouchManager.Instance.PressedPointers[0].Position;
#endif
if(isFirstTouch)
{
oldScrTouchPos = currentScrTouchPos;
isFirstTouch = false;
return;
}
dragDelta = currentScrTouchPos - oldScrTouchPos;
if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)
oldScrTouchPos = currentScrTouchPos;
}
else
ResetInput();
}
#endif
// for Mouse
else
{
if(Input.GetMouseButton(0))
{
// ドラッグ量を計算
Vector3 currentScrTouchPos = Input.mousePosition;
if(isFirstTouch)
{
oldScrTouchPos = currentScrTouchPos;
isFirstTouch = false;
return;
}
dragDelta = currentScrTouchPos - oldScrTouchPos;
if(controllType == FLYTHROUGH_CONTROLL_TYPE.DRAG)
oldScrTouchPos = currentScrTouchPos;
}
else
ResetInput();
}
}
/// <summary>
/// Input更新のLock
/// </summary>
public void LockInput(object sender)
{
if(!inputLock)
{
lockObject = sender;
inputLock = true;
}
}
/// <summary>
/// Input更新のUnLock
/// </summary>
public void UnlockInput(object sender)
{
if(inputLock && lockObject == sender)
inputLock = false;
}
/// <summary>
/// フライスルーを更新
/// </summary>
private void UpdateFlyThrough()
{
if(!FlyThroughCamera.updateEnable || flyThroughRoot == null)
return;
// 位置
float dragX = dragDelta.x * (dragInvertX ? -1.0f : 1.0f);
float dragY = dragDelta.y * (dragInvertY ? -1.0f : 1.0f);
if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)
dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, 0.0f, dragY) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime);
else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)
dampDragDelta = Vector3.SmoothDamp(dampDragDelta, new Vector3(dragX, dragY, 0.0f) * moveBias + pushMoveDelta, ref velocitySmoothPos, moveSmoothTime);
flyThroughRoot.transform.Translate(dampDragDelta, Space.Self);
pushMoveDelta = Vector3.zero;
if(useLimitArea)
{
// 移動範囲限界を設定
if(limitAreaCollider != null)
{
Vector3 movingLimitMin = limitAreaCollider.bounds.min + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position;
Vector3 movingLimitMax = limitAreaCollider.bounds.max + limitAreaCollider.bounds.center - limitAreaCollider.gameObject.transform.position;
if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)
{
float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x);
float limitZ = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.z, movingLimitMax.z), movingLimitMin.z);
flyThroughRoot.transform.position = new Vector3(limitX, flyThroughRoot.transform.position.y, limitZ);
}
else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)
{
float limitX = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.x, movingLimitMax.x), movingLimitMin.x);
float limitY = Mathf.Max(Mathf.Min(flyThroughRoot.transform.position.y, movingLimitMax.y), movingLimitMin.y);
flyThroughRoot.transform.position = new Vector3(limitX, limitY, flyThroughRoot.transform.position.z);
}
}
}
// 方向
dampRotateDelta = Mathf.SmoothDamp(dampRotateDelta, pushRotateDelta * rotateBias, ref velocitySmoothRot, rotateSmoothTime);
if(moveType == FLYTHROUGH_MOVE_TYPE.XZ)
flyThroughRoot.transform.Rotate(Vector3.up, dampRotateDelta, Space.Self);
else if(moveType == FLYTHROUGH_MOVE_TYPE.XY)
flyThroughRoot.transform.Rotate(Vector3.forward, dampRotateDelta, Space.Self);
pushRotateDelta = 0.0f;
}
private void UpdateOrbitCombination()
{
// 連携機能
if(combinationOrbitCamera != null && combinationOrbitCamera.OrbitRoot != null)
{
Vector3 lookPoint = combinationOrbitCamera.OrbitRoot.transform.position;
Transform orbitParent = combinationOrbitCamera.OrbitRoot.transform.parent;
combinationOrbitCamera.OrbitRoot.transform.parent = null;
flyThroughRoot.transform.LookAt(lookPoint, Vector3.up);
flyThroughRoot.transform.rotation = Quaternion.Euler(
0.0f, flyThroughRoot.transform.rotation.eulerAngles.y + 180.0f, 0.0f);
combinationOrbitCamera.OrbitRoot.transform.parent = orbitParent;
}
}
/// <summary>
/// 目標位置にカメラを移動させる
/// </summary>
public void MoveToFlyThrough(Vector3 targetPosition, float time = 1.0f)
{
dampDragDelta = Vector3.zero;
flyThroughRoot.transform.DOMove(targetPosition, time)
.SetEase(Ease.OutCubic)
.Play();
}
/// <summary>
/// 指定値でカメラを移動させる
/// </summary>
public void TranslateToFlyThrough(Vector3 move)
{
dampDragDelta = Vector3.zero;
flyThroughRoot.transform.Translate(move, Space.Self);
}
/// <summary>
/// 目標方向にカメラを回転させる
/// </summary>
public void RotateToFlyThrough(float targetAngle, float time = 1.0f)
{
dampRotateDelta = 0.0f;
Vector3 targetEulerAngles = flyThroughRoot.transform.rotation.eulerAngles;
targetEulerAngles.y = targetAngle;
flyThroughRoot.transform.DORotate(targetEulerAngles, time)
.SetEase(Ease.OutCubic)
.Play();
}
/// <summary>
/// 外部トリガーで移動させる
/// </summary>
public void PushMove(Vector3 move)
{
pushMoveDelta = move;
}
/// <summary>
/// 外部トリガーでカメラ方向を回転させる
/// </summary>
public void PushRotate(float rotate)
{
pushRotateDelta = rotate;
}
/// <summary>
/// フライスルーを初期化
/// </summary>
public void ResetFlyThrough()
{
ResetInput();
MoveToFlyThrough(defaultPos);
RotateToFlyThrough(defaultRot.eulerAngles.y);
}
}
}
|
using System.Threading;
using CodeTiger;
using Xunit;
namespace UnitTests.CodeTiger
{
public class LazyTests
{
public class Create1
{
[Fact]
public void SetsIsValueCreatedToFalse()
{
var target = Lazy.Create<object>();
Assert.False(target.IsValueCreated);
}
[Fact]
public void ReturnsDefaultValueOfObject()
{
var target = Lazy.Create<object>();
Assert.NotNull(target.Value);
Assert.Equal(typeof(object), target.Value.GetType());
}
[Fact]
public void ReturnsDefaultValueOfBoolean()
{
var target = Lazy.Create<bool>();
Assert.Equal(new bool(), target.Value);
}
[Fact]
public void ReturnsDefaultValueOfDecimal()
{
var target = Lazy.Create<decimal>();
Assert.Equal(new decimal(), target.Value);
}
}
public class Create1_Boolean
{
[Theory]
[InlineData(false)]
[InlineData(true)]
public void SetsIsValueCreatedToFalse(bool isThreadSafe)
{
var target = Lazy.Create<object>(isThreadSafe);
Assert.False(target.IsValueCreated);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ReturnsDefaultValueOfObject(bool isThreadSafe)
{
var target = Lazy.Create<object>(isThreadSafe);
Assert.NotNull(target.Value);
Assert.Equal(typeof(object), target.Value.GetType());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ReturnsDefaultValueOfBoolean(bool isThreadSafe)
{
var target = Lazy.Create<bool>(isThreadSafe);
Assert.Equal(new bool(), target.Value);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ReturnsDefaultValueOfDecimal(bool isThreadSafe)
{
var target = Lazy.Create<decimal>(isThreadSafe);
Assert.Equal(new decimal(), target.Value);
}
}
public class Create1_LazyThreadSafetyMode
{
[Theory]
[InlineData(LazyThreadSafetyMode.None)]
[InlineData(LazyThreadSafetyMode.PublicationOnly)]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
public void SetsIsValueCreatedToFalse(LazyThreadSafetyMode mode)
{
var target = Lazy.Create<object>(mode);
Assert.False(target.IsValueCreated);
}
[Theory]
[InlineData(LazyThreadSafetyMode.None)]
[InlineData(LazyThreadSafetyMode.PublicationOnly)]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
public void CreatesTaskWhichReturnsDefaultValueOfObject(LazyThreadSafetyMode mode)
{
var target = Lazy.Create<object>(mode);
Assert.NotNull(target.Value);
Assert.Equal(typeof(object), target.Value.GetType());
}
[Theory]
[InlineData(LazyThreadSafetyMode.None)]
[InlineData(LazyThreadSafetyMode.PublicationOnly)]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
public void CreatesTaskWhichReturnsDefaultValueOfBoolean(LazyThreadSafetyMode mode)
{
var target = Lazy.Create<bool>(mode);
Assert.Equal(new bool(), target.Value);
}
[Theory]
[InlineData(LazyThreadSafetyMode.None)]
[InlineData(LazyThreadSafetyMode.PublicationOnly)]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
public void CreatesTaskWhichReturnsDefaultValueOfDecimal(LazyThreadSafetyMode mode)
{
var target = Lazy.Create<decimal>(mode);
Assert.Equal(new decimal(), target.Value);
}
}
public class Create1_FuncOfTaskOfT1
{
[Fact]
public void SetsIsValueCreatedToFalse()
{
object expected = new object();
var target = Lazy.Create(() => expected);
Assert.False(target.IsValueCreated);
}
[Fact]
public void SetsValueToProvidedObject()
{
object expected = new object();
var target = Lazy.Create(() => expected);
Assert.Same(expected, target.Value);
}
}
public class Create1_FuncOfTaskOfT1_Boolean
{
[Theory]
[InlineData(false)]
[InlineData(true)]
public void SetsIsValueCreatedToFalse(bool isThreadSafe)
{
object expected = new object();
var target = Lazy.Create(() => expected, isThreadSafe);
Assert.False(target.IsValueCreated);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void SetsValueToProvidedTask(bool isThreadSafe)
{
object expected = new object();
var target = Lazy.Create(() => expected, isThreadSafe);
Assert.Same(expected, target.Value);
}
}
public class Create1_FuncOfTaskOfT1_LazyThreadSafetyMode
{
[Theory]
[InlineData(LazyThreadSafetyMode.None)]
[InlineData(LazyThreadSafetyMode.PublicationOnly)]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
public void SetsIsValueCreatedToFalse(LazyThreadSafetyMode mode)
{
object expected = new object();
var target = Lazy.Create(() => expected, mode);
Assert.False(target.IsValueCreated);
}
[Theory]
[InlineData(LazyThreadSafetyMode.None)]
[InlineData(LazyThreadSafetyMode.PublicationOnly)]
[InlineData(LazyThreadSafetyMode.ExecutionAndPublication)]
public void SetsValueToProvidedTask(LazyThreadSafetyMode mode)
{
object expected = new object();
var target = Lazy.Create(() => expected, mode);
Assert.Same(expected, target.Value);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Globalization;
namespace DevTreks.Extensions
{
/// <summary>
///Purpose: Serialize and deserialize a food nutrition cost object.
/// This calculator is used with inputs to calculate costs.
///Author: www.devtreks.org
///Date: 2014, June
///References: www.devtreks.org/helptreks/linkedviews/help/linkedview/HelpFile/148
///NOTES 1. Extends the base object MNSR1 object
///</summary>
public class MNC1Calculator : MNSR1
{
public MNC1Calculator()
: base()
{
//health care cost object
InitMNC1Properties();
}
//copy constructor
public MNC1Calculator(MNC1Calculator lca1Calc)
: base(lca1Calc)
{
CopyMNC1Properties(lca1Calc);
}
//need to store locals and update parent input.ocprice, aohprice, capprice
public Input MNCInput { get; set; }
public virtual void InitMNC1Properties()
{
//avoid null references to properties
this.InitCalculatorProperties();
this.InitSharedObjectProperties();
this.InitMNSR1Properties();
this.MNCInput = new Input();
}
public virtual void CopyMNC1Properties(
MNC1Calculator calculator)
{
this.CopyCalculatorProperties(calculator);
this.CopySharedObjectProperties(calculator);
this.CopyMNSR1Properties(calculator);
this.MNCInput = new Input(calculator.MNCInput);
}
//set the class properties using the XElement
public virtual void SetMNC1Properties(XElement calculator,
XElement currentElement)
{
this.SetCalculatorProperties(calculator);
//need the aggregating params (label, groupid, typeid and Date for sorting)
this.SetSharedObjectProperties(currentElement);
this.SetMNSR1Properties(calculator);
}
//attname and attvalue generally passed in from a reader
public virtual void SetMNC1Property(string attName,
string attValue)
{
this.SetMNSR1Property(attName, attValue);
}
public void SetMNC1Attributes(string attNameExtension,
ref XElement calculator)
{
//must remove old unwanted attributes
if (calculator != null)
{
//do not remove atts here, they were removed in prior this.MNCInput.SetInputAtts
//and now include good locals
//this also sets the aggregating atts
this.SetAndRemoveCalculatorAttributes(attNameExtension, ref calculator);
}
this.SetMNSR1Attributes(attNameExtension, ref calculator);
}
public virtual void SetMNC1Attributes(string attNameExtension,
ref XmlWriter writer)
{
//note must first use use either setanalyzeratts or SetCalculatorAttributes(attNameExtension, ref writer);
this.SetMNSR1Attributes(attNameExtension, ref writer);
}
public bool SetMNC1Calculations(
MN1CalculatorHelper.CALCULATOR_TYPES calculatorType,
CalculatorParameters calcParameters, ref XElement calculator,
ref XElement currentElement)
{
bool bHasCalculations = false;
string sErrorMessage = string.Empty;
InitMNC1Properties();
//deserialize xml to object
//set the base input properties (updates base input prices)
//locals come from input
this.MNCInput.SetInputProperties(calcParameters,
calculator, currentElement);
//set the calculator
this.SetMNC1Properties(calculator, currentElement);
bHasCalculations = RunMNC1Calculations(calcParameters);
if (calcParameters.SubApplicationType == Constants.SUBAPPLICATION_TYPES.inputprices)
{
//serialize object back to xml and fill in updates list
//this also removes atts
this.MNCInput.SetInputAttributes(calcParameters,
ref currentElement, calcParameters.Updates);
}
else
{
//no db updates outside base output
this.MNCInput.SetInputAttributes(calcParameters,
ref currentElement, null);
}
//this sets and removes some atts
this.SetMNC1Attributes(string.Empty, ref calculator);
//set the totals into calculator
this.MNCInput.SetNewInputAttributes(calcParameters, ref calculator);
//set calculatorid (primary way to display calculation attributes)
CalculatorHelpers.SetCalculatorId(
calculator, currentElement);
calcParameters.ErrorMessage = sErrorMessage;
return bHasCalculations;
}
public bool RunMNC1Calculations(CalculatorParameters calcParameters)
{
bool bHasCalculations = false;
//first figure quantities
UpdateBaseInputUnitPrices(calcParameters);
//then figure whether ocamount or capamount should be used as a multiplier
//times calcd by stock.multiplier
double multiplier = GetMultiplierForMNSR1();
//run cost calcs
bHasCalculations = this.RunMNSR1Calculations(calcParameters, multiplier);
return bHasCalculations;
}
private void UpdateBaseInputUnitPrices(
CalculatorParameters calcParameters)
{
//is being able to change ins and outs in tech elements scalable?? double check
//check illegal divisors
this.ContainerSizeInSSUnits = (this.ContainerSizeInSSUnits == 0)
? -1 : this.ContainerSizeInSSUnits;
this.TypicalServingsPerContainer = this.ContainerSizeInSSUnits / this.TypicalServingSize;
this.ActualServingsPerContainer = this.ContainerSizeInSSUnits / this.ActualServingSize;
//Actual serving size has to be 1 unit of hh measure
if (calcParameters.SubApplicationType == Constants.SUBAPPLICATION_TYPES.inputprices)
{
//tech analysis can change from base
this.MNCInput.OCAmount = 1;
}
//calculate OCPrice as a unit cost per serving (not per each unit of serving or ContainerSizeInSSUnits)
this.MNCInput.OCPrice = this.ContainerPrice / this.ActualServingsPerContainer;
//serving size is the unit cost
this.MNCInput.OCUnit = string.Concat(this.ActualServingSize, " ", this.ServingSizeUnit);
//transfer capprice (benefits need to track the package price using calculator.props)
this.MNCInput.CAPPrice = this.ContainerPrice;
this.MNCInput.CAPUnit = this.ContainerUnit;
if (this.MNCInput.CAPAmount > 0)
{
this.ServingCost = this.MNCInput.CAPPrice * this.MNCInput.CAPAmount;
this.MNCInput.TotalCAP = this.ServingCost;
}
else
{
//calculate cost per actual serving
//note that this can change when the input is added elsewhere
this.ServingCost = this.MNCInput.OCPrice * this.MNCInput.OCAmount;
this.MNCInput.TotalOC = this.ServingCost;
}
}
public double GetMultiplierForMNSR1()
{
double multiplier = 1;
if (this.MNCInput.CAPAmount > 0)
{
//cap budget can use container size for nutrient values
multiplier = this.ActualServingsPerContainer * this.MNCInput.CAPAmount;
}
else if (this.MNCInput.CAPAmount <= 0)
{
//op budget can use ocamount for nutrient values
multiplier = this.MNCInput.OCAmount;
}
return multiplier;
}
}
}
|
using System;
using CommandLine;
using System.IO;
using Nancy.Hosting.Self;
using SeudoBuild.Core;
using SeudoBuild.Core.FileSystems;
using SeudoBuild.Pipeline;
using SeudoBuild.Net;
namespace SeudoBuild.Agent
{
class Program
{
private const string Header = @"
_ _ _ _ _
___ ___ _ _ _| |___| |_ _ _|_| |_| |
|_ -| -_| | | . | . | . | | | | | . |
|___|___|___|___|___|___|___|_|_|___|
";
private static ILogger _logger;
[Verb("build", HelpText = "Create a local build.")]
private class BuildSubOptions
{
[Option('t', "build-target", HelpText = "Name of the build target as specified in the project configuration file. If no build target is specified, the first target will be used.")]
public string BuildTarget { get; set; }
[Option('o', "output-folder", HelpText = "Path to the build output folder.")]
public string OutputPath { get; set; }
[Value(0, MetaName = "project", HelpText = "Path to a project configuration file.", Required = true)]
public string ProjectConfigPath { get; set; }
}
[Verb("scan", HelpText = "List build agents found on the local network.")]
private class ScanSubOptions
{
}
[Verb("submit", HelpText = "Submit a build request for a remote build agent to fulfill.")]
private class SubmitSubOptions
{
[Option('p', "project-config", HelpText = "Path to a project configuration file.", Required = true)]
public string ProjectConfigPath { get; set; }
[Option('t', "build-target", HelpText = "Name of the target to build as specified in the project configuration file.")]
public string BuildTarget { get; set; }
[Option('a', "agent-name", HelpText = "The unique name of a specific build agent. If not set, the job will be broadcast to all available agents.")]
public string AgentName { get; set; }
}
[Verb("queue", HelpText = "Queue build requests received over the network.")]
private class QueueSubOptions
{
[Option('n', "agent-name", HelpText = "A unique name for the build agent. If not set, a name will be generated.")]
public string AgentName { get; set; }
[Option('p', "port", HelpText = "Port on which to listen for build queue messages.")]
public int? Port { get; set; }
}
[Verb("deploy", HelpText = "Listen for deployment messages.")]
private class DeploySubOptions
{
}
[Verb("name", Hidden = true)]
private class NameSubOptions
{
[Option('r', "random")]
public bool Random { get; set; }
}
public static void Main(string[] args)
{
_logger = new Logger();
Console.Title = "SeudoBuild";
Parser.Default.ParseArguments<BuildSubOptions, ScanSubOptions, SubmitSubOptions, QueueSubOptions, DeploySubOptions, NameSubOptions>(args)
.MapResult(
(BuildSubOptions opts) => Build(opts),
(ScanSubOptions opts) => Scan(opts),
(SubmitSubOptions opts) => Submit(opts),
(QueueSubOptions opts) => Queue(opts),
(DeploySubOptions opts) => Deploy(opts),
(NameSubOptions opts) => ShowAgentName(opts),
errs => 1
);
}
/// <summary>
/// Build a single target, then exit.
/// </summary>
private static int Build(BuildSubOptions opts)
{
Console.Title = "SeudoBuild • Build";
Console.WriteLine(Header);
// Load pipeline modules
var factory = new ModuleLoaderFactory();
IModuleLoader moduleLoader = factory.Create(_logger);
// Load project config
ProjectConfig projectConfig = null;
try
{
var fs = new WindowsFileSystem();
var serializer = new Serializer(fs);
var converters = moduleLoader.Registry.GetJsonConverters();
projectConfig = serializer.DeserializeFromFile<ProjectConfig>(opts.ProjectConfigPath, converters);
}
catch (Exception e)
{
Console.WriteLine("Can't parse project config:");
Console.WriteLine(e.Message);
return 1;
}
// Execute build
var builder = new Builder(moduleLoader, _logger);
var parentDirectory = opts.OutputPath;
if (string.IsNullOrEmpty(parentDirectory))
{
// Config file's directory
parentDirectory = new FileInfo(opts.ProjectConfigPath).Directory?.FullName;
}
var pipeline = new PipelineRunner(new PipelineConfig { BaseDirectory = parentDirectory }, _logger);
bool success = builder.Build(pipeline, projectConfig, opts.BuildTarget);
return success ? 0 : 1;
}
/// <summary>
/// Discover build agents on the network.
/// </summary>
private static int Scan(ScanSubOptions opts)
{
Console.Title = "SeudoBuild • Scan";
Console.WriteLine(Header);
Console.WriteLine("Looking for build agents. Press any key to exit.");
// FIXME fill in port from command line argument
var locator = new AgentLocator(5511);
try
{
locator.Start();
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Could not start build agent discovery client");
Console.ResetColor();
return 1;
}
// FIXME don't hard-code port
locator.AgentFound += (agent) =>
{
_logger.Write($"{agent.AgentName} ({agent.Address})", LogType.Bullet);
};
locator.AgentLost += (agent) =>
{
_logger.Write($"Lost agent: {agent.AgentName} ({agent.Address})", LogType.Bullet);
};
Console.WriteLine();
Console.ReadKey();
return 0;
}
/// <summary>
/// Submit a build job to another agent.
/// </summary>
private static int Submit(SubmitSubOptions opts)
{
Console.Title = "SeudoBuild • Submit";
Console.WriteLine(Header);
string configJson = null;
try
{
configJson = File.ReadAllText(opts.ProjectConfigPath);
}
catch
{
_logger.Write("Project could not be read from " + opts.ProjectConfigPath, LogType.Failure);
return 1;
}
var buildSubmitter = new BuildSubmitter(_logger);
try
{
// Find agent on the network, with timeout
var discoveryClient = new UdpDiscoveryClient();
buildSubmitter.Submit(discoveryClient, configJson, opts.BuildTarget, opts.AgentName);
}
catch (Exception e)
{
_logger.Write("Could not submit job: " + e.Message, LogType.Failure);
return 1;
}
return 0;
}
/// <summary>
/// Receive build jobs from other agents or clients, queue them, and execute them.
/// Continue listening until user exits.
/// </summary>
private static int Queue(QueueSubOptions opts)
{
Console.Title = "SeudoBuild • Queue";
Console.WriteLine(Header);
//string agentName = string.IsNullOrEmpty(opts.AgentName) ? AgentName.GetUniqueAgentName() : opts.AgentName;
// FIXME pull port from command line argument, and incorporate into ServerBeacon object
int port = 5511;
if (opts.Port.HasValue)
{
port = opts.Port.Value;
}
// Starting the Nancy server will automatically execute the Bootstrapper class
var uri = new Uri($"http://localhost:{port}");
using (var host = new NancyHost(uri))
{
_logger.Write("");
try
{
host.Start();
_logger.Write("Build Queue", LogType.Header);
_logger.Write("");
_logger.Write("Started build agent server: " + uri, LogType.Bullet);
try
{
// FIXME configure the port from a command line argument
var serverInfo = new UdpDiscoveryBeacon { Port = 5511 };
var discovery = new UdpDiscoveryServer(serverInfo);
discovery.Start();
_logger.Write("Build agent discovery beacon started", LogType.Bullet);
}
catch
{
_logger.Write("Could not initialize build agent discovery beacon", LogType.Alert);
}
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Could not start build server: " + e.Message);
Console.ResetColor();
return 1;
}
Console.WriteLine("");
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
return 0;
}
/// <summary>
/// Deploy a build product on the local machine.
/// </summary>
private static int Deploy(DeploySubOptions opts)
{
return 0;
}
/// <summary>
/// Display the unique name for this agent.
/// </summary>
private static int ShowAgentName(NameSubOptions opts)
{
string name;
name = opts.Random ? AgentName.GetRandomName() : AgentName.GetUniqueAgentName();
Console.WriteLine();
Console.WriteLine(name);
Console.WriteLine();
return 0;
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using StockExchangeYahooFinance.DbContext;
namespace StockExchangeYahooFinance.Migrations
{
[DbContext(typeof(YahooFinanceDbContext))]
[Migration("20170419132834_updateExAddCountry")]
partial class updateExAddCountry
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.1")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Companies", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ADR_TSO");
b.Property<string>("ExchangeId");
b.Property<string>("IPOyear");
b.Property<string>("IndustryId");
b.Property<string>("LastSale");
b.Property<string>("MarketCap");
b.Property<string>("Name");
b.Property<string>("RegionId");
b.Property<string>("SectorId");
b.Property<string>("Symbol");
b.Property<string>("Type");
b.HasKey("Id");
b.HasIndex("ExchangeId");
b.HasIndex("IndustryId");
b.HasIndex("RegionId");
b.HasIndex("SectorId");
b.ToTable("Companies");
});
modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Country", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("CountryCode");
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Country");
});
modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Currencies", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Code");
b.Property<string>("Currency");
b.Property<string>("Entity");
b.Property<string>("MinorUnit");
b.Property<int>("NumericCode");
b.HasKey("Id");
b.ToTable("Currencies");
});
modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Exchange", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClosingTimeLocal");
b.Property<string>("DataProvider");
b.Property<string>("Delay");
b.Property<string>("Name");
b.Property<string>("OpeningTimeLocal");
b.Property<string>("RegionId");
b.Property<string>("StockExchangeId");
b.Property<string>("Suffix");
b.Property<string>("TradingDays");
b.Property<string>("UtcOffsetStandardTime");
b.HasKey("Id");
b.HasIndex("RegionId");
b.ToTable("Exchange");
});
modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.FinanceModel", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("AfterHoursChangeRealtime");
b.Property<string>("AnnualizedGain");
b.Property<string>("Ask");
b.Property<string>("AskRealtime");
b.Property<string>("AverageDailyVolume");
b.Property<string>("Bid");
b.Property<string>("BidRealtime");
b.Property<string>("BookValue");
b.Property<string>("Change");
b.Property<string>("ChangeFromFiftydayMovingAverage");
b.Property<string>("ChangeFromTwoHundreddayMovingAverage");
b.Property<string>("ChangeFromYearHigh");
b.Property<string>("ChangeFromYearLow");
b.Property<string>("ChangePercentRealtime");
b.Property<string>("ChangeRealtime");
b.Property<string>("Change_PercentChange");
b.Property<string>("ChangeinPercent");
b.Property<string>("Commission");
b.Property<string>("CompaniesId");
b.Property<string>("CurencyId");
b.Property<string>("CurrenciesId");
b.Property<string>("Currency");
b.Property<string>("Date");
b.Property<string>("DaysHigh");
b.Property<string>("DaysLow");
b.Property<string>("DaysRange");
b.Property<string>("DaysRangeRealtime");
b.Property<string>("DaysValueChange");
b.Property<string>("DaysValueChangeRealtime");
b.Property<string>("DividendPayDate");
b.Property<string>("DividendShare");
b.Property<string>("DividendYield");
b.Property<string>("EBITDA");
b.Property<string>("EPSEstimateCurrentYear");
b.Property<string>("EPSEstimateNextQuarter");
b.Property<string>("EPSEstimateNextYear");
b.Property<string>("EarningsShare");
b.Property<string>("ErrorIndicationreturnedforsymbolchangedinvalid");
b.Property<string>("ExDividendDate");
b.Property<string>("FiftydayMovingAverage");
b.Property<string>("HighLimit");
b.Property<string>("HoldingsGain");
b.Property<string>("HoldingsGainPercent");
b.Property<string>("HoldingsGainPercentRealtime");
b.Property<string>("HoldingsGainRealtime");
b.Property<string>("HoldingsValue");
b.Property<string>("HoldingsValueRealtime");
b.Property<string>("LastTradeDate");
b.Property<string>("LastTradePriceOnly");
b.Property<string>("LastTradeRealtimeWithTime");
b.Property<string>("LastTradeTime");
b.Property<string>("LastTradeWithTime");
b.Property<string>("LowLimit");
b.Property<string>("MarketCapRealtime");
b.Property<string>("MarketCapitalization");
b.Property<string>("MoreInfo");
b.Property<string>("Name");
b.Property<string>("Notes");
b.Property<string>("OneyrTargetPrice");
b.Property<string>("Open");
b.Property<string>("OrderBookRealtime");
b.Property<string>("PEGRatio");
b.Property<string>("PERatio");
b.Property<string>("PERatioRealtime");
b.Property<string>("PercebtChangeFromYearHigh");
b.Property<string>("PercentChange");
b.Property<string>("PercentChangeFromFiftydayMovingAverage");
b.Property<string>("PercentChangeFromTwoHundreddayMovingAverage");
b.Property<string>("PercentChangeFromYearLow");
b.Property<string>("PreviousClose");
b.Property<string>("PriceBook");
b.Property<string>("PriceEPSEstimateCurrentYear");
b.Property<string>("PriceEPSEstimateNextYear");
b.Property<string>("PricePaid");
b.Property<string>("PriceSales");
b.Property<string>("Rate");
b.Property<string>("SharesOwned");
b.Property<string>("ShortRatio");
b.Property<string>("StockExchange");
b.Property<string>("Symbol");
b.Property<string>("TickerTrend");
b.Property<string>("Time");
b.Property<string>("TradeDate");
b.Property<string>("TwoHundreddayMovingAverage");
b.Property<string>("Volume");
b.Property<string>("YearHigh");
b.Property<string>("YearLow");
b.Property<string>("YearRange");
b.HasKey("Id");
b.HasIndex("CompaniesId");
b.HasIndex("CurrenciesId");
b.ToTable("FinanceModel");
});
modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Industry", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Industrie");
});
modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Region", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Region");
});
modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Sector", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Name");
b.HasKey("Id");
b.ToTable("Sector");
});
modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Companies", b =>
{
b.HasOne("StockExchangeYahooFinance.Data.Models.Exchange", "Exchange")
.WithMany()
.HasForeignKey("ExchangeId");
b.HasOne("StockExchangeYahooFinance.Data.Models.Industry", "Industry")
.WithMany()
.HasForeignKey("IndustryId");
b.HasOne("StockExchangeYahooFinance.Data.Models.Region", "Region")
.WithMany()
.HasForeignKey("RegionId");
b.HasOne("StockExchangeYahooFinance.Data.Models.Sector", "Sector")
.WithMany()
.HasForeignKey("SectorId");
});
modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.Exchange", b =>
{
b.HasOne("StockExchangeYahooFinance.Data.Models.Region", "Region")
.WithMany()
.HasForeignKey("RegionId");
});
modelBuilder.Entity("StockExchangeYahooFinance.Data.Models.FinanceModel", b =>
{
b.HasOne("StockExchangeYahooFinance.Data.Models.Companies", "Companies")
.WithMany()
.HasForeignKey("CompaniesId");
b.HasOne("StockExchangeYahooFinance.Data.Models.Currencies", "Currencies")
.WithMany()
.HasForeignKey("CurrenciesId");
});
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using PowerLib.System;
using PowerLib.System.Collections;
using PowerLib.System.IO;
using PowerLib.System.IO.Streamed.Typed;
using PowerLib.System.Numerics;
using PowerLib.System.Data.SqlTypes.Numerics;
namespace PowerLib.System.Data.SqlTypes.Collections
{
[SqlUserDefinedType(Format.UserDefined, Name = "GradAngleCollection", IsByteOrdered = true, IsFixedLength = false, MaxByteSize = -1)]
public sealed class SqlGradAngleCollection : INullable, IBinarySerialize
{
private List<GradAngle?> _list;
#region Contructors
public SqlGradAngleCollection()
{
_list = null;
}
public SqlGradAngleCollection(IEnumerable<GradAngle?> coll)
{
_list = coll != null ? new List<GradAngle?>(coll) : null;
}
private SqlGradAngleCollection(List<GradAngle?> list)
{
_list = list;
}
#endregion
#region Properties
public List<GradAngle?> List
{
get { return _list; }
set { _list = value; }
}
public static SqlGradAngleCollection Null
{
get { return new SqlGradAngleCollection(); }
}
public bool IsNull
{
get { return _list == null; }
}
public SqlInt32 Count
{
get { return _list != null ? _list.Count : SqlInt32.Null; }
}
#endregion
#region Methods
public static SqlGradAngleCollection Parse(SqlString s)
{
if (s.IsNull)
return Null;
return new SqlGradAngleCollection(SqlFormatting.ParseCollection<GradAngle?>(s.Value,
t => !t.Equals(SqlFormatting.NullText, StringComparison.InvariantCultureIgnoreCase) ? SqlGradAngle.Parse(t).Value : default(GradAngle?)));
}
public override String ToString()
{
return SqlFormatting.Format(_list, t => (t.HasValue ? new SqlGradAngle(t.Value) : SqlGradAngle.Null).ToString());
}
[SqlMethod(IsMutator = true)]
public void Clear()
{
_list.Clear();
}
[SqlMethod(IsMutator = true)]
public void AddItem(SqlGradAngle value)
{
_list.Add(value.IsNull ? default(GradAngle?) : value.Value);
}
[SqlMethod(IsMutator = true)]
public void InsertItem(SqlInt32 index, SqlGradAngle value)
{
_list.Insert(index.IsNull ? _list.Count : index.Value, value.IsNull ? default(GradAngle?) : value.Value);
}
[SqlMethod(IsMutator = true)]
public void RemoveItem(SqlGradAngle value)
{
_list.Remove(value.IsNull ? default(GradAngle?) : value.Value);
}
[SqlMethod(IsMutator = true)]
public void RemoveAt(SqlInt32 index)
{
if (index.IsNull)
return;
_list.RemoveAt(index.Value);
}
[SqlMethod(IsMutator = true)]
public void SetItem(SqlInt32 index, SqlGradAngle value)
{
if (index.IsNull)
return;
_list[index.Value] = value.IsNull ? default(GradAngle?) : value.Value;
}
[SqlMethod(IsMutator = true)]
public void AddRange(SqlGradAngleCollection coll)
{
if (coll.IsNull)
return;
_list.AddRange(coll._list);
}
[SqlMethod(IsMutator = true)]
public void AddRepeat(SqlGradAngle value, SqlInt32 count)
{
if (count.IsNull)
return;
_list.AddRepeat(value.IsNull ? default(GradAngle?) : value.Value, count.Value);
}
[SqlMethod(IsMutator = true)]
public void InsertRange(SqlInt32 index, SqlGradAngleCollection coll)
{
if (coll.IsNull)
return;
int indexValue = !index.IsNull ? index.Value : _list.Count;
_list.InsertRange(indexValue, coll._list);
}
[SqlMethod(IsMutator = true)]
public void InsertRepeat(SqlInt32 index, SqlGradAngle value, SqlInt32 count)
{
if (count.IsNull)
return;
int indexValue = !index.IsNull ? index.Value : _list.Count;
_list.InsertRepeat(indexValue, value.IsNull ? default(GradAngle?) : value.Value, count.Value);
}
[SqlMethod(IsMutator = true)]
public void SetRange(SqlInt32 index, SqlGradAngleCollection range)
{
if (range.IsNull)
return;
int indexValue = index.IsNull ? _list.Count - Comparable.Min(_list.Count, range._list.Count) : index.Value;
_list.SetRange(indexValue, range.List);
}
[SqlMethod(IsMutator = true)]
public void SetRepeat(SqlInt32 index, SqlGradAngle value, SqlInt32 count)
{
int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value;
int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value;
_list.SetRepeat(indexValue, value.IsNull ? default(GradAngle?) : value.Value, countValue);
}
[SqlMethod(IsMutator = true)]
public void RemoveRange(SqlInt32 index, SqlInt32 count)
{
int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value;
int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value;
_list.RemoveRange(indexValue, countValue);
}
[SqlMethod]
public SqlGradAngle GetItem(SqlInt32 index)
{
return !index.IsNull && _list[index.Value].HasValue ? _list[index.Value].Value : SqlGradAngle.Null;
}
[SqlMethod]
public SqlGradAngleCollection GetRange(SqlInt32 index, SqlInt32 count)
{
int indexValue = !index.IsNull ? index.Value : count.IsNull ? 0 : _list.Count - count.Value;
int countValue = !count.IsNull ? count.Value : index.IsNull ? 0 : _list.Count - index.Value;
return new SqlGradAngleCollection(_list.GetRange(indexValue, countValue));
}
[SqlMethod]
public SqlGradAngleArray ToArray()
{
return new SqlGradAngleArray(_list);
}
#endregion
#region Operators
public static implicit operator byte[] (SqlGradAngleCollection coll)
{
using (var ms = new MemoryStream())
using (new NulInt32StreamedCollection(ms, SizeEncoding.B4, true, coll._list.Select(t => t.HasValue ? t.Value.Units : default(Int32?)).Counted(coll._list.Count), true, false))
return ms.ToArray();
}
public static explicit operator SqlGradAngleCollection(byte[] buffer)
{
using (var ms = new MemoryStream(buffer))
using (var sa = new NulInt32StreamedArray(ms, true, false))
return new SqlGradAngleCollection(sa.Select(t => t.HasValue ? new GradAngle(t.Value) : default(GradAngle?)).ToList());
}
#endregion
#region IBinarySerialize implementation
public void Read(BinaryReader rd)
{
using (var sa = new NulInt32StreamedArray(rd.BaseStream, true, false))
_list = sa.Select(t => !t.HasValue ? default(GradAngle?) : new GradAngle(t.Value)).ToList();
}
public void Write(BinaryWriter wr)
{
using (var ms = new MemoryStream())
using (var sa = new NulInt32StreamedArray(ms, SizeEncoding.B4, true, _list.Select(t => t.HasValue ? t.Value.Units : default(Int32?)).Counted(_list.Count), true, false))
wr.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ProjectData;
using Tools;
using ProjectBLL;
using System.Data;
using Approve.RuleCenter;
using System.Text;
using System.Collections;
using Approve.RuleApp;
public partial class JSDW_DesignDoc_Report : Page
{
ProjectDB db = new ProjectDB();
RCenter rc = new RCenter();
protected void Page_Load(object sender, EventArgs e)
{
pageTool tool = new pageTool(this.Page);
tool.ExecuteScript("tab();");
if (Session["FIsApprove"] != null && Session["FIsApprove"].ToString() == "1")
{
this.RegisterStartupScript(Guid.NewGuid().ToString(), "<script>FIsApprove();</script>");
}
if (!IsPostBack)
{
btnSave.Attributes["onclick"] = "return checkInfo();";
BindControl();
showInfo();
}
}
//绑定
private void BindControl()
{
//备案部门
string deptId = ComFunction.GetDefaultDept();
StringBuilder sb = new StringBuilder();
sb.Append("select case FLevel when 1 then FFullName when 2 then FName when 3 then FName end FName,");
sb.Append("FNumber from cf_Sys_ManageDept ");
sb.Append("where fnumber like '" + deptId + "%' ");
sb.Append("and fname<>'市辖区' ");
sb.Append("order by left(FNumber,4),flevel");
DataTable dt = rc.GetTable(sb.ToString());
p_FManageDeptId.DataSource = dt;
p_FManageDeptId.DataSource = dt;
p_FManageDeptId.DataTextField = "FName";
p_FManageDeptId.DataValueField = "FNumber";
p_FManageDeptId.DataBind();
}
//显示
private void showInfo()
{
string FAppId = EConvert.ToString(Session["FAppId"]);
var app = (from t in db.CF_App_List
where t.FId == FAppId
select new
{
t.FName,
t.FYear,
t.FLinkId,
t.FBaseName,
t.FPrjId,
t.FState,
}).FirstOrDefault();
pageTool tool = new pageTool(this.Page, "p_");
if (app != null)
{
t_FName.Text = app.FName;
//已提交不能修改
if (app.FState == 1 || app.FState == 6)
{
tool.ExecuteScript("btnEnable();");
}
//显示工程信息
CF_Prj_BaseInfo prj = db.CF_Prj_BaseInfo.Where(t => t.FId == app.FPrjId).FirstOrDefault();
if (prj != null)
{
tool.fillPageControl(prj);
}
}
}
/// <summary>
/// 验证附件是否上传
/// </summary>
/// <returns></returns>
bool IsUploadFile(int? FMTypeId, string FAppId)
{
CF_Prj_BaseInfo prj = (from p in db.CF_Prj_BaseInfo
join a in db.CF_App_List on p.FId equals a.FPrjId
where a.FId == FAppId
select p).FirstOrDefault();
var v =false ;
if (prj != null)
{
v = db.CF_Sys_PrjList.Count(t => t.FIsMust == 1
&& t.FManageType == FMTypeId && t.FIsPrjType.Contains(prj.FType.ToString())
&& db.CF_AppPrj_FileOther.Count(o => o.FPrjFileId == t.FId
&& o.FAppId == FAppId) < 1) > 0;
}
return v;
}
public void Report()
{
RCenter rc = new RCenter();
pageTool tool = new pageTool(this.Page);
string fDeptNumber = ComFunction.GetDefaultDept();
if (fDeptNumber == null || fDeptNumber == "")
{
tool.showMessage("系统出错,请配置默认管理部门");
return;
}
string FAppId = EConvert.ToString(Session["FAppId"]);
var app = (from t in db.CF_App_List
where t.FId == FAppId
select t).FirstOrDefault();
SortedList[] sl = new SortedList[1];
if (app != null)
{
//验证必需的附件是否上传
if (IsUploadFile(app.FManageTypeId, FAppId))
{
tool.showMessage("“上传行政批文、上传设计文件”菜单中存在未上传的附件(必需上传的),请先上传!");
return;
}
CF_Prj_BaseInfo prj = db.CF_Prj_BaseInfo.Where(t => t.FId == app.FPrjId).FirstOrDefault();
if (prj != null)
{
sl[0] = new SortedList();
sl[0].Add("FID", app.FId);
sl[0].Add("FAppId", app.FId);
sl[0].Add("FBaseInfoId", app.FBaseinfoId);
sl[0].Add("FManageTypeId", app.FManageTypeId);
sl[0].Add("FListId", "19301");
sl[0].Add("FTypeId", "1930100");
sl[0].Add("FLevelId", "1930100");
sl[0].Add("FIsPrime", 0);
//sl.Add("FAppDeptId", row["FAppDeptId"].ToString());
//sl.Add("FAppDeptName", row["FAppDeptName"].ToString());
sl[0].Add("FAppTime", DateTime.Now);
sl[0].Add("FIsNew", 0);
sl[0].Add("FIsBase", 0);
sl[0].Add("FIsTemp", 0);
sl[0].Add("FUpDept", p_FManageDeptId.SelectedValue);
sl[0].Add("FEmpId", prj.FId);
sl[0].Add("FEmpName", prj.FPrjName);
//存设计单位
var s = (from t in db.CF_Prj_Ent
join a in db.CF_App_List on t.FAppId equals a.FId
where a.FPrjId == app.FPrjId && a.FManageTypeId == 291 && t.FEntType == 155 && a.FState == 6
select new
{
t.FId,
t.FBaseInfoId,
t.FName,
t.FLevelName,
t.FCertiNo,
t.FMoney,
t.FPlanDate,
t.FAppId
}).FirstOrDefault();
if (s != null)
{
sl[0].Add("FLeadId", s.FBaseInfoId);
sl[0].Add("FLeadName", s.FName);
}
StringBuilder sb = new StringBuilder();
sb.Append("update CF_App_List set FUpDeptId=" + p_FManageDeptId.SelectedValue + ",");
sb.Append("ftime=getdate() where fid = '" + FAppId + "'");
rc.PExcute(sb.ToString());
string fsystemid = CurrentEntUser.SystemId;
RApp ra = new RApp();
if (ra.EntStartProcessKCSJ(app.FBaseinfoId, FAppId, app.FYear.ToString(), DateTime.Now.Month.ToString(), fsystemid, fDeptNumber, p_FManageDeptId.SelectedValue, sl))
{
sb.Remove(0, sb.Length);
this.Session["FIsApprove"] = 1;
tool.showMessageAndRunFunction("上报成功!", "location.href=location.href");
}
}
}
}
//保存按钮
protected void btnSave_Click(object sender, EventArgs e)
{
Report();
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.EnumsShouldHaveZeroValueAnalyzer,
Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpEnumsShouldHaveZeroValueFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.EnumsShouldHaveZeroValueAnalyzer,
Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicEnumsShouldHaveZeroValueFixer>;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class EnumsShouldHaveZeroValueFixerTests
{
[Fact]
public async Task CSharp_EnumsShouldZeroValueFlagsRenameAsync()
{
var code = @"
public class Outer
{
[System.Flags]
public enum E
{
A = 0,
B = 3
}
}
[System.Flags]
public enum E2
{
A2 = 0,
B2 = 1
}
[System.Flags]
public enum E3
{
A3 = (ushort)0,
B3 = (ushort)1
}
[System.Flags]
public enum E4
{
A4 = 0,
B4 = (int)2 // Sample comment
}
[System.Flags]
public enum NoZeroValuedField
{
A5 = 1,
B5 = 2
}";
var expectedFixedCode = @"
public class Outer
{
[System.Flags]
public enum E
{
None = 0,
B = 3
}
}
[System.Flags]
public enum E2
{
None = 0,
B2 = 1
}
[System.Flags]
public enum E3
{
None = (ushort)0,
B3 = (ushort)1
}
[System.Flags]
public enum E4
{
None = 0,
B4 = (int)2 // Sample comment
}
[System.Flags]
public enum NoZeroValuedField
{
A5 = 1,
B5 = 2
}";
await VerifyCS.VerifyCodeFixAsync(
code,
new[]
{
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(7, 9, 7, 10).WithArguments("E", "A"),
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(15, 5, 15, 7).WithArguments("E2", "A2"),
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(22, 5, 22, 7).WithArguments("E3", "A3"),
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(29, 5, 29, 7).WithArguments("E4", "A4"),
},
expectedFixedCode);
}
[Fact]
public async Task CSharp_EnumsShouldZeroValueFlagsMultipleZeroAsync()
{
var code = @"// Some comment
public class Outer
{
[System.Flags]
public enum E
{
None = 0,
A = 0
}
}
// Some comment
[System.Flags]
public enum E2
{
None = 0,
A = None
}";
var expectedFixedCode = @"// Some comment
public class Outer
{
[System.Flags]
public enum E
{
None = 0
}
}
// Some comment
[System.Flags]
public enum E2
{
None = 0
}";
await VerifyCS.VerifyCodeFixAsync(
code,
new[]
{
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(5, 17, 5, 18).WithArguments("E"),
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(13, 13, 13, 15).WithArguments("E2"),
},
expectedFixedCode);
}
[Fact]
public async Task CSharp_EnumsShouldZeroValueNotFlagsNoZeroValueAsync()
{
var code = @"
public class Outer
{
public enum E
{
A = 1
}
public enum E2
{
None = 1,
A = 2
}
}
public enum E3
{
None = 0,
A = 1
}
public enum E4
{
None = 0,
A = 0
}
";
var expectedFixedCode = @"
public class Outer
{
public enum E
{
None,
A = 1
}
public enum E2
{
None,
A = 2
}
}
public enum E3
{
None = 0,
A = 1
}
public enum E4
{
None = 0,
A = 0
}
";
await VerifyCS.VerifyCodeFixAsync(
code,
new[]
{
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleNoZero).WithSpan(4, 17, 4, 18).WithArguments("E"),
VerifyCS.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleNoZero).WithSpan(9, 17, 9, 19).WithArguments("E2"),
},
expectedFixedCode);
}
[Fact]
public async Task VisualBasic_EnumsShouldZeroValueFlagsRenameAsync()
{
var code = @"
Public Class Outer
<System.Flags>
Public Enum E
A = 0
B = 1
End Enum
End Class
<System.Flags>
Public Enum E2
A2 = 0
B2 = 1
End Enum
<System.Flags>
Public Enum E3
A3 = CUShort(0)
B3 = CUShort(1)
End Enum
<System.Flags>
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
var expectedFixedCode = @"
Public Class Outer
<System.Flags>
Public Enum E
None = 0
B = 1
End Enum
End Class
<System.Flags>
Public Enum E2
None = 0
B2 = 1
End Enum
<System.Flags>
Public Enum E3
None = CUShort(0)
B3 = CUShort(1)
End Enum
<System.Flags>
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
await VerifyVB.VerifyCodeFixAsync(
code,
new[]
{
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(5, 9, 5, 10).WithArguments("E", "A"),
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(12, 5, 12, 7).WithArguments("E2", "A2"),
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(18, 5, 18, 7).WithArguments("E3", "A3"),
},
expectedFixedCode);
}
[WorkItem(836193, "DevDiv")]
[Fact]
public async Task VisualBasic_EnumsShouldZeroValueFlagsRename_AttributeListHasTriviaAsync()
{
var code = @"
Public Class Outer
<System.Flags> _
Public Enum E
A = 0
B = 1
End Enum
End Class
<System.Flags> _
Public Enum E2
A2 = 0
B2 = 1
End Enum
<System.Flags> _
Public Enum E3
A3 = CUShort(0)
B3 = CUShort(1)
End Enum
<System.Flags> _
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
var expectedFixedCode = @"
Public Class Outer
<System.Flags> _
Public Enum E
None = 0
B = 1
End Enum
End Class
<System.Flags> _
Public Enum E2
None = 0
B2 = 1
End Enum
<System.Flags> _
Public Enum E3
None = CUShort(0)
B3 = CUShort(1)
End Enum
<System.Flags> _
Public Enum NoZeroValuedField
A5 = 1
B5 = 2
End Enum
";
await VerifyVB.VerifyCodeFixAsync(
code,
new[]
{
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(5, 9, 5, 10).WithArguments("E", "A"),
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(12, 5, 12, 7).WithArguments("E2", "A2"),
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleRename).WithSpan(18, 5, 18, 7).WithArguments("E3", "A3"),
},
expectedFixedCode);
}
[Fact]
public async Task VisualBasic_EnumsShouldZeroValueFlagsMultipleZeroAsync()
{
var code = @"
Public Class Outer
<System.Flags>
Public Enum E
None = 0
A = 0
End Enum
End Class
<System.Flags>
Public Enum E2
None = 0
A = None
End Enum
<System.Flags>
Public Enum E3
A3 = 0
B3 = CUInt(0) ' Not a constant
End Enum";
var expectedFixedCode = @"
Public Class Outer
<System.Flags>
Public Enum E
None = 0
End Enum
End Class
<System.Flags>
Public Enum E2
None = 0
End Enum
<System.Flags>
Public Enum E3
None
End Enum";
await VerifyVB.VerifyCodeFixAsync(
code,
new[]
{
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(4, 17, 4, 18).WithArguments("E"),
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(11, 13, 11, 15).WithArguments("E2"),
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleMultipleZero).WithSpan(17, 13, 17, 15).WithArguments("E3"),
},
expectedFixedCode);
}
[Fact]
public async Task VisualBasic_EnumsShouldZeroValueNotFlagsNoZeroValueAsync()
{
var code = @"
Public Class C
Public Enum E
A = 1
End Enum
Public Enum E2
None = 1
A = 2
End Enum
End Class
Public Enum E3
None = 0
A = 1
End Enum
Public Enum E4
None = 0
A = 0
End Enum
";
var expectedFixedCode = @"
Public Class C
Public Enum E
None
A = 1
End Enum
Public Enum E2
None
A = 2
End Enum
End Class
Public Enum E3
None = 0
A = 1
End Enum
Public Enum E4
None = 0
A = 0
End Enum
";
await VerifyVB.VerifyCodeFixAsync(
code,
new[]
{
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleNoZero).WithSpan(3, 17, 3, 18).WithArguments("E"),
VerifyVB.Diagnostic(EnumsShouldHaveZeroValueAnalyzer.RuleNoZero).WithSpan(7, 17, 7, 19).WithArguments("E2"),
},
expectedFixedCode);
}
}
}
|
using System;
using Windows.Devices.Enumeration;
using Windows.Devices.Spi;
using Windows.Foundation.Metadata;
namespace ABElectronics_Win10IOT_Libraries
{
/// <summary>
/// Class for accessing the ADCDAC Pi from AB Electronics UK.
/// </summary>
public class ADCDACPi : IDisposable
{
private const string SPI_CONTROLLER_NAME = "SPI0";
private const Int32 ADC_CHIP_SELECT_LINE = 0; // ADC on SPI channel select CE0
private const Int32 DAC_CHIP_SELECT_LINE = 1; // ADC on SPI channel select CE1
private SpiDevice adc;
private double ADCReferenceVoltage = 3.3;
private SpiDevice dac;
/// <summary>
/// Event triggers when a connection is established.
/// </summary>
public bool IsConnected { get; private set; }
// Flag: Has Dispose already been called?
bool disposed = false;
// Instantiate a SafeHandle instance.
System.Runtime.InteropServices.SafeHandle handle = new Microsoft.Win32.SafeHandles.SafeFileHandle(IntPtr.Zero, true);
/// <summary>
/// Open a connection to the ADCDAC Pi.
/// </summary>
public async void Connect()
{
if (IsConnected)
{
return; // Already connected
}
if(!ApiInformation.IsTypePresent("Windows.Devices.Spi.SpiDevice"))
{
return; // This system does not support this feature: can't connect
}
try
{
// Create SPI initialization settings for the ADC
var adcsettings =
new SpiConnectionSettings(ADC_CHIP_SELECT_LINE)
{
ClockFrequency = 10000000, // SPI clock frequency of 10MHz
Mode = SpiMode.Mode0
};
var spiAqs = SpiDevice.GetDeviceSelector(SPI_CONTROLLER_NAME); // Find the selector string for the SPI bus controller
var devicesInfo = await DeviceInformation.FindAllAsync(spiAqs); // Find the SPI bus controller device with our selector string
if (devicesInfo.Count == 0)
{
return; // Controller not found
}
adc = await SpiDevice.FromIdAsync(devicesInfo[0].Id, adcsettings); // Create an ADC connection with our bus controller and SPI settings
// Create SPI initialization settings for the DAC
var dacSettings =
new SpiConnectionSettings(DAC_CHIP_SELECT_LINE)
{
ClockFrequency = 2000000, // SPI clock frequency of 20MHz
Mode = SpiMode.Mode0
};
dac = await SpiDevice.FromIdAsync(devicesInfo[0].Id, dacSettings); // Create a DAC connection with our bus controller and SPI settings
IsConnected = true; // connection established, set IsConnected to true.
// Fire the Connected event handler
Connected?.Invoke(this, EventArgs.Empty);
}
/* If initialization fails, display the exception and stop running */
catch (Exception ex)
{
IsConnected = false;
throw new Exception("SPI Initialization Failed", ex);
}
}
/// <summary>
/// Event occurs when connection is made.
/// </summary>
public event EventHandler Connected;
/// <summary>
/// Read the voltage from the selected <paramref name="channel" /> on the ADC.
/// </summary>
/// <param name="channel">1 or 2</param>
/// <returns>voltage</returns>
public double ReadADCVoltage(byte channel)
{
if (channel < 1 || channel > 2)
{
throw new ArgumentOutOfRangeException(nameof(channel));
}
var raw = ReadADCRaw(channel);
var voltage = ADCReferenceVoltage / 4096 * raw; // convert the raw value into a voltage based on the reference voltage.
return voltage;
}
/// <summary>
/// Read the raw value from the selected <paramref name="channel" /> on the ADC.
/// </summary>
/// <param name="channel">1 or 2</param>
/// <returns>Integer</returns>
public int ReadADCRaw(byte channel)
{
if (channel < 1 || channel > 2)
{
throw new ArgumentOutOfRangeException(nameof(channel));
}
CheckConnected();
var writeArray = new byte[] { 0x01, (byte) ((1 + channel) << 6), 0x00}; // create the write bytes based on the input channel
var readBuffer = new byte[3]; // this holds the output data
adc.TransferFullDuplex(writeArray, readBuffer); // transfer the adc data
var ret = (short) (((readBuffer[1] & 0x0F) << 8) + readBuffer[2]); // combine the two bytes into a single 16bit integer
return ret;
}
/// <summary>
/// Set the reference <paramref name="voltage" /> for the analogue to digital converter.
/// The ADC uses the raspberry pi 3.3V power as a <paramref name="voltage" /> reference
/// so using this method to set the reference to match the exact output
/// <paramref name="voltage" /> from the 3.3V regulator will increase the accuracy of
/// the ADC readings.
/// </summary>
/// <param name="voltage">double</param>
public void SetADCrefVoltage(double voltage)
{
CheckConnected();
if (voltage < 0.0 || voltage > 7.0)
{
throw new ArgumentOutOfRangeException(nameof(voltage), "Reference voltage must be between 0.0V and 7.0V.");
}
ADCReferenceVoltage = voltage;
}
/// <summary>
/// Set the <paramref name="voltage" /> for the selected channel on the DAC.
/// </summary>
/// <param name="channel">1 or 2</param>
/// <param name="voltage">Voltage can be between 0 and 2.047 volts</param>
public void SetDACVoltage(byte channel, double voltage)
{
// Check for valid channel and voltage variables
if (channel < 1 || channel > 2)
{
throw new ArgumentOutOfRangeException();
}
if (voltage >= 0.0 && voltage < 2.048)
{
var rawval = Convert.ToInt16(voltage / 2.048 * 4096); // convert the voltage into a raw value
SetDACRaw(channel, rawval);
}
else
{
throw new ArgumentOutOfRangeException();
}
}
/// <summary>
/// Set the raw <paramref name="value" /> from the selected <paramref name="channel" /> on the DAC.
/// </summary>
/// <param name="channel">1 or 2</param>
/// <param name="value">Value between 0 and 4095</param>
public void SetDACRaw(byte channel, short value)
{
CheckConnected();
if (channel < 1 || channel > 2)
{
throw new ArgumentOutOfRangeException();
}
// split the raw value into two bytes and send it to the DAC.
var lowByte = (byte) (value & 0xff);
var highByte = (byte) (((value >> 8) & 0xff) | ((channel - 1) << 7) | (0x1 << 5) | (1 << 4));
var writeBuffer = new [] { highByte, lowByte};
dac.Write(writeBuffer);
}
private void CheckConnected()
{
if (!IsConnected)
{
throw new InvalidOperationException("Not connected. You must call .Connect() first.");
}
}
/// <summary>
/// Dispose of the resources
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Protected implementation of Dispose pattern
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
handle.Dispose();
// Free any other managed objects here.
adc?.Dispose();
adc = null;
dac?.Dispose();
dac = null;
IsConnected = false;
}
// Free any unmanaged objects here.
//
disposed = true;
}
}
} |
//
// PgpMimeTests.cs
//
// Author: Jeffrey Stedfast <jestedfa@microsoft.com>
//
// Copyright (c) 2013-2022 .NET Foundation and Contributors
//
// 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.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using NUnit.Framework;
using Org.BouncyCastle.Bcpg;
using Org.BouncyCastle.Bcpg.OpenPgp;
using MimeKit;
using MimeKit.IO;
using MimeKit.IO.Filters;
using MimeKit.Cryptography;
namespace UnitTests.Cryptography {
[TestFixture]
public class PgpMimeTests
{
static PgpMimeTests ()
{
Environment.SetEnvironmentVariable ("GNUPGHOME", Path.GetFullPath ("."));
var dataDir = Path.Combine (TestHelper.ProjectDir, "TestData", "openpgp");
CryptographyContext.Register (typeof (DummyOpenPgpContext));
foreach (var name in new [] { "pubring.gpg", "pubring.gpg~", "secring.gpg", "secring.gpg~", "gpg.conf" }) {
if (File.Exists (name))
File.Delete (name);
}
using (var ctx = new DummyOpenPgpContext ()) {
using (var seckeys = File.OpenRead (Path.Combine (dataDir, "mimekit.gpg.sec"))) {
using (var armored = new ArmoredInputStream (seckeys))
ctx.Import (new PgpSecretKeyRingBundle (armored));
}
using (var pubkeys = File.OpenRead (Path.Combine (dataDir, "mimekit.gpg.pub")))
ctx.Import (pubkeys);
}
File.Copy (Path.Combine (dataDir, "gpg.conf"), "gpg.conf", true);
}
static bool IsSupported (EncryptionAlgorithm algorithm)
{
switch (algorithm) {
case EncryptionAlgorithm.RC2128:
case EncryptionAlgorithm.RC264:
case EncryptionAlgorithm.RC240:
case EncryptionAlgorithm.Seed:
return false;
default:
return true;
}
}
[Test]
public void TestPreferredAlgorithms ()
{
using (var ctx = new DummyOpenPgpContext ()) {
var encryptionAlgorithms = ctx.EnabledEncryptionAlgorithms;
Assert.AreEqual (4, encryptionAlgorithms.Length);
Assert.AreEqual (EncryptionAlgorithm.Aes256, encryptionAlgorithms[0]);
Assert.AreEqual (EncryptionAlgorithm.Aes192, encryptionAlgorithms[1]);
Assert.AreEqual (EncryptionAlgorithm.Aes128, encryptionAlgorithms[2]);
Assert.AreEqual (EncryptionAlgorithm.TripleDes, encryptionAlgorithms[3]);
var digestAlgorithms = ctx.EnabledDigestAlgorithms;
Assert.AreEqual (3, digestAlgorithms.Length);
Assert.AreEqual (DigestAlgorithm.Sha256, digestAlgorithms[0]);
Assert.AreEqual (DigestAlgorithm.Sha512, digestAlgorithms[1]);
Assert.AreEqual (DigestAlgorithm.Sha1, digestAlgorithms[2]);
}
}
[Test]
public void TestKeyEnumeration ()
{
using (var ctx = new DummyOpenPgpContext ()) {
var unknownMailbox = new MailboxAddress ("Snarky McSnarkypants", "snarky@snarkypants.net");
var knownMailbox = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
int count = ctx.EnumeratePublicKeys ().Count ();
// Note: the count will be 8 if run as a complete unit test or 2 if run individually
Assert.IsTrue (count == 8 || count == 2, "Unexpected number of public keys");
Assert.AreEqual (0, ctx.EnumeratePublicKeys (unknownMailbox).Count (), "Unexpected number of public keys for an unknown mailbox");
Assert.AreEqual (2, ctx.EnumeratePublicKeys (knownMailbox).Count (), "Unexpected number of public keys for a known mailbox");
Assert.AreEqual (2, ctx.EnumerateSecretKeys ().Count (), "Unexpected number of secret keys");
Assert.AreEqual (0, ctx.EnumerateSecretKeys (unknownMailbox).Count (), "Unexpected number of secret keys for an unknown mailbox");
Assert.AreEqual (2, ctx.EnumerateSecretKeys (knownMailbox).Count (), "Unexpected number of secret keys for a known mailbox");
Assert.IsTrue (ctx.CanSign (knownMailbox));
Assert.IsFalse (ctx.CanSign (unknownMailbox));
Assert.IsTrue (ctx.CanEncrypt (knownMailbox));
Assert.IsFalse (ctx.CanEncrypt (unknownMailbox));
}
}
[Test]
public void TestKeyGeneration ()
{
using (var ctx = new DummyOpenPgpContext ()) {
var mailbox = new MailboxAddress ("Snarky McSnarkypants", "snarky@snarkypants.net");
int publicKeyRings = ctx.EnumeratePublicKeyRings ().Count ();
int secretKeyRings = ctx.EnumerateSecretKeyRings ().Count ();
ctx.GenerateKeyPair (mailbox, "password", DateTime.Now.AddYears (1), EncryptionAlgorithm.Cast5);
var pubring = ctx.EnumeratePublicKeyRings (mailbox).FirstOrDefault ();
Assert.IsNotNull (pubring, "Expected to find the generated public keyring");
ctx.Delete (pubring);
Assert.AreEqual (publicKeyRings, ctx.EnumeratePublicKeyRings ().Count (), "Unexpected number of public keyrings");
var secring = ctx.EnumerateSecretKeyRings (mailbox).FirstOrDefault ();
Assert.IsNotNull (secring, "Expected to find the generated secret keyring");
ctx.Delete (secring);
Assert.AreEqual (secretKeyRings, ctx.EnumerateSecretKeyRings ().Count (), "Unexpected number of secret keyrings");
}
}
[Test]
public void TestKeySigning ()
{
using (var ctx = new DummyOpenPgpContext ()) {
var seckey = ctx.EnumerateSecretKeys (new MailboxAddress ("", "mimekit@example.com")).FirstOrDefault ();
var mailbox = new MailboxAddress ("Snarky McSnarkypants", "snarky@snarkypants.net");
ctx.GenerateKeyPair (mailbox, "password", DateTime.Now.AddYears (1), EncryptionAlgorithm.Cast5);
// delete the secret keyring, we don't need it
var secring = ctx.EnumerateSecretKeyRings (mailbox).FirstOrDefault ();
ctx.Delete (secring);
var pubring = ctx.EnumeratePublicKeyRings (mailbox).FirstOrDefault ();
var pubkey = pubring.GetPublicKey ();
int sigCount = 0;
foreach (PgpSignature sig in pubkey.GetKeySignatures ())
sigCount++;
Assert.AreEqual (0, sigCount);
ctx.SignKey (seckey, pubkey, DigestAlgorithm.Sha256, OpenPgpKeyCertification.CasualCertification);
pubring = ctx.EnumeratePublicKeyRings (mailbox).FirstOrDefault ();
pubkey = pubring.GetPublicKey ();
sigCount = 0;
foreach (PgpSignature sig in pubkey.GetKeySignatures ()) {
Assert.AreEqual (seckey.KeyId, sig.KeyId);
Assert.AreEqual (HashAlgorithmTag.Sha256, sig.HashAlgorithm);
Assert.AreEqual ((int) OpenPgpKeyCertification.CasualCertification, sig.SignatureType);
sigCount++;
}
Assert.AreEqual (1, sigCount);
ctx.Delete (pubring);
}
}
[Test]
public void TestMimeMessageSign ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
var message = new MimeMessage { Subject = "Test of signing with OpenPGP" };
using (var ctx = new DummyOpenPgpContext ()) {
// throws because no Body is set
Assert.Throws<InvalidOperationException> (() => message.Sign (ctx));
message.Body = body;
// throws because no sender is set
Assert.Throws<InvalidOperationException> (() => message.Sign (ctx));
message.From.Add (self);
// ok, now we can sign
message.Sign (ctx);
Assert.IsInstanceOf<MultipartSigned> (message.Body);
var multipart = (MultipartSigned) message.Body;
Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children.");
var protocol = multipart.ContentType.Parameters["protocol"];
Assert.AreEqual (ctx.SignatureProtocol, protocol, "The multipart/signed protocol does not match.");
Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part.");
Assert.IsInstanceOf<ApplicationPgpSignature> (multipart[1], "The second child is not a detached signature.");
var signatures = multipart.Verify (ctx);
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
var signature = signatures[0];
Assert.AreEqual ("MimeKit UnitTests", signature.SignerCertificate.Name);
Assert.AreEqual ("mimekit@example.com", signature.SignerCertificate.Email);
Assert.AreEqual ("44CD48EEC90D8849961F36BA50DCD107AB0821A2", signature.SignerCertificate.Fingerprint);
Assert.AreEqual (new DateTime (2013, 11, 3, 18, 32, 27), signature.SignerCertificate.CreationDate, "CreationDate");
Assert.AreEqual (DateTime.MaxValue, signature.SignerCertificate.ExpirationDate, "ExpirationDate");
Assert.AreEqual (PublicKeyAlgorithm.RsaGeneral, signature.SignerCertificate.PublicKeyAlgorithm);
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public async Task TestMimeMessageSignAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
var message = new MimeMessage { Subject = "Test of signing with OpenPGP" };
using (var ctx = new DummyOpenPgpContext ()) {
// throws because no Body is set
Assert.Throws<InvalidOperationException> (() => message.Sign (ctx));
message.Body = body;
// throws because no sender is set
Assert.Throws<InvalidOperationException> (() => message.Sign (ctx));
message.From.Add (self);
// ok, now we can sign
message.Sign (ctx);
Assert.IsInstanceOf<MultipartSigned> (message.Body);
var multipart = (MultipartSigned) message.Body;
Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children.");
var protocol = multipart.ContentType.Parameters["protocol"];
Assert.AreEqual (ctx.SignatureProtocol, protocol, "The multipart/signed protocol does not match.");
Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part.");
Assert.IsInstanceOf<ApplicationPgpSignature> (multipart[1], "The second child is not a detached signature.");
var signatures = await multipart.VerifyAsync (ctx);
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
var signature = signatures[0];
Assert.AreEqual ("MimeKit UnitTests", signature.SignerCertificate.Name);
Assert.AreEqual ("mimekit@example.com", signature.SignerCertificate.Email);
Assert.AreEqual ("44CD48EEC90D8849961F36BA50DCD107AB0821A2", signature.SignerCertificate.Fingerprint);
Assert.AreEqual (new DateTime (2013, 11, 3, 18, 32, 27), signature.SignerCertificate.CreationDate, "CreationDate");
Assert.AreEqual (DateTime.MaxValue, signature.SignerCertificate.ExpirationDate, "ExpirationDate");
Assert.AreEqual (PublicKeyAlgorithm.RsaGeneral, signature.SignerCertificate.PublicKeyAlgorithm);
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public void TestMultipartSignedVerifyExceptions ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
using (var ctx = new DummyOpenPgpContext ()) {
var signed = MultipartSigned.Create (ctx, self, DigestAlgorithm.Sha256, body);
var protocol = signed.ContentType.Parameters["protocol"];
signed.ContentType.Parameters.Remove ("protocol");
Assert.Throws<FormatException> (() => signed.Verify (), "Verify() w/o protocol parameter");
Assert.Throws<FormatException> (() => signed.Verify (ctx), "Verify(ctx) w/o protocol parameter");
Assert.ThrowsAsync<FormatException> (() => signed.VerifyAsync (), "VerifyAsync() w/o protocol parameter");
Assert.ThrowsAsync<FormatException> (() => signed.VerifyAsync (ctx), "VerifyAsync(ctx) w/o protocol parameter");
signed.ContentType.Parameters.Add ("protocol", "invalid-protocol");
Assert.Throws<NotSupportedException> (() => signed.Verify (), "Verify() w/ invalid protocol parameter");
Assert.Throws<NotSupportedException> (() => signed.Verify (ctx), "Verify(ctx) w/ invalid protocol parameter");
Assert.ThrowsAsync<NotSupportedException> (() => signed.VerifyAsync (), "VerifyAsync() w/ invalid protocol parameter");
Assert.ThrowsAsync<NotSupportedException> (() => signed.VerifyAsync (ctx), "VerifyAsync(ctx) w/ invalid protocol parameter");
signed.ContentType.Parameters["protocol"] = protocol;
var signature = signed[1];
signed.RemoveAt (1);
Assert.Throws<FormatException> (() => signed.Verify (), "Verify() w/ < 2 parts");
Assert.Throws<FormatException> (() => signed.Verify (ctx), "Verify(ctx) w/ < 2 parts");
Assert.ThrowsAsync<FormatException> (() => signed.VerifyAsync (), "VerifyAsync() w/ < 2 parts");
Assert.ThrowsAsync<FormatException> (() => signed.VerifyAsync (ctx), "VerifyAsync(ctx) w/ < 2 parts");
var emptySignature = new MimePart ("application", "octet-stream");
signed.Add (emptySignature);
Assert.Throws<FormatException> (() => signed.Verify (), "Verify() w/ invalid signature part");
Assert.Throws<FormatException> (() => signed.Verify (ctx), "Verify(ctx) w/ invalid signature part");
Assert.ThrowsAsync<FormatException> (() => signed.VerifyAsync (), "VerifyAsync() w/ invalid signature part");
Assert.ThrowsAsync<FormatException> (() => signed.VerifyAsync (ctx), "VerifyAsync(ctx) w/ invalid signature part");
var invalidContent = new MimePart ("image", "jpeg") {
Content = new MimeContent (new MemoryStream (Array.Empty<byte> (), false))
};
signed[1] = invalidContent;
Assert.Throws<NotSupportedException> (() => signed.Verify (), "Verify() w/ invalid content part");
Assert.Throws<NotSupportedException> (() => signed.Verify (ctx), "Verify(ctx) w/ invalid content part");
Assert.ThrowsAsync<NotSupportedException> (() => signed.VerifyAsync (), "VerifyAsync() w/ invalid content part");
Assert.ThrowsAsync<NotSupportedException> (() => signed.VerifyAsync (ctx), "VerifyAsync(ctx) w/ invalid content part");
}
}
[Test]
public void TestMultipartSignedSignUsingKeys ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "44CD48EEC90D8849961F36BA50DCD107AB0821A2");
PgpSecretKey signer;
using (var ctx = new DummyOpenPgpContext ()) {
signer = ctx.GetSigningKey (self);
foreach (DigestAlgorithm digest in Enum.GetValues (typeof (DigestAlgorithm))) {
if (digest == DigestAlgorithm.None ||
digest == DigestAlgorithm.DoubleSha ||
digest == DigestAlgorithm.Tiger192 ||
digest == DigestAlgorithm.Haval5160 ||
digest == DigestAlgorithm.MD4)
continue;
var multipart = MultipartSigned.Create (signer, digest, body);
Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children.");
var protocol = multipart.ContentType.Parameters["protocol"];
Assert.AreEqual ("application/pgp-signature", protocol, "The multipart/signed protocol does not match.");
var micalg = multipart.ContentType.Parameters["micalg"];
var algorithm = ctx.GetDigestAlgorithm (micalg);
Assert.AreEqual (digest, algorithm, "The multipart/signed micalg does not match.");
Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part.");
Assert.IsInstanceOf<ApplicationPgpSignature> (multipart[1], "The second child is not a detached signature.");
var signatures = multipart.Verify ();
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
}
}
[Test]
public async Task TestMultipartSignedSignUsingKeysAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "44CD48EEC90D8849961F36BA50DCD107AB0821A2");
PgpSecretKey signer;
using (var ctx = new DummyOpenPgpContext ()) {
signer = ctx.GetSigningKey (self);
foreach (DigestAlgorithm digest in Enum.GetValues (typeof (DigestAlgorithm))) {
if (digest == DigestAlgorithm.None ||
digest == DigestAlgorithm.DoubleSha ||
digest == DigestAlgorithm.Tiger192 ||
digest == DigestAlgorithm.Haval5160 ||
digest == DigestAlgorithm.MD4)
continue;
var multipart = await MultipartSigned.CreateAsync (signer, digest, body);
Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children.");
var protocol = multipart.ContentType.Parameters["protocol"];
Assert.AreEqual ("application/pgp-signature", protocol, "The multipart/signed protocol does not match.");
var micalg = multipart.ContentType.Parameters["micalg"];
var algorithm = ctx.GetDigestAlgorithm (micalg);
Assert.AreEqual (digest, algorithm, "The multipart/signed micalg does not match.");
Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part.");
Assert.IsInstanceOf<ApplicationPgpSignature> (multipart[1], "The second child is not a detached signature.");
var signatures = await multipart.VerifyAsync ();
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
}
}
[Test]
public void TestMimeMessageEncrypt ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "44CD48EEC90D8849961F36BA50DCD107AB0821A2");
var message = new MimeMessage { Subject = "Test of signing with OpenPGP" };
using (var ctx = new DummyOpenPgpContext ()) {
// throws because no Body has been set
Assert.Throws<InvalidOperationException> (() => message.Encrypt (ctx));
message.Body = body;
// throws because no recipients have been set
Assert.Throws<InvalidOperationException> (() => message.Encrypt (ctx));
message.From.Add (self);
message.To.Add (self);
message.Encrypt (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
var encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt (ctx);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
// now do the same thing, but encrypt to the Resent-To headers
message.From.Clear ();
message.To.Clear ();
message.From.Add (new MailboxAddress ("Dummy Sender", "dummy@sender.com"));
message.To.Add (new MailboxAddress ("Dummy Recipient", "dummy@recipient.com"));
message.ResentFrom.Add (self);
message.ResentTo.Add (self);
message.Body = body;
message.Encrypt (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
decrypted = encrypted.Decrypt (ctx);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
}
[Test]
public async Task TestMimeMessageEncryptAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "44CD48EEC90D8849961F36BA50DCD107AB0821A2");
var message = new MimeMessage { Subject = "Test of signing with OpenPGP" };
using (var ctx = new DummyOpenPgpContext ()) {
// throws because no Body has been set
Assert.ThrowsAsync<InvalidOperationException> (() => message.EncryptAsync (ctx));
message.Body = body;
// throws because no recipients have been set
Assert.ThrowsAsync<InvalidOperationException> (() => message.EncryptAsync (ctx));
message.From.Add (self);
message.To.Add (self);
await message.EncryptAsync (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
var encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt (ctx);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
// now do the same thing, but encrypt to the Resent-To headers
message.From.Clear ();
message.To.Clear ();
message.From.Add (new MailboxAddress ("Dummy Sender", "dummy@sender.com"));
message.To.Add (new MailboxAddress ("Dummy Recipient", "dummy@recipient.com"));
message.ResentFrom.Add (self);
message.ResentTo.Add (self);
message.Body = body;
await message.EncryptAsync (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
decrypted = encrypted.Decrypt (ctx);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
}
[Test]
public void TestMultipartEncryptedDecryptExceptions ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
var encrypted = MultipartEncrypted.Encrypt (new[] { self }, body);
using (var ctx = new DummyOpenPgpContext ()) {
var protocol = encrypted.ContentType.Parameters["protocol"];
encrypted.ContentType.Parameters.Remove ("protocol");
Assert.Throws<FormatException> (() => encrypted.Decrypt (), "Decrypt() w/o protocol parameter");
Assert.Throws<FormatException> (() => encrypted.Decrypt (ctx), "Decrypt(ctx) w/o protocol parameter");
encrypted.ContentType.Parameters.Add ("protocol", "invalid-protocol");
//Assert.Throws<NotSupportedException> (() => encrypted.Decrypt (), "Decrypt() w/ invalid protocol parameter");
Assert.Throws<NotSupportedException> (() => encrypted.Decrypt (ctx), "Decrypt(ctx) w/ invalid protocol parameter");
encrypted.ContentType.Parameters["protocol"] = protocol;
var version = encrypted[0];
encrypted.RemoveAt (0);
Assert.Throws<FormatException> (() => encrypted.Decrypt (), "Decrypt() w/ < 2 parts");
Assert.Throws<FormatException> (() => encrypted.Decrypt (ctx), "Decrypt(ctx) w/ < 2 parts");
var invalidVersion = new MimePart ("application", "octet-stream") {
Content = new MimeContent (new MemoryStream (Array.Empty<byte> (), false))
};
encrypted.Insert (0, invalidVersion);
Assert.Throws<FormatException> (() => encrypted.Decrypt (), "Decrypt() w/ invalid version part");
Assert.Throws<FormatException> (() => encrypted.Decrypt (ctx), "Decrypt(ctx) w/ invalid version part");
var emptyContent = new MimePart ("application", "octet-stream");
var content = encrypted[1];
encrypted[1] = emptyContent;
encrypted[0] = version;
Assert.Throws<FormatException> (() => encrypted.Decrypt (), "Decrypt() w/ empty content part");
Assert.Throws<FormatException> (() => encrypted.Decrypt (ctx), "Decrypt(ctx) w/ empty content part");
var invalidContent = new MimePart ("image", "jpeg") {
Content = new MimeContent (new MemoryStream (Array.Empty<byte> (), false))
};
encrypted[1] = invalidContent;
Assert.Throws<FormatException> (() => encrypted.Decrypt (), "Decrypt() w/ invalid content part");
Assert.Throws<FormatException> (() => encrypted.Decrypt (ctx), "Decrypt(ctx) w/ invalid content part");
}
}
[Test]
public void TestMultipartEncryptedEncrypt ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
var encrypted = MultipartEncrypted.Encrypt (new [] { self }, body);
using (var stream = new MemoryStream ()) {
encrypted.WriteTo (stream);
stream.Position = 0;
var entity = MimeEntity.Load (stream);
Assert.IsInstanceOf<MultipartEncrypted> (entity, "Encrypted part is not the expected type");
encrypted = (MultipartEncrypted) entity;
Assert.IsInstanceOf<ApplicationPgpEncrypted> (encrypted[0], "First child of multipart/encrypted is not the expected type");
Assert.IsInstanceOf<MimePart> (encrypted[1], "Second child of multipart/encrypted is not the expected type");
Assert.AreEqual ("application/octet-stream", encrypted[1].ContentType.MimeType, "Second child of multipart/encrypted is not the expected mime-type");
}
var decrypted = encrypted.Decrypt ();
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
[Test]
public async Task TestMultipartEncryptedEncryptAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
var encrypted = await MultipartEncrypted.EncryptAsync (new[] { self }, body);
using (var stream = new MemoryStream ()) {
await encrypted.WriteToAsync (stream);
stream.Position = 0;
var entity = await MimeEntity.LoadAsync (stream);
Assert.IsInstanceOf<MultipartEncrypted> (entity, "Encrypted part is not the expected type");
encrypted = (MultipartEncrypted) entity;
Assert.IsInstanceOf<ApplicationPgpEncrypted> (encrypted[0], "First child of multipart/encrypted is not the expected type");
Assert.IsInstanceOf<MimePart> (encrypted[1], "Second child of multipart/encrypted is not the expected type");
Assert.AreEqual ("application/octet-stream", encrypted[1].ContentType.MimeType, "Second child of multipart/encrypted is not the expected mime-type");
}
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt ();
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
[Test]
public void TestMultipartEncryptedEncryptUsingKeys ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
IList<PgpPublicKey> recipients;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = ctx.GetPublicKeys (new [] { self });
}
var encrypted = MultipartEncrypted.Encrypt (recipients, body);
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt ();
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
[Test]
public async Task TestMultipartEncryptedEncryptUsingKeysAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
IList<PgpPublicKey> recipients;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = await ctx.GetPublicKeysAsync (new[] { self });
}
var encrypted = await MultipartEncrypted.EncryptAsync (recipients, body);
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt ();
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
[Test]
public void TestMultipartEncryptedEncryptAlgorithm ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
using (var ctx = new DummyOpenPgpContext ()) {
foreach (EncryptionAlgorithm algorithm in Enum.GetValues (typeof (EncryptionAlgorithm))) {
if (!IsSupported (algorithm))
continue;
var encrypted = MultipartEncrypted.Encrypt (algorithm, new [] { self }, body);
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt (ctx);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
}
}
[Test]
public async Task TestMultipartEncryptedEncryptAlgorithmAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
using (var ctx = new DummyOpenPgpContext ()) {
foreach (EncryptionAlgorithm algorithm in Enum.GetValues (typeof (EncryptionAlgorithm))) {
if (!IsSupported (algorithm))
continue;
var encrypted = await MultipartEncrypted.EncryptAsync (algorithm, new[] { self }, body);
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt (ctx);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
}
}
[Test]
public void TestMultipartEncryptedEncryptAlgorithmUsingKeys ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
IList<PgpPublicKey> recipients;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = ctx.GetPublicKeys (new [] { self });
}
foreach (EncryptionAlgorithm algorithm in Enum.GetValues (typeof (EncryptionAlgorithm))) {
if (!IsSupported (algorithm))
continue;
var encrypted = MultipartEncrypted.Encrypt (algorithm, recipients, body);
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt ();
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
}
[Test]
public async Task TestMultipartEncryptedEncryptAlgorithmUsingKeysAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up encrypting..." };
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
IList<PgpPublicKey> recipients;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = await ctx.GetPublicKeysAsync (new[] { self });
}
foreach (EncryptionAlgorithm algorithm in Enum.GetValues (typeof (EncryptionAlgorithm))) {
if (!IsSupported (algorithm))
continue;
var encrypted = await MultipartEncrypted.EncryptAsync (algorithm, recipients, body);
//using (var file = File.Create ("pgp-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt ();
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
}
}
[Test]
public void TestMimeMessageSignAndEncrypt ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
var message = new MimeMessage { Subject = "Test of signing with OpenPGP" };
DigitalSignatureCollection signatures;
using (var ctx = new DummyOpenPgpContext ()) {
// throws because no Body has been set
Assert.Throws<InvalidOperationException> (() => message.SignAndEncrypt (ctx));
message.Body = body;
// throws because no sender has been set
Assert.Throws<InvalidOperationException> (() => message.SignAndEncrypt (ctx));
message.From.Add (self);
message.To.Add (self);
message.SignAndEncrypt (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
var encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt (ctx, out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
// now do the same thing, but encrypt to the Resent-To headers
message.From.Clear ();
message.To.Clear ();
message.From.Add (new MailboxAddress ("Dummy Sender", "dummy@sender.com"));
message.To.Add (new MailboxAddress ("Dummy Recipient", "dummy@recipient.com"));
message.ResentFrom.Add (self);
message.ResentTo.Add (self);
message.Body = body;
message.SignAndEncrypt (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
decrypted = encrypted.Decrypt (ctx, out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
}
[Test]
public async Task TestMimeMessageSignAndEncryptAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
var message = new MimeMessage { Subject = "Test of signing with OpenPGP" };
DigitalSignatureCollection signatures;
using (var ctx = new DummyOpenPgpContext ()) {
// throws because no Body has been set
Assert.ThrowsAsync<InvalidOperationException> (() => message.SignAndEncryptAsync (ctx));
message.Body = body;
// throws because no sender has been set
Assert.ThrowsAsync<InvalidOperationException> (() => message.SignAndEncryptAsync (ctx));
message.From.Add (self);
message.To.Add (self);
await message.SignAndEncryptAsync (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
var encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt (ctx, out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
// now do the same thing, but encrypt to the Resent-To headers
message.From.Clear ();
message.To.Clear ();
message.From.Add (new MailboxAddress ("Dummy Sender", "dummy@sender.com"));
message.To.Add (new MailboxAddress ("Dummy Recipient", "dummy@recipient.com"));
message.ResentFrom.Add (self);
message.ResentTo.Add (self);
message.Body = body;
await message.SignAndEncryptAsync (ctx);
Assert.IsInstanceOf<MultipartEncrypted> (message.Body);
encrypted = (MultipartEncrypted) message.Body;
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
decrypted = encrypted.Decrypt (ctx, out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
}
[Test]
public void TestMultipartEncryptedSignAndEncrypt ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
var encrypted = MultipartEncrypted.SignAndEncrypt (self, DigestAlgorithm.Sha1, new [] { self }, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public async Task TestMultipartEncryptedSignAndEncryptAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
var encrypted = await MultipartEncrypted.SignAndEncryptAsync (self, DigestAlgorithm.Sha1, new[] { self }, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public void TestMultipartEncryptedSignAndEncryptUsingKeys ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
IList<PgpPublicKey> recipients;
PgpSecretKey signer;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = ctx.GetPublicKeys (new [] { self });
signer = ctx.GetSigningKey (self);
}
var encrypted = MultipartEncrypted.SignAndEncrypt (signer, DigestAlgorithm.Sha1, recipients, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public async Task TestMultipartEncryptedSignAndEncryptUsingKeysAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
IList<PgpPublicKey> recipients;
PgpSecretKey signer;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = await ctx.GetPublicKeysAsync (new[] { self });
signer = await ctx.GetSigningKeyAsync (self);
}
var encrypted = await MultipartEncrypted.SignAndEncryptAsync (signer, DigestAlgorithm.Sha1, recipients, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public void TestMultipartEncryptedSignAndEncryptAlgorithm ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
var encrypted = MultipartEncrypted.SignAndEncrypt (self, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, new [] { self }, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public async Task TestMultipartEncryptedSignAndEncryptAlgorithmAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
var encrypted = await MultipartEncrypted.SignAndEncryptAsync (self, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, new[] { self }, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public void TestMultipartEncryptedSignAndEncryptAlgorithmUsingKeys ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
IList<PgpPublicKey> recipients;
PgpSecretKey signer;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = ctx.GetPublicKeys (new [] { self });
signer = ctx.GetSigningKey (self);
}
var encrypted = MultipartEncrypted.SignAndEncrypt (signer, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, recipients, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public async Task TestMultipartEncryptedSignAndEncryptAlgorithmUsingKeysAsync ()
{
var body = new TextPart ("plain") { Text = "This is some cleartext that we'll end up signing and encrypting..." };
var self = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", "AB0821A2");
DigitalSignatureCollection signatures;
IList<PgpPublicKey> recipients;
PgpSecretKey signer;
using (var ctx = new DummyOpenPgpContext ()) {
recipients = await ctx.GetPublicKeysAsync (new[] { self });
signer = await ctx.GetSigningKeyAsync (self);
}
var encrypted = await MultipartEncrypted.SignAndEncryptAsync (signer, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, recipients, body);
//using (var file = File.Create ("pgp-signed-encrypted.asc"))
// encrypted.WriteTo (file);
// TODO: implement DecryptAsync
var decrypted = encrypted.Decrypt (out signatures);
Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted part is not the expected type.");
Assert.AreEqual (body.Text, ((TextPart) decrypted).Text, "Decrypted content is not the same as the original.");
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException ex) {
Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public void TestAutoKeyRetrieve ()
{
var message = MimeMessage.Load (Path.Combine (TestHelper.ProjectDir, "TestData", "openpgp", "[Announce] GnuPG 2.1.20 released.eml"));
var multipart = (MultipartSigned) ((Multipart) message.Body)[0];
Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children.");
var protocol = multipart.ContentType.Parameters["protocol"];
Assert.AreEqual ("application/pgp-signature", protocol, "The multipart/signed protocol does not match.");
var micalg = multipart.ContentType.Parameters["micalg"];
Assert.AreEqual ("pgp-sha1", micalg, "The multipart/signed micalg does not match.");
Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part.");
Assert.IsInstanceOf<ApplicationPgpSignature> (multipart[1], "The second child is not a detached signature.");
DigitalSignatureCollection signatures;
try {
signatures = multipart.Verify ();
} catch (IOException ex) {
if (ex.Message == "unknown PGP public key algorithm encountered") {
Assert.Ignore ("Known issue: {0}", ex.Message);
return;
}
throw;
}
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException) {
// Note: Werner Koch's keyring has an EdDSA subkey which breaks BouncyCastle's
// PgpPublicKeyRingBundle reader. If/when one of the round-robin keys.gnupg.net
// key servers returns this particular keyring, we can expect to get an exception
// about being unable to find Werner's public key.
//Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public async Task TestAutoKeyRetrieveAsync ()
{
var message = await MimeMessage.LoadAsync (Path.Combine (TestHelper.ProjectDir, "TestData", "openpgp", "[Announce] GnuPG 2.1.20 released.eml"));
var multipart = (MultipartSigned) ((Multipart) message.Body)[0];
Assert.AreEqual (2, multipart.Count, "The multipart/signed has an unexpected number of children.");
var protocol = multipart.ContentType.Parameters["protocol"];
Assert.AreEqual ("application/pgp-signature", protocol, "The multipart/signed protocol does not match.");
var micalg = multipart.ContentType.Parameters["micalg"];
Assert.AreEqual ("pgp-sha1", micalg, "The multipart/signed micalg does not match.");
Assert.IsInstanceOf<TextPart> (multipart[0], "The first child is not a text part.");
Assert.IsInstanceOf<ApplicationPgpSignature> (multipart[1], "The second child is not a detached signature.");
DigitalSignatureCollection signatures;
try {
signatures = await multipart.VerifyAsync ();
} catch (IOException ex) {
if (ex.Message == "unknown PGP public key algorithm encountered") {
Assert.Ignore ("Known issue: {0}", ex.Message);
return;
}
throw;
}
Assert.AreEqual (1, signatures.Count, "Verify returned an unexpected number of signatures.");
foreach (var signature in signatures) {
try {
bool valid = signature.Verify ();
Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email);
} catch (DigitalSignatureVerifyException) {
// Note: Werner Koch's keyring has an EdDSA subkey which breaks BouncyCastle's
// PgpPublicKeyRingBundle reader. If/when one of the round-robin keys.gnupg.net
// key servers returns this particular keyring, we can expect to get an exception
// about being unable to find Werner's public key.
//Assert.Fail ("Failed to verify signature: {0}", ex);
}
}
}
[Test]
public void TestExport ()
{
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
using (var ctx = new DummyOpenPgpContext ()) {
Assert.AreEqual ("application/pgp-keys", ctx.KeyExchangeProtocol, "The key-exchange protocol does not match.");
var keys = ctx.EnumeratePublicKeys (self).ToList ();
var exported = ctx.Export (new [] { self });
Assert.IsNotNull (exported, "The exported MIME part should not be null.");
Assert.IsInstanceOf<MimePart> (exported, "The exported MIME part should be a MimePart.");
Assert.AreEqual ("application/pgp-keys", exported.ContentType.MimeType);
exported = ctx.Export (keys);
Assert.IsNotNull (exported, "The exported MIME part should not be null.");
Assert.IsInstanceOf<MimePart> (exported, "The exported MIME part should be a MimePart.");
Assert.AreEqual ("application/pgp-keys", exported.ContentType.MimeType);
using (var stream = new MemoryStream ()) {
ctx.Export (new[] { self }, stream, true);
Assert.AreEqual (exported.Content.Stream.Length, stream.Length);
}
foreach (var keyring in ctx.EnumeratePublicKeyRings (self)) {
using (var stream = new MemoryStream ()) {
ctx.Export (new[] { self }, stream, true);
Assert.AreEqual (exported.Content.Stream.Length, stream.Length);
}
}
using (var stream = new MemoryStream ()) {
ctx.Export (keys, stream, true);
Assert.AreEqual (exported.Content.Stream.Length, stream.Length);
}
}
}
[Test]
public async Task TestExportAsync ()
{
var self = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com");
using (var ctx = new DummyOpenPgpContext ()) {
Assert.AreEqual ("application/pgp-keys", ctx.KeyExchangeProtocol, "The key-exchange protocol does not match.");
var keys = ctx.EnumeratePublicKeys (self).ToList ();
var exported = await ctx.ExportAsync (new[] { self });
Assert.IsNotNull (exported, "The exported MIME part should not be null.");
Assert.IsInstanceOf<MimePart> (exported, "The exported MIME part should be a MimePart.");
Assert.AreEqual ("application/pgp-keys", exported.ContentType.MimeType);
exported = await ctx.ExportAsync (keys);
Assert.IsNotNull (exported, "The exported MIME part should not be null.");
Assert.IsInstanceOf<MimePart> (exported, "The exported MIME part should be a MimePart.");
Assert.AreEqual ("application/pgp-keys", exported.ContentType.MimeType);
using (var stream = new MemoryStream ()) {
await ctx.ExportAsync (new[] { self }, stream, true);
Assert.AreEqual (exported.Content.Stream.Length, stream.Length);
}
foreach (var keyring in ctx.EnumeratePublicKeyRings (self)) {
using (var stream = new MemoryStream ()) {
await ctx.ExportAsync (new[] { self }, stream, true);
Assert.AreEqual (exported.Content.Stream.Length, stream.Length);
}
}
using (var stream = new MemoryStream ()) {
await ctx.ExportAsync (keys, stream, true);
Assert.AreEqual (exported.Content.Stream.Length, stream.Length);
}
}
}
[Test]
public void TestDefaultEncryptionAlgorithm ()
{
using (var ctx = new DummyOpenPgpContext ()) {
foreach (EncryptionAlgorithm algorithm in Enum.GetValues (typeof (EncryptionAlgorithm))) {
if (!IsSupported (algorithm)) {
Assert.Throws<NotSupportedException> (() => ctx.DefaultEncryptionAlgorithm = algorithm);
continue;
}
ctx.DefaultEncryptionAlgorithm = algorithm;
Assert.AreEqual (algorithm, ctx.DefaultEncryptionAlgorithm, "Default encryption algorithm does not match.");
}
}
}
[Test]
public void TestSupports ()
{
var supports = new [] { "application/pgp-encrypted", "application/pgp-signature", "application/pgp-keys",
"application/x-pgp-encrypted", "application/x-pgp-signature", "application/x-pgp-keys" };
using (var ctx = new DummyOpenPgpContext ()) {
for (int i = 0; i < supports.Length; i++)
Assert.IsTrue (ctx.Supports (supports[i]), supports[i]);
Assert.IsFalse (ctx.Supports ("application/octet-stream"), "application/octet-stream");
Assert.IsFalse (ctx.Supports ("text/plain"), "text/plain");
}
}
[Test]
public void TestAlgorithmMappings ()
{
using (var ctx = new DummyOpenPgpContext ()) {
foreach (DigestAlgorithm digest in Enum.GetValues (typeof (DigestAlgorithm))) {
if (digest == DigestAlgorithm.None || digest == DigestAlgorithm.DoubleSha)
continue;
var name = ctx.GetDigestAlgorithmName (digest);
var algo = ctx.GetDigestAlgorithm (name);
Assert.AreEqual (digest, algo);
}
Assert.AreEqual (DigestAlgorithm.MD5, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.MD5));
Assert.AreEqual (DigestAlgorithm.Sha1, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.Sha1));
Assert.AreEqual (DigestAlgorithm.RipeMD160, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.RipeMD160));
Assert.AreEqual (DigestAlgorithm.DoubleSha, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.DoubleSha));
Assert.AreEqual (DigestAlgorithm.MD2, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.MD2));
Assert.AreEqual (DigestAlgorithm.Tiger192, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.Tiger192));
Assert.AreEqual (DigestAlgorithm.Haval5160, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.Haval5pass160));
Assert.AreEqual (DigestAlgorithm.Sha256, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.Sha256));
Assert.AreEqual (DigestAlgorithm.Sha384, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.Sha384));
Assert.AreEqual (DigestAlgorithm.Sha512, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.Sha512));
Assert.AreEqual (DigestAlgorithm.Sha224, OpenPgpContext.GetDigestAlgorithm (Org.BouncyCastle.Bcpg.HashAlgorithmTag.Sha224));
Assert.AreEqual (PublicKeyAlgorithm.RsaGeneral, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.RsaGeneral));
Assert.AreEqual (PublicKeyAlgorithm.RsaEncrypt, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.RsaEncrypt));
Assert.AreEqual (PublicKeyAlgorithm.RsaSign, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.RsaSign));
Assert.AreEqual (PublicKeyAlgorithm.ElGamalGeneral, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.ElGamalGeneral));
Assert.AreEqual (PublicKeyAlgorithm.ElGamalEncrypt, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.ElGamalEncrypt));
Assert.AreEqual (PublicKeyAlgorithm.Dsa, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.Dsa));
Assert.AreEqual (PublicKeyAlgorithm.EllipticCurve, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.ECDH));
Assert.AreEqual (PublicKeyAlgorithm.EllipticCurveDsa, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.ECDsa));
Assert.AreEqual (PublicKeyAlgorithm.DiffieHellman, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.DiffieHellman));
//Assert.AreEqual (PublicKeyAlgorithm.EdwardsCurveDsa, OpenPgpContext.GetPublicKeyAlgorithm (Org.BouncyCastle.Bcpg.PublicKeyAlgorithmTag.EdDSA));
}
}
[Test]
public void TestArgumentExceptions ()
{
Assert.Throws<ArgumentNullException> (() => CryptographyContext.Create (null));
Assert.Throws<ArgumentNullException> (() => CryptographyContext.Register ((Type) null));
Assert.Throws<ArgumentNullException> (() => CryptographyContext.Register ((Func<OpenPgpContext>) null));
Assert.Throws<ArgumentNullException> (() => CryptographyContext.Register ((Func<SecureMimeContext>) null));
using (var ctx = new DummyOpenPgpContext ()) {
var clientEastwood = new MailboxAddress ("Man with No Name", "client.eastwood@fistfullofdollars.com");
var mailboxes = new [] { new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com") };
var emptyMailboxes = new MailboxAddress[0];
var pubkeys = ctx.GetPublicKeys (mailboxes);
var key = ctx.GetSigningKey (mailboxes[0]);
var emptyPubkeys = new PgpPublicKey[0];
DigitalSignatureCollection signatures;
var stream = new MemoryStream ();
var entity = new MimePart ();
Assert.Throws<ArgumentException> (() => ctx.KeyServer = new Uri ("relative/uri", UriKind.Relative));
Assert.Throws<ArgumentNullException> (() => ctx.GetDigestAlgorithm (null));
Assert.Throws<ArgumentOutOfRangeException> (() => ctx.GetDigestAlgorithmName (DigestAlgorithm.DoubleSha));
Assert.Throws<NotSupportedException> (() => OpenPgpContext.GetHashAlgorithm (DigestAlgorithm.DoubleSha));
Assert.Throws<NotSupportedException> (() => OpenPgpContext.GetHashAlgorithm (DigestAlgorithm.Tiger192));
Assert.Throws<NotSupportedException> (() => OpenPgpContext.GetHashAlgorithm (DigestAlgorithm.Haval5160));
Assert.Throws<NotSupportedException> (() => OpenPgpContext.GetHashAlgorithm (DigestAlgorithm.MD4));
Assert.Throws<ArgumentOutOfRangeException> (() => OpenPgpContext.GetDigestAlgorithm ((Org.BouncyCastle.Bcpg.HashAlgorithmTag) 1024));
Assert.Throws<ArgumentNullException> (() => new ApplicationPgpEncrypted ((MimeEntityConstructorArgs) null));
Assert.Throws<ArgumentNullException> (() => new ApplicationPgpSignature ((MimeEntityConstructorArgs) null));
Assert.Throws<ArgumentNullException> (() => new ApplicationPgpSignature ((Stream) null));
// Accept
Assert.Throws<ArgumentNullException> (() => new ApplicationPgpEncrypted ().Accept (null));
Assert.Throws<ArgumentNullException> (() => new ApplicationPgpSignature (stream).Accept (null));
Assert.Throws<ArgumentNullException> (() => ctx.CanSign (null));
Assert.Throws<ArgumentNullException> (() => ctx.CanEncrypt (null));
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.CanSignAsync (null));
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.CanEncryptAsync (null));
// Delete
Assert.Throws<ArgumentNullException> (() => ctx.Delete ((PgpPublicKeyRing) null), "Delete");
Assert.Throws<ArgumentNullException> (() => ctx.Delete ((PgpSecretKeyRing) null), "Delete");
// Decrypt
Assert.Throws<ArgumentNullException> (() => ctx.Decrypt (null), "Decrypt");
// Encrypt
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt (EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, stream), "Encrypt");
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt (EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, stream), "Encrypt");
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt ((MailboxAddress[]) null, stream), "Encrypt");
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt ((PgpPublicKey[]) null, stream), "Encrypt");
Assert.Throws<ArgumentException> (() => ctx.Encrypt (EncryptionAlgorithm.Cast5, emptyMailboxes, stream), "Encrypt");
Assert.Throws<ArgumentException> (() => ctx.Encrypt (EncryptionAlgorithm.Cast5, emptyPubkeys, stream), "Encrypt");
Assert.Throws<ArgumentException> (() => ctx.Encrypt (emptyMailboxes, stream), "Encrypt");
Assert.Throws<ArgumentException> (() => ctx.Encrypt (emptyPubkeys, stream), "Encrypt");
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt (EncryptionAlgorithm.Cast5, mailboxes, null), "Encrypt");
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt (EncryptionAlgorithm.Cast5, pubkeys, null), "Encrypt");
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt (mailboxes, null), "Encrypt");
Assert.Throws<ArgumentNullException> (() => ctx.Encrypt (pubkeys, null), "Encrypt");
// EncryptAsync
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync (EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync (EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync ((MailboxAddress[]) null, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync ((PgpPublicKey[]) null, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.EncryptAsync (EncryptionAlgorithm.Cast5, emptyMailboxes, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.EncryptAsync (EncryptionAlgorithm.Cast5, emptyPubkeys, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.EncryptAsync (emptyMailboxes, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.EncryptAsync (emptyPubkeys, stream), "EncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync (EncryptionAlgorithm.Cast5, mailboxes, null), "EncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync (EncryptionAlgorithm.Cast5, pubkeys, null), "EncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync (mailboxes, null), "EncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.EncryptAsync (pubkeys, null), "EncryptAsync");
// Export
Assert.Throws<ArgumentNullException> (() => ctx.Export ((PgpPublicKeyRingBundle) null), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export ((MailboxAddress[]) null), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export ((PgpPublicKey[]) null), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export ((PgpPublicKeyRingBundle) null, stream, true), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export ((MailboxAddress[]) null, stream, true), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export ((PgpPublicKey[]) null, stream, true), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export (ctx.PublicKeyRingBundle, null, true), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export (mailboxes, null, true), "Export");
Assert.Throws<ArgumentNullException> (() => ctx.Export (pubkeys, null, true), "Export");
// ExportAsync
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync ((PgpPublicKeyRingBundle) null), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync ((MailboxAddress[]) null), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync ((PgpPublicKey[]) null), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync ((PgpPublicKeyRingBundle) null, stream, true), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync ((MailboxAddress[]) null, stream, true), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync ((PgpPublicKey[]) null, stream, true), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync (ctx.PublicKeyRingBundle, null, true), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync (mailboxes, null, true), "ExportAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ExportAsync (pubkeys, null, true), "ExportAsync");
// EnumeratePublicKey[Ring]s
Assert.Throws<ArgumentNullException> (() => ctx.EnumeratePublicKeyRings (null).FirstOrDefault ());
Assert.Throws<ArgumentNullException> (() => ctx.EnumeratePublicKeys (null).FirstOrDefault ());
Assert.Throws<ArgumentNullException> (() => ctx.EnumerateSecretKeyRings (null).FirstOrDefault ());
Assert.Throws<ArgumentNullException> (() => ctx.EnumerateSecretKeys (null).FirstOrDefault ());
// GenerateKeyPair
Assert.Throws<ArgumentNullException> (() => ctx.GenerateKeyPair (null, "password"));
Assert.Throws<ArgumentNullException> (() => ctx.GenerateKeyPair (mailboxes[0], null));
Assert.Throws<ArgumentException> (() => ctx.GenerateKeyPair (mailboxes[0], "password", DateTime.Now));
// DecryptTo
Assert.Throws<ArgumentNullException> (() => ctx.DecryptTo (null, stream), "DecryptTo");
Assert.Throws<ArgumentNullException> (() => ctx.DecryptTo (stream, null), "DecryptTo");
// DecryptToAsync
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.DecryptToAsync (null, stream), "DecryptToAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.DecryptToAsync (stream, null), "DecryptToAsync");
// GetDigestAlgorithmName
Assert.Throws<ArgumentOutOfRangeException> (() => ctx.GetDigestAlgorithmName (DigestAlgorithm.None), "GetDigestAlgorithmName");
// GetPublicKeys
Assert.Throws<ArgumentNullException> (() => ctx.GetPublicKeys (null));
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.GetPublicKeysAsync (null));
Assert.Throws<PublicKeyNotFoundException> (() => ctx.GetPublicKeys (new MailboxAddress[] { clientEastwood }));
Assert.ThrowsAsync<PublicKeyNotFoundException> (() => ctx.GetPublicKeysAsync (new MailboxAddress[] { clientEastwood }));
// GetSigningKey
Assert.Throws<ArgumentNullException> (() => ctx.GetSigningKey (null));
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.GetSigningKeyAsync (null));
Assert.Throws<PrivateKeyNotFoundException> (() => ctx.GetSigningKey (clientEastwood));
Assert.ThrowsAsync<PrivateKeyNotFoundException> (() => ctx.GetSigningKeyAsync (clientEastwood));
// Import
Assert.Throws<ArgumentNullException> (() => ctx.Import ((Stream) null), "Import");
Assert.Throws<ArgumentNullException> (() => ctx.Import ((PgpPublicKeyRing) null), "Import");
Assert.Throws<ArgumentNullException> (() => ctx.Import ((PgpPublicKeyRingBundle) null), "Import");
Assert.Throws<ArgumentNullException> (() => ctx.Import ((PgpSecretKeyRing) null), "Import");
Assert.Throws<ArgumentNullException> (() => ctx.Import ((PgpSecretKeyRingBundle) null), "Import");
// ImportAsync
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ImportAsync ((Stream) null), "ImportAsync");
//Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ImportAsync ((PgpPublicKeyRing) null), "ImportAsync");
//Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ImportAsync ((PgpPublicKeyRingBundle) null), "ImportAsync");
//Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ImportAsync ((PgpSecretKeyRing) null), "ImportAsync");
//Assert.ThrowsAsync<ArgumentNullException> (() => ctx.ImportAsync ((PgpSecretKeyRingBundle) null), "ImportAsync");
// Sign
Assert.Throws<ArgumentNullException> (() => ctx.Sign ((MailboxAddress) null, DigestAlgorithm.Sha1, stream), "Sign");
Assert.Throws<ArgumentNullException> (() => ctx.Sign ((PgpSecretKey) null, DigestAlgorithm.Sha1, stream), "Sign");
Assert.Throws<ArgumentNullException> (() => ctx.Sign (mailboxes[0], DigestAlgorithm.Sha1, null), "Sign");
Assert.Throws<ArgumentNullException> (() => ctx.Sign (key, DigestAlgorithm.Sha1, null), "Sign");
// SignAsync
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAsync ((MailboxAddress) null, DigestAlgorithm.Sha1, stream), "SignAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAsync ((PgpSecretKey) null, DigestAlgorithm.Sha1, stream), "SignAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAsync (mailboxes[0], DigestAlgorithm.Sha1, null), "SignAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAsync (key, DigestAlgorithm.Sha1, null), "SignAsync");
// SignAndEncrypt
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt ((MailboxAddress) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt ((PgpSecretKey) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, stream), "SignAndEncrypt");
Assert.Throws<ArgumentException> (() => ctx.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyMailboxes, stream), "SignAndEncrypt");
Assert.Throws<ArgumentException> (() => ctx.SignAndEncrypt (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyPubkeys, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, null), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, null), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt ((MailboxAddress) null, DigestAlgorithm.Sha1, mailboxes, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt ((PgpSecretKey) null, DigestAlgorithm.Sha1, pubkeys, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, (MailboxAddress[]) null, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (key, DigestAlgorithm.Sha1, (PgpPublicKey[]) null, stream), "SignAndEncrypt");
Assert.Throws<ArgumentException> (() => ctx.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, emptyMailboxes, stream), "SignAndEncrypt");
Assert.Throws<ArgumentException> (() => ctx.SignAndEncrypt (key, DigestAlgorithm.Sha1, emptyPubkeys, stream), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, mailboxes, null), "SignAndEncrypt");
Assert.Throws<ArgumentNullException> (() => ctx.SignAndEncrypt (key, DigestAlgorithm.Sha1, pubkeys, null), "SignAndEncrypt");
// SignAndEncryptAsync
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync ((MailboxAddress) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync ((PgpSecretKey) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyMailboxes, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyPubkeys, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, null), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, null), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync ((MailboxAddress) null, DigestAlgorithm.Sha1, mailboxes, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync ((PgpSecretKey) null, DigestAlgorithm.Sha1, pubkeys, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, (MailboxAddress[]) null, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, (PgpPublicKey[]) null, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, emptyMailboxes, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentException> (() => ctx.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, emptyPubkeys, stream), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, mailboxes, null), "SignAndEncryptAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, pubkeys, null), "SignAndEncryptAsync");
// SignKey
Assert.Throws<ArgumentNullException> (() => ctx.SignKey (null, pubkeys[0]), "SignKey");
Assert.Throws<ArgumentNullException> (() => ctx.SignKey (key, null), "SignKey");
// Supports
Assert.Throws<ArgumentNullException> (() => ctx.Supports (null), "Supports");
// Verify
Assert.Throws<ArgumentNullException> (() => ctx.Verify (null, stream), "Verify");
Assert.Throws<ArgumentNullException> (() => ctx.Verify (stream, null), "Verify");
// VerifyAsync
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.VerifyAsync (null, stream), "VerifyAsync");
Assert.ThrowsAsync<ArgumentNullException> (() => ctx.VerifyAsync (stream, null), "VerifyAsync");
// MultipartEncrypted
// Encrypt
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt ((MailboxAddress[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt ((PgpPublicKey[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (pubkeys, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (null, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, (MailboxAddress[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (ctx, emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (null, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, (PgpPublicKey[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (ctx, emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, pubkeys, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (EncryptionAlgorithm.Cast5, pubkeys, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (null, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (ctx, EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (null, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.Encrypt (ctx, EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.Encrypt (ctx, EncryptionAlgorithm.Cast5, pubkeys, null));
// EncryptAsync
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync ((MailboxAddress[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync ((PgpPublicKey[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (pubkeys, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (null, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, (MailboxAddress[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (ctx, emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (null, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, (PgpPublicKey[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (ctx, emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, pubkeys, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (EncryptionAlgorithm.Cast5, pubkeys, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (null, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, EncryptionAlgorithm.Cast5, (MailboxAddress[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (ctx, EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (null, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, EncryptionAlgorithm.Cast5, (PgpPublicKey[]) null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.EncryptAsync (ctx, EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.EncryptAsync (ctx, EncryptionAlgorithm.Cast5, pubkeys, null));
// SignAndEncrypt
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt ((MailboxAddress) null, DigestAlgorithm.Sha1, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt ((PgpSecretKey) null, DigestAlgorithm.Sha1, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (key, DigestAlgorithm.Sha1, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (key, DigestAlgorithm.Sha1, emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (key, DigestAlgorithm.Sha1, pubkeys, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (null, mailboxes[0], DigestAlgorithm.Sha1, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, (MailboxAddress) null, DigestAlgorithm.Sha1, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, mailboxes[0], DigestAlgorithm.Sha1, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (ctx, mailboxes[0], DigestAlgorithm.Sha1, emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, mailboxes[0], DigestAlgorithm.Sha1, mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (null, key, DigestAlgorithm.Sha1, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, (PgpSecretKey) null, DigestAlgorithm.Sha1, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, key, DigestAlgorithm.Sha1, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (ctx, key, DigestAlgorithm.Sha1, emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, key, DigestAlgorithm.Sha1, pubkeys, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt ((MailboxAddress) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt ((PgpSecretKey) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (null, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, (MailboxAddress) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (ctx, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (null, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, (PgpSecretKey) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.Throws<ArgumentException> (() => MultipartEncrypted.SignAndEncrypt (ctx, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.Throws<ArgumentNullException> (() => MultipartEncrypted.SignAndEncrypt (ctx, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, null));
// SignAndEncryptAsync
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync ((MailboxAddress) null, DigestAlgorithm.Sha1, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync ((PgpSecretKey) null, DigestAlgorithm.Sha1, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, pubkeys, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (null, mailboxes[0], DigestAlgorithm.Sha1, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, (MailboxAddress) null, DigestAlgorithm.Sha1, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, mailboxes[0], DigestAlgorithm.Sha1, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, mailboxes[0], DigestAlgorithm.Sha1, emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, mailboxes[0], DigestAlgorithm.Sha1, mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (null, key, DigestAlgorithm.Sha1, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, (PgpSecretKey) null, DigestAlgorithm.Sha1, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, key, DigestAlgorithm.Sha1, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, key, DigestAlgorithm.Sha1, emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, key, DigestAlgorithm.Sha1, pubkeys, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync ((MailboxAddress) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync ((PgpSecretKey) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (null, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, (MailboxAddress) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyMailboxes, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, mailboxes[0], DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, mailboxes, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (null, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, (PgpSecretKey) null, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, null, entity));
Assert.ThrowsAsync<ArgumentException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, emptyPubkeys, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartEncrypted.SignAndEncryptAsync (ctx, key, DigestAlgorithm.Sha1, EncryptionAlgorithm.Cast5, pubkeys, null));
var encrypted = new MultipartEncrypted ();
Assert.Throws<ArgumentNullException> (() => encrypted.Accept (null));
Assert.Throws<ArgumentNullException> (() => encrypted.Decrypt (null));
Assert.Throws<ArgumentNullException> (() => encrypted.Decrypt (null, out signatures));
// MultipartSigned.Create
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (null, mailboxes[0], DigestAlgorithm.Sha1, entity));
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (ctx, (MailboxAddress) null, DigestAlgorithm.Sha1, entity));
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (ctx, mailboxes[0], DigestAlgorithm.Sha1, null));
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (null, key, DigestAlgorithm.Sha1, entity));
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (ctx, (PgpSecretKey) null, DigestAlgorithm.Sha1, entity));
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (ctx, key, DigestAlgorithm.Sha1, null));
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create ((PgpSecretKey) null, DigestAlgorithm.Sha1, entity));
Assert.Throws<ArgumentNullException> (() => MultipartSigned.Create (key, DigestAlgorithm.Sha1, null));
// MultipartSigned.CreateAsync
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync (null, mailboxes[0], DigestAlgorithm.Sha1, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync (ctx, (MailboxAddress) null, DigestAlgorithm.Sha1, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync (ctx, mailboxes[0], DigestAlgorithm.Sha1, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync (null, key, DigestAlgorithm.Sha1, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync (ctx, (PgpSecretKey) null, DigestAlgorithm.Sha1, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync (ctx, key, DigestAlgorithm.Sha1, null));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync ((PgpSecretKey) null, DigestAlgorithm.Sha1, entity));
Assert.ThrowsAsync<ArgumentNullException> (() => MultipartSigned.CreateAsync (key, DigestAlgorithm.Sha1, null));
var signed = MultipartSigned.Create (key, DigestAlgorithm.Sha1, entity);
Assert.Throws<ArgumentNullException> (() => signed.Accept (null));
Assert.Throws<ArgumentOutOfRangeException> (() => signed.Prepare (EncodingConstraint.SevenBit, 0));
Assert.Throws<ArgumentNullException> (() => signed.Verify (null));
Assert.ThrowsAsync<ArgumentNullException> (() => signed.VerifyAsync (null));
}
}
static void PumpDataThroughFilter (IMimeFilter filter, string fileName, bool isText)
{
using (var stream = File.OpenRead (fileName)) {
using (var filtered = new FilteredStream (stream)) {
var buffer = new byte[1];
int outputLength;
int outputIndex;
int n;
if (isText)
filtered.Add (new Unix2DosFilter ());
while ((n = filtered.Read (buffer, 0, buffer.Length)) > 0)
filter.Filter (buffer, 0, n, out outputIndex, out outputLength);
filter.Flush (buffer, 0, 0, out outputIndex, out outputLength);
}
}
}
[Test]
public void TestOpenPgpDetectionFilter ()
{
var filter = new OpenPgpDetectionFilter ();
PumpDataThroughFilter (filter, Path.Combine (TestHelper.ProjectDir, "TestData", "openpgp", "mimekit.gpg.pub"), true);
Assert.AreEqual (OpenPgpDataType.PublicKey, filter.DataType);
Assert.AreEqual (0, filter.BeginOffset);
Assert.AreEqual (1754, filter.EndOffset);
filter.Reset ();
PumpDataThroughFilter (filter, Path.Combine (TestHelper.ProjectDir, "TestData", "openpgp", "mimekit.gpg.sec"), true);
Assert.AreEqual (OpenPgpDataType.PrivateKey, filter.DataType);
Assert.AreEqual (0, filter.BeginOffset);
Assert.AreEqual (3650, filter.EndOffset);
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Dependinator.Common.ModelMetadataFolders;
using Dependinator.Common.ModelMetadataFolders.Private;
using Dependinator.Common.SettingsHandling;
using Dependinator.Utils;
using Dependinator.Utils.Dependencies;
using Dependinator.Utils.ErrorHandling;
using Dependinator.Utils.Net;
using Dependinator.Utils.OsSystem;
using Dependinator.Utils.Serialization;
using Dependinator.Utils.Threading;
using Microsoft.Win32;
namespace Dependinator.Common.Installation.Private
{
[SingleInstance]
internal class LatestVersionService : ILatestVersionService
{
private static readonly TimeSpan IdleTimerInterval = TimeSpan.FromMinutes(1);
private static readonly TimeSpan IdleTimeBeforeRestarting = TimeSpan.FromMinutes(10);
private static readonly string latestUri =
"https://api.github.com/repos/michael-reichenauer/Dependinator/releases/latest";
private static readonly string UserAgent = "Dependinator";
private readonly ModelMetadata modelMetadata;
private readonly ISettingsService settingsService;
private readonly IStartInstanceService startInstanceService;
private DispatcherTimer idleTimer;
private DateTime lastIdleCheck = DateTime.MaxValue;
public LatestVersionService(
IStartInstanceService startInstanceService,
ISettingsService settingsService,
ModelMetadata modelMetadata)
{
this.startInstanceService = startInstanceService;
this.settingsService = settingsService;
this.modelMetadata = modelMetadata;
}
public event EventHandler OnNewVersionAvailable;
public void StartCheckForLatestVersion()
{
idleTimer = new DispatcherTimer();
idleTimer.Tick += CheckIdleBeforeRestart;
idleTimer.Interval = IdleTimerInterval;
idleTimer.Start();
SystemEvents.PowerModeChanged += OnPowerModeChange;
}
public async Task CheckLatestVersionAsync()
{
if (settingsService.Get<Options>().DisableAutoUpdate)
{
return;
}
if (await IsNewRemoteVersionAvailableAsync())
{
await DownloadLatestVersionAsync();
await IsNewRemoteVersionAvailableAsync();
}
}
private async Task<bool> IsNewRemoteVersionAvailableAsync()
{
Version remoteVersion = await GetLatestRemoteVersionAsync();
Version currentVersion = Version.Parse(ProgramInfo.Version);
Version installedVersion = ProgramInfo.GetInstalledVersion();
Version setupVersion = ProgramInfo.GetSetupVersion();
LogVersion(currentVersion, installedVersion, remoteVersion, setupVersion);
return installedVersion < remoteVersion && setupVersion < remoteVersion;
}
private async Task<bool> DownloadLatestVersionAsync()
{
try
{
Log.Info($"Downloading remote setup {latestUri} ...");
LatestInfo latestInfo = GetCachedLatestVersionInfo();
if (latestInfo == null)
{
// No installed version.
return false;
}
using (HttpClientDownloadWithProgress httpClient = GetDownloadHttpClient())
{
await DownloadSetupAsync(httpClient, latestInfo);
return true;
}
}
catch (Exception e) when (e.IsNotFatal())
{
Log.Error($"Failed to install new version {e}");
}
return false;
}
private static async Task<string> DownloadSetupAsync(
HttpClientDownloadWithProgress httpClient, LatestInfo latestInfo)
{
Asset setupFileInfo = latestInfo.assets.First(a => a.name == $"{ProgramInfo.Name}Setup.exe");
string downloadUrl = setupFileInfo.browser_download_url;
Log.Info($"Downloading {latestInfo.tag_name} from {downloadUrl} ...");
Timing t = Timing.Start();
httpClient.ProgressChanged += (totalFileSize, totalBytesDownloaded, progressPercentage) =>
{
Log.Info($"Downloading {latestInfo.tag_name} {progressPercentage}% (time: {t.Elapsed}) ...");
};
string setupPath = ProgramInfo.GetSetupFilePath();
if (File.Exists(setupPath))
{
File.Delete(setupPath);
}
await httpClient.StartDownloadAsync(downloadUrl, setupPath);
Log.Info($"Downloaded {latestInfo.tag_name} to {setupPath}");
return setupPath;
}
private async Task<Version> GetLatestRemoteVersionAsync()
{
try
{
M<LatestInfo> latestInfo = await GetLatestInfoAsync();
if (latestInfo.IsOk && latestInfo.Value.tag_name != null)
{
Version version = Version.Parse(latestInfo.Value.tag_name.Substring(1));
return version;
}
}
catch (Exception e) when (e.IsNotFatal())
{
Log.Warn($"Failed to get latest version {e}");
}
return new Version(0, 0, 0, 0);
}
private async Task<M<LatestInfo>> GetLatestInfoAsync()
{
try
{
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("user-agent", UserAgent);
// Try get cached information about latest remote version
string eTag = GetCachedLatestVersionInfoEtag();
if (!string.IsNullOrEmpty(eTag))
{
// There is cached information, lets use the ETag when checking to follow
// GitHub Rate Limiting method.
httpClient.DefaultRequestHeaders.IfNoneMatch.Clear();
httpClient.DefaultRequestHeaders.IfNoneMatch.Add(new EntityTagHeaderValue(eTag));
}
HttpResponseMessage response = await httpClient.GetAsync(latestUri);
if (response.StatusCode == HttpStatusCode.NotModified || response.Content == null)
{
return GetCachedLatestVersionInfo();
}
string latestInfoText = await response.Content.ReadAsStringAsync();
Log.Debug("New version info");
if (response.Headers.ETag != null)
{
eTag = response.Headers.ETag.Tag;
CacheLatestVersionInfo(eTag, latestInfoText);
}
return Json.As<LatestInfo>(latestInfoText);
}
}
catch (Exception e) when (e.IsNotFatal())
{
Log.Exception(e, "Failed to download latest setup");
return Error.From(e);
}
}
private LatestInfo GetCachedLatestVersionInfo()
{
ProgramSettings programSettings = settingsService.Get<ProgramSettings>();
return Json.As<LatestInfo>(programSettings.LatestVersionInfo);
}
private string GetCachedLatestVersionInfoEtag()
{
ProgramSettings programSettings = settingsService.Get<ProgramSettings>();
return programSettings.LatestVersionInfoETag;
}
private void CacheLatestVersionInfo(string eTag, string latestInfoText)
{
if (string.IsNullOrEmpty(eTag)) return;
// Cache the latest version info
settingsService.Edit<ProgramSettings>(s =>
{
s.LatestVersionInfoETag = eTag;
s.LatestVersionInfo = latestInfoText;
});
}
private static void LogVersion(Version current, Version installed, Version remote, Version setup)
{
Log.Usage(
$"Version current: {current}, installed: {installed}, remote: {remote}, setup {setup}");
}
private void NotifyIfNewVersionIsAvailable()
{
if (IsNewVersionInstalled())
{
OnNewVersionAvailable?.Invoke(this, EventArgs.Empty);
}
}
private void OnPowerModeChange(object sender, PowerModeChangedEventArgs e)
{
Log.Info($"Power mode {e.Mode}");
if (e.Mode == PowerModes.Resume)
{
if (IsNewVersionInstalled())
{
Log.Info("Newer version is installed, restart ...");
if (startInstanceService.StartInstance(modelMetadata.ModelFilePath))
{
// Newer version is started, close this instance
Application.Current.Shutdown(0);
}
}
}
}
private void CheckIdleBeforeRestart(object sender, EventArgs e)
{
TimeSpan timeSinceCheck = DateTime.UtcNow - lastIdleCheck;
bool wasSleeping = false;
if (timeSinceCheck > IdleTimerInterval + TimeSpan.FromMinutes(1))
{
// The timer did not tick within the expected timeout, thus computer was probably sleeping.
Log.Info($"Idle timer timeout, was: {timeSinceCheck}");
wasSleeping = true;
}
lastIdleCheck = DateTime.UtcNow;
TimeSpan idleTime = SystemIdle.GetLastInputIdleTimeSpan();
if (wasSleeping || idleTime > IdleTimeBeforeRestarting)
{
if (IsNewVersionInstalled())
{
if (startInstanceService.StartInstance(modelMetadata.ModelFilePath))
{
// Newer version is started, close this instance
Application.Current.Shutdown(0);
}
}
}
}
private static bool IsNewVersionInstalled()
{
Version currentVersion = Version.Parse(ProgramInfo.Version);
Version installedVersion = ProgramInfo.GetInstalledVersion();
Log.Debug($"Current version: {currentVersion} installed version: {installedVersion}");
return currentVersion < installedVersion;
}
private static HttpClientDownloadWithProgress GetDownloadHttpClient()
{
HttpClientDownloadWithProgress client = new HttpClientDownloadWithProgress();
client.NetworkActivityTimeout = TimeSpan.FromSeconds(30);
client.HttpClient.Timeout = TimeSpan.FromSeconds(60 * 5);
client.HttpClient.DefaultRequestHeaders.Add("user-agent", UserAgent);
return client;
}
// Type used when parsing latest version information json
public class LatestInfo
{
public Asset[] assets;
public string tag_name;
}
// Type used when parsing latest version information json
internal class Asset
{
public string browser_download_url;
public int download_count;
public string name;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Light.Data.Mysql.Test
{
class BaseFieldSelectModelNull
{
#region "Data Property"
private int id;
/// <summary>
/// Id
/// </summary>
/// <value></value>
public int Id {
get {
return this.id;
}
set {
this.id = value;
}
}
private bool? boolFieldNull;
/// <summary>
/// BoolField
/// </summary>
/// <value></value>
public bool? BoolFieldNull {
get {
return this.boolFieldNull;
}
set {
this.boolFieldNull = value;
}
}
private sbyte? sbyteFieldNull;
/// <summary>
/// SbyteField
/// </summary>
/// <value></value>
public sbyte? SbyteFieldNull {
get {
return this.sbyteFieldNull;
}
set {
this.sbyteFieldNull = value;
}
}
private byte? byteFieldNull;
/// <summary>
/// ByteField
/// </summary>
/// <value></value>
public byte? ByteFieldNull {
get {
return this.byteFieldNull;
}
set {
this.byteFieldNull = value;
}
}
private short? int16FieldNull;
/// <summary>
/// Int16Field
/// </summary>
/// <value></value>
public short? Int16FieldNull {
get {
return this.int16FieldNull;
}
set {
this.int16FieldNull = value;
}
}
private ushort? uInt16FieldNull;
/// <summary>
/// UInt16Field
/// </summary>
/// <value></value>
public ushort? UInt16FieldNull {
get {
return this.uInt16FieldNull;
}
set {
this.uInt16FieldNull = value;
}
}
private int? int32FieldNull;
/// <summary>
/// Int32Field
/// </summary>
/// <value></value>
public int? Int32FieldNull {
get {
return this.int32FieldNull;
}
set {
this.int32FieldNull = value;
}
}
private uint? uInt32FieldNull;
/// <summary>
/// UInt32Field
/// </summary>
/// <value></value>
public uint? UInt32FieldNull {
get {
return this.uInt32FieldNull;
}
set {
this.uInt32FieldNull = value;
}
}
private long? int64FieldNull;
/// <summary>
/// Int64Field
/// </summary>
/// <value></value>
public long? Int64FieldNull {
get {
return this.int64FieldNull;
}
set {
this.int64FieldNull = value;
}
}
private ulong? uInt64FieldNull;
/// <summary>
/// UInt64Field
/// </summary>
/// <value></value>
public ulong? UInt64FieldNull {
get {
return this.uInt64FieldNull;
}
set {
this.uInt64FieldNull = value;
}
}
private float? floatFieldNull;
/// <summary>
/// FloatField
/// </summary>
/// <value></value>
public float? FloatFieldNull {
get {
return this.floatFieldNull;
}
set {
this.floatFieldNull = value;
}
}
private double? doubleFieldNull;
/// <summary>
/// DoubleField
/// </summary>
/// <value></value>
public double? DoubleFieldNull {
get {
return this.doubleFieldNull;
}
set {
this.doubleFieldNull = value;
}
}
private decimal? decimalFieldNull;
/// <summary>
/// DecimalField
/// </summary>
/// <value></value>
public decimal? DecimalFieldNull {
get {
return this.decimalFieldNull;
}
set {
this.decimalFieldNull = value;
}
}
private DateTime? dateTimeFieldNull;
/// <summary>
/// DateTimeField
/// </summary>
/// <value></value>
public DateTime? DateTimeFieldNull {
get {
return this.dateTimeFieldNull;
}
set {
this.dateTimeFieldNull = value;
}
}
private string varcharFieldNull;
/// <summary>
/// VarcharField
/// </summary>
/// <value></value>
public string VarcharFieldNull {
get {
return this.varcharFieldNull;
}
set {
this.varcharFieldNull = value;
}
}
private string textFieldNull;
/// <summary>
/// TextField
/// </summary>
/// <value></value>
public string TextFieldNull {
get {
return this.textFieldNull;
}
set {
this.textFieldNull = value;
}
}
private byte[] bigDataFieldNull;
/// <summary>
/// BigDataField
/// </summary>
/// <value></value>
public byte[] BigDataFieldNull {
get {
return this.bigDataFieldNull;
}
set {
this.bigDataFieldNull = value;
}
}
private EnumInt32Type enumInt32FieldNull;
/// <summary>
/// EnumInt32Field
/// </summary>
/// <value></value>
public EnumInt32Type EnumInt32FieldNull {
get {
return this.enumInt32FieldNull;
}
set {
this.enumInt32FieldNull = value;
}
}
private EnumInt64Type enumInt64FieldNull;
/// <summary>
/// EnumInt64Field
/// </summary>
/// <value></value>
public EnumInt64Type EnumInt64FieldNull {
get {
return this.enumInt64FieldNull;
}
set {
this.enumInt64FieldNull = value;
}
}
#endregion
}
}
|
using SharpDX;
using SharpDX.Direct3D11;
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Xml;
using System.IO;
using System.Reflection;
namespace Profiler.DirectX
{
public class TextManager : IDisposable
{
[StructLayout(LayoutKind.Sequential)]
public struct Vertex
{
public Vector2 Position;
public Vector2 UV;
public SharpDX.Color Color;
}
DynamicBuffer<Vertex> VertexBuffer;
DynamicBuffer<int> IndexBuffer;
Mesh TextMesh;
class Font : IDisposable
{
public struct Symbol
{
public RectangleF UV;
public Size2F Size;
public float Advance;
}
public Symbol[] Symbols = new Symbol[256];
public Texture2D Texture;
public ShaderResourceView TextureView;
public double Size { get; set; }
public static Font Create(Device device, String name)
{
Font font = new Font();
Assembly assembly = Assembly.GetExecutingAssembly();
using (Stream stream = assembly.GetManifestResourceStream(String.Format("Profiler.DirectX.Fonts.{0}.fnt", name)))
{
XmlDocument doc = new XmlDocument();
doc.Load(stream);
XmlNode desc = doc.SelectSingleNode("//info");
font.Size = double.Parse(desc.Attributes["size"].Value);
XmlNode info = doc.SelectSingleNode("//common");
float width = float.Parse(info.Attributes["scaleW"].Value);
float height = float.Parse(info.Attributes["scaleH"].Value);
foreach (XmlNode node in doc.SelectNodes("//char"))
{
int id = int.Parse(node.Attributes["id"].Value);
Symbol symbol = new Symbol();
symbol.Size.Width = float.Parse(node.Attributes["width"].Value);
symbol.Size.Height = float.Parse(node.Attributes["height"].Value);
int x = int.Parse(node.Attributes["x"].Value);
int y = int.Parse(node.Attributes["y"].Value);
symbol.UV = new RectangleF(x / width, y / height, symbol.Size.Width / width, symbol.Size.Height / height);
symbol.Advance = float.Parse(node.Attributes["xadvance"].Value);
font.Symbols[id] = symbol;
}
using (Stream textureStream = assembly.GetManifestResourceStream(String.Format("Profiler.DirectX.Fonts.{0}_0.png", name)))
{
font.Texture = TextureLoader.CreateTex2DFromFile(device, textureStream);
}
font.TextureView = new ShaderResourceView(device, font.Texture);
}
return font;
}
public void Dispose()
{
Utilities.Dispose(ref Texture);
Utilities.Dispose(ref TextureView);
}
}
Font SegoeUI;
public TextManager(DirectX.DirectXCanvas canvas)
{
double baseFontSize = 16.0;
int desiredFontSize = (int)(RenderSettings.dpiScaleY * baseFontSize);
int fontSize = 16;
int[] sizes = { 16, 20, 24, 28, 32 };
for (int i = 0; i < sizes.Length; ++i)
{
if (desiredFontSize < sizes[i])
break;
fontSize = sizes[i];
}
SegoeUI = Font.Create(canvas.RenderDevice, String.Format("SegoeUI_{0}_Normal", fontSize));
VertexBuffer = new DynamicBuffer<Vertex>(canvas.RenderDevice, BindFlags.VertexBuffer);
IndexBuffer = new DynamicBuffer<int>(canvas.RenderDevice, BindFlags.IndexBuffer);
TextMesh = canvas.CreateMesh(DirectXCanvas.MeshType.Text);
TextMesh.UseAlpha = true;
}
public void Draw(System.Windows.Point pos, String text, System.Windows.Media.Color color, TextAlignment alignment = TextAlignment.Left, double maxWidth = double.MaxValue)
{
Color textColor = Utils.Convert(color);
char[] str = text.ToCharArray();
switch (alignment)
{
case TextAlignment.Center:
{
double totalWidth = 0.0;
for (int i = 0; i < str.Length; ++i)
totalWidth += SegoeUI.Symbols[str[i]].Advance;
double shift = Math.Max(0.0, (maxWidth - totalWidth) * 0.5);
Vector2 origin = new Vector2((float)(pos.X + shift), (float)pos.Y);
for (int i = 0; i < str.Length; ++i)
{
Font.Symbol symbol = SegoeUI.Symbols[str[i]];
if (symbol.Size.Width > maxWidth)
break;
Draw(origin, symbol, textColor);
origin.X += symbol.Advance;
maxWidth -= symbol.Advance;
}
}
break;
case TextAlignment.Right:
{
Vector2 origin = new Vector2((float)(pos.X + maxWidth), (float)pos.Y);
for (int i = str.Length - 1; i >= 0; --i)
{
Font.Symbol symbol = SegoeUI.Symbols[str[i]];
origin.X -= symbol.Advance;
if (symbol.Size.Width > maxWidth)
break;
Draw(origin, symbol, textColor);
maxWidth -= symbol.Advance;
}
}
break;
default:
{
Vector2 origin = new Vector2((float)pos.X, (float)pos.Y);
for (int i = 0; i < str.Length; ++i)
{
Font.Symbol symbol = SegoeUI.Symbols[str[i]];
if (symbol.Size.Width > maxWidth)
break;
Draw(origin, symbol, textColor);
origin.X += symbol.Advance;
maxWidth -= symbol.Advance;
}
}
break;
}
}
void Draw(Vector2 pos, Font.Symbol symbol, Color color)
{
VertexBuffer.Add(new Vertex()
{
Position = new Vector2(pos.X, pos.Y),
UV = symbol.UV.TopLeft,
Color = color
});
VertexBuffer.Add(new Vertex()
{
Position = new Vector2(pos.X + symbol.Size.Width, pos.Y),
UV = symbol.UV.TopRight,
Color = color
});
VertexBuffer.Add(new Vertex()
{
Position = new Vector2(pos.X + symbol.Size.Width, pos.Y + symbol.Size.Height),
UV = symbol.UV.BottomRight,
Color = color
});
VertexBuffer.Add(new Vertex()
{
Position = new Vector2(pos.X, pos.Y + symbol.Size.Height),
UV = symbol.UV.BottomLeft,
Color = color
});
}
public void Render(DirectX.DirectXCanvas canvas)
{
Freeze(canvas.RenderDevice);
canvas.RenderDevice.ImmediateContext.PixelShader.SetSampler(0, canvas.TextSamplerState);
canvas.RenderDevice.ImmediateContext.PixelShader.SetShaderResource(0, SegoeUI.TextureView);
canvas.Draw(TextMesh);
}
public void Freeze(Device device)
{
TextMesh.PrimitiveCount = VertexBuffer.Count * 2 / 4;
if (IndexBuffer.Count < TextMesh.PrimitiveCount * 6)
{
IndexBuffer.Capacity = TextMesh.PrimitiveCount * 6;
while (IndexBuffer.Count < TextMesh.PrimitiveCount * 6)
{
int baseIndex = (IndexBuffer.Count * 4) / 6;
foreach (int i in DynamicMesh.BoxTriIndices)
IndexBuffer.Add(baseIndex + i);
}
IndexBuffer.Update(device);
}
VertexBuffer.Update(device);
TextMesh.VertexBuffer = VertexBuffer.Buffer;
TextMesh.IndexBuffer = IndexBuffer.Buffer;
TextMesh.VertexBufferBinding = new VertexBufferBinding(TextMesh.VertexBuffer, Utilites.SizeOf<Vertex>(), 0);
}
public void Dispose()
{
SharpDX.Utilities.Dispose(ref SegoeUI);
SharpDX.Utilities.Dispose(ref TextMesh);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace CommonHelperLibrary.WEB
{
/// <summary>
/// Author : Hans.Huang
/// Date : 2012-12-03
/// Class : HttpWebDealer
/// Discription : Helper class for dealer with the http website
/// </summary>
public class HttpWebDealer
{
protected static LoggerHelper Logger = LoggerHelper.Instance;
#region GetHtml
/// <summary>
/// Get Html text by URL
/// I can't tell the encoding of page,So give me the encodeing best
/// </summary>
/// <param name="url">URL</param>
/// <param name="headers">http request headers</param>
/// <param name="txtEncoding">The Encoding suggest of webpage</param>
/// <returns></returns>
public static string GetHtml(string url, WebHeaderCollection headers = null, Encoding txtEncoding = null)
{
var html = "";
if (string.IsNullOrWhiteSpace(url)) return html;
var response = GetResponseByUrl(url,headers);
html = HttpWebDealerBase.GetHtmlFromResponse(response, txtEncoding);
return html;
}
#endregion
#region GetJsonObject
/// <summary>
/// Get Dynamic Object (json)
/// </summary>
/// <param name="url">URL</param>
/// <param name="headers">http request headers</param>
/// <param name="txtEncoding">The Encoding suggest of response</param>
/// <returns></returns>
public static dynamic GetJsonObject(string url,WebHeaderCollection headers = null, Encoding txtEncoding = null)
{
var json = GetHtml(url, headers, txtEncoding);
var jsonSerializer = new JavaScriptSerializer();
return jsonSerializer.Deserialize<dynamic>(json);
}
#endregion
#region DownloadFile
/// <summary>
/// Get file by HttpWebRequest and save it(Just for Small files those's content length less then 65K)
/// </summary>
/// <param name="fileName">File Name to save as</param>
/// <param name="url">URL</param>
/// <param name="path">The path to save the file</param>
/// <param name="timeout">Request timeout</param>
/// <param name="headers">http request header</param>
/// <returns>Success:Ture</returns>
public static bool DownloadFile(string fileName, string url, string path, int timeout, WebHeaderCollection headers = null)
{
var response = GetResponseByUrl(url, headers, timeout);
var stream = response.GetResponseStream();
if (stream == null) return false;
using (var bReader = new BinaryReader(stream))
{
var length = Int32.Parse(response.ContentLength.ToString(CultureInfo.InvariantCulture));
var byteArr = new byte[length];
//stream.Read(byteArr, 0, length);
bReader.Read(byteArr, 0, length);
//if (File.Exists(path + fileName)) File.Delete(path + fileName);
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
var fs = File.Create(path +"\\"+ fileName);
fs.Write(byteArr, 0, length);
fs.Close();
}
return true;
}
/// <summary>
/// Get file by WebClient method
/// </summary>
/// <param name="fileName">File name to save</param>
/// <param name="url">file url to download</param>
/// <param name="path">file path to save</param>
/// <param name="monitor">Monitor action for download progress</param>
/// <returns></returns>
public static bool DownloadFile(string fileName, string url, string path,
DownloadProgressChangedEventHandler monitor = null)
{
if (string.IsNullOrWhiteSpace(url)) return false;
if (!path.EndsWith("\\")) path += "\\";
using (var wc = new WebClient())
{
//if (File.Exists(path +"\\"+ fileName)) File.Delete(path +"\\"+ fileName);
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
if (monitor != null)
wc.DownloadProgressChanged += monitor;
wc.DownloadFileAsync(new Uri(url), path + fileName);
}
return true;
}
/// <summary>
/// Download largest file from url list
/// </summary>
/// <param name="fileName">File name to save</param>
/// <param name="urls">file url list to download</param>
/// <param name="path">file path to save</param>
/// <param name="monitor">Monitor action for download progress</param>
/// <returns>File Length</returns>
public static long DownloadLargestFile(string fileName, List<string> urls, string path,
DownloadProgressChangedEventHandler monitor = null)
{
if (urls == null || urls.Count == 0) return 0;
var results = new Dictionary<string, long>();
var signals = new List<EventWaitHandle>();
var locker = new object();
foreach (var url in urls)
{
var signal = new EventWaitHandle(true, EventResetMode.ManualReset);
signals.Add(signal);
var str = url;
signal.Reset();
Task.Run(() =>
{
var rsponse = GetResponseByUrl(str, null, 3000);
if (rsponse == null) return;
lock (locker)
{
results.Add(str, rsponse.ContentLength);
}
signal.Set();
});
}
signals.ForEach(s => s.WaitOne(3000));
var largest = new KeyValuePair<string, long>(string.Empty, 0);
foreach (var res in results)
{
if (res.Value > largest.Value) largest = res;
}
return DownloadFile(fileName, largest.Key, path, monitor) ? largest.Value : 0;
}
#endregion
#region GetResponseByUrl
/// <summary>
/// Get response by url
/// </summary>
/// <param name="url">URL</param>
/// <param name="headers">Request headers</param>
/// <param name="requestTimeout">Request timeout(Set to 0 for no limit)</param>
/// <returns></returns>
public static HttpWebResponse GetResponseByUrl(string url, WebHeaderCollection headers = null, int requestTimeout = 0)
{
HttpWebResponse response = null;
var request = (HttpWebRequest)WebRequest.Create(url);
if (requestTimeout > 0) request.Timeout = requestTimeout;
string postData;
HttpWebDealerBase.CorrectHeader(request, headers, out postData);
for (var i = 0; i < 3; i++)
{
try
{
HttpWebDealerBase.TryPostData(request, postData);
response = (HttpWebResponse)request.GetResponse();
return response;
}
catch (Exception e)
{
Logger.Msg("Error", url);
Logger.Exception(e);
}
Thread.Sleep(200);
}
return response;
}
#endregion
/// <summary>
/// Detects the byte order mark of a file and returns an appropriate encoding for the file.
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static Encoding GetEncoding(Stream stream)
{
// Use Default of Encoding.Default (Ansi CodePage)
var enc = Encoding.Default;
// Detect byte order mark if any - otherwise assume default
//var simple = new MemoryStream();
//stream.CopyTo(simple, 5);
var buffer = new byte[5];
stream.Read(buffer, 0, 5);
if (buffer[0] == 0xef && buffer[1] == 0xbb && buffer[2] == 0xbf)
enc = Encoding.UTF8;
else if (buffer[0] == 0xfe && buffer[1] == 0xff)
enc = Encoding.Unicode;
else if (buffer[0] == 0 && buffer[1] == 0 && buffer[2] == 0xfe && buffer[3] == 0xff)
enc = Encoding.UTF32;
else if (buffer[0] == 0x2b && buffer[1] == 0x2f && buffer[2] == 0x76)
enc = Encoding.UTF7;
//simple.Close();
return enc;
}
}
}
|
using System;
using System.Collections.Generic;
using Roguelike.Core.Elements.Inventory;
using Roguelike.Entities;
using RLNET;
namespace Roguelike.Systems {
public class InventorySystem {
private Player player;
public InventorySystem() {
player = Game.Player;
}
void SelectEquipment(Equipment pressedOn) {
if (pressedOn.GetType() == typeof(HeadEquipment)) {
SelectHeadEquipment((HeadEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(BodyEquipment)) {
SelectBodyEquipment((BodyEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(ArmEquipment)) {
SelectArmEquipment((ArmEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(LegEquipment)) {
SelectLegEquipment((LegEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(HandEquipment)) {
SelectHandEquipment((HandEquipment)pressedOn);
} else if (pressedOn.GetType() == typeof(FeetEquipment)) {
SelectFeetEquipment((FeetEquipment)pressedOn);
}
Game.Render();
}
void DiscardEquipment(Equipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
Game.Render();
}
void SelectHeadEquipment(HeadEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if(player.Head != null && player.Head != HeadEquipment.None()) {
player.AddEquipment(player.Head);
}
player.Head = pressedOn;
}
void SelectBodyEquipment(BodyEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Body != null && player.Body != BodyEquipment.None()) {
player.AddEquipment(player.Body);
}
player.Body = pressedOn;
}
void SelectArmEquipment(ArmEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Arms != null && player.Arms != ArmEquipment.None()) {
player.AddEquipment(player.Arms);
}
player.Arms = pressedOn;
}
void SelectLegEquipment(LegEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Legs != null && player.Legs != LegEquipment.None()) {
player.AddEquipment(player.Legs);
}
player.Legs = pressedOn;
}
void SelectHandEquipment(HandEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Hands != null && player.Hands != HandEquipment.None()) {
player.AddEquipment(player.Hands);
}
player.Hands = pressedOn;
}
void SelectFeetEquipment(FeetEquipment pressedOn) {
player.equipmentInInventory.Remove(pressedOn);
if (player.Feet != null && player.Feet != FeetEquipment.None()) {
player.AddEquipment(player.Feet);
}
player.Feet = pressedOn;
}
public Equipment EquipArmourFromInventory(int x, int y) {
for (int i = 0; i < player.equipmentInInventory.Count; i++) {
int lengthOfString = player.equipmentInInventory[i].Name.Length;
int numberOfLines = 0;
if(lengthOfString >= 20) {
numberOfLines = 2;
} else {
numberOfLines = 1;
}
int xStartPosition = 0;
int yPosition = (3 * i) + 3;
if(i < 6) {
xStartPosition = 22;
} else {
yPosition = (3 * i) - 15;
xStartPosition = 44;
}
if(numberOfLines == 1) {
if(x >= xStartPosition && x < xStartPosition + lengthOfString && y == yPosition) {
SelectEquipment(player.equipmentInInventory[i]);
}
}else if(numberOfLines == 2) {
string topString = TopLine(player.equipmentInInventory[i].Name);
string bottomString = BottomLine(player.equipmentInInventory[i].Name, topString);
if(y == yPosition) {
if(x >= xStartPosition && x < xStartPosition + topString.Length - 1) {
SelectEquipment(player.equipmentInInventory[i]);
}
} else if(y == yPosition + 1) {
if (x >= xStartPosition && x < xStartPosition + bottomString.Length) {
SelectEquipment(player.equipmentInInventory[i]);
}
}
}
}
return null;
}
public void DiscardArmourFromInventory(int x, int y) {
for (int i = 0; i < player.equipmentInInventory.Count; i++) {
int lengthOfString = player.equipmentInInventory[i].Name.Length;
int numberOfLines = 0;
if (lengthOfString >= 20) {
numberOfLines = 2;
} else {
numberOfLines = 1;
}
int xStartPosition = 0;
int yPosition = (3 * i) + 3;
if (i < 6) {
xStartPosition = 22;
} else {
yPosition = (3 * i) - 15;
xStartPosition = 44;
}
if (numberOfLines == 1) {
if (x >= xStartPosition && x < xStartPosition + lengthOfString && y == yPosition) {
DiscardEquipment(player.equipmentInInventory[i]);
}
} else if (numberOfLines == 2) {
string topString = TopLine(player.equipmentInInventory[i].Name);
string bottomString = BottomLine(player.equipmentInInventory[i].Name, topString);
if (y == yPosition) {
if (x >= xStartPosition && x < xStartPosition + topString.Length - 1) {
DiscardEquipment(player.equipmentInInventory[i]);
}
} else if (y == yPosition + 1) {
if (x >= xStartPosition && x < xStartPosition + bottomString.Length) {
DiscardEquipment(player.equipmentInInventory[i]);
}
}
}
}
}
public void RemoveEquipment(int x, int y) {
if (y == 3) {
if (x >= 1 && x <= 14) {
HeadEquipment toRemove = player.Head;
player.Head = HeadEquipment.None();
player.equipmentInInventory.Add(toRemove);
} else if (x > 14 && x < 28) {
LegEquipment toRemove = player.Legs;
player.Legs = LegEquipment.None();
player.equipmentInInventory.Add(toRemove);
}
} else if (y == 5) {
if (x >= 1 && x <= 14) {
BodyEquipment toRemove = player.Body;
player.Body = BodyEquipment.None();
player.equipmentInInventory.Add(toRemove);
} else if (x > 14 && x < 28) {
HandEquipment toRemove = player.Hands;
player.Hands = HandEquipment.None();
player.equipmentInInventory.Add(toRemove);
}
} else if (y == 7) {
if (x >= 1 && x <= 14) {
ArmEquipment toRemove = player.Arms;
player.Arms = ArmEquipment.None();
player.equipmentInInventory.Add(toRemove);
} else if (x > 14 && x < 28) {
FeetEquipment toRemove = player.Feet;
player.Feet = FeetEquipment.None();
player.equipmentInInventory.Add(toRemove);
}
}
Game.Render();
}
public Equipment RemoveCurrentArmour(int x, int y) {
if(y == 3 || y == 4) {
ClickedOnHead(x, y);
} else if(y == 6 || y == 7) {
ClickedOnBody(x, y);
} else if (y == 9 || y == 10) {
ClickedOnArms(x, y);
} else if (y == 12 || y == 13) {
ClickedOnLegs(x, y);
} else if (y == 15 || y == 16) {
ClickedOnHands(x, y);
} else if (y == 18 || y == 19) {
ClickedOnFeet(x, y);
}
return null;
}
private void ClickedOnHead(int x, int y) {
string topLine = TopLine("Head: " + player.Head.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Head: " + player.Head.Name, topLine);
} catch {
}
if (y == 4) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Head);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Head);
}
}
}
public void ClickedOnBody(int x, int y) {
string topLine = TopLine("Body: " + player.Body.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Body: " + player.Body.Name, topLine);
} catch {
}
if (y == 7) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Body);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Body);
}
}
}
public void ClickedOnArms(int x, int y) {
string topLine = TopLine("Arms: " + player.Arms.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Arms: " + player.Arms.Name, topLine);
} catch {
}
if (y == 10) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Arms);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Arms);
}
}
}
public void ClickedOnLegs(int x, int y) {
string topLine = TopLine("Legs: " + player.Legs.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Legs: " + player.Legs.Name, topLine);
} catch {
}
if (y == 13) {
if (bottomLine != "") {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Legs);
}
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Legs);
}
}
}
public void ClickedOnHands(int x, int y) {
string topLine = TopLine("Hands: " + player.Hands.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Hands: " + player.Hands.Name, topLine);
} catch {
}
if (y == 16) {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Hands);
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Hands);
}
}
}
private void ClickedOnFeet(int x, int y) {
string topLine = TopLine("Feet: " + player.Feet.Name, 20);
string bottomLine = "";
try {
bottomLine = BottomLine("Feet: " + player.Feet.Name, topLine);
} catch {
}
if (y == 19) {
if (DidClickOnString(x, y, true, topLine, bottomLine)) {
UnequipArmour(player.Feet);
}
} else {
if (DidClickOnString(x, y, false, topLine, bottomLine)) {
UnequipArmour(player.Feet);
}
}
}
public bool DidClickOnString(int x, int y, bool secondLine,string topLine, string bottomLine = "") {
int xStartPosition = 1;
int topXEndPosition = xStartPosition + topLine.Length;
int bottomXEndPosition = xStartPosition + bottomLine.Length;
if (bottomLine != "") {
if (secondLine) {
if (x >= xStartPosition && x <= bottomXEndPosition) {
return true;
} else {
return false;
}
} else {
if (x >= xStartPosition && x <= topXEndPosition) {
return true;
} else {
return false;
}
}
} else {
if(x >= xStartPosition && x <= topXEndPosition) {
return true;
} else {
return false;
}
}
}
private void UnequipArmour(Equipment toUnequip) {
if (toUnequip.GetType() == typeof(HeadEquipment) && toUnequip != HeadEquipment.None()) {
UnSelectHeadEquipment((HeadEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(BodyEquipment) && toUnequip != BodyEquipment.None()) {
UnSelectBodyEquipment((BodyEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(ArmEquipment) && toUnequip != ArmEquipment.None()) {
UnSelectArmEquipment((ArmEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(LegEquipment) && toUnequip != LegEquipment.None()) {
UnSelectLegEquipment((LegEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(HandEquipment) && toUnequip != HandEquipment.None()) {
UnSelectHandEquipment((HandEquipment)toUnequip);
} else if (toUnequip.GetType() == typeof(FeetEquipment) && toUnequip != FeetEquipment.None()) {
UnSelectFeetEquipment((FeetEquipment)toUnequip);
}
Game.Render();
}
private void UnSelectHeadEquipment(HeadEquipment toUnequip) {
if(player.equipmentInInventory.Count < 12) {
player.Head = HeadEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectBodyEquipment(BodyEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Body = BodyEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectArmEquipment(ArmEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Arms = ArmEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectLegEquipment(LegEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Legs = LegEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectHandEquipment(HandEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Hands = HandEquipment.None();
player.AddEquipment(toUnequip);
}
}
private void UnSelectFeetEquipment(FeetEquipment toUnequip) {
if (player.equipmentInInventory.Count < 12) {
player.Feet = FeetEquipment.None();
player.AddEquipment(toUnequip);
}
}
private string TopLine(string totalString, int wrapLength = 18) {
List<string> wordsInString = new List<string>();
string currentString = "";
for (int i = 0; i < totalString.Length; i++) {
char character = totalString[i];
if (character == ' ') {
wordsInString.Add(currentString);
currentString = "";
}else if(i == totalString.Length - 1) {
currentString += character;
wordsInString.Add(currentString);
currentString = "";
} else {
currentString += character;
}
}
int lengthSoFar = 0;
string topLine = "";
for (int i = 0; i < wordsInString.Count; i++) {
if (lengthSoFar + wordsInString[i].Length >= wrapLength) {
break;
}
lengthSoFar += wordsInString[i].Length;
topLine += wordsInString[i];
topLine += " ";
}
return topLine;
}
private string BottomLine(string totalString, string topLine) {
string bottom = totalString;
bottom = bottom.Substring(topLine.Length);
return bottom;
}
}
}
|
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace PoshGit2.TabCompletion
{
public class TabCompletionTests
{
private readonly ITestOutputHelper _log;
public TabCompletionTests(ITestOutputHelper log)
{
_log = log;
}
[InlineData("gi")]
[InlineData("git")]
[InlineData("git.")]
[InlineData("git.exe")]
[Theory]
public async Task GitCommand(string cmd)
{
var repo = Substitute.For<IRepositoryStatus>();
var completer = new TabCompleter(Task.FromResult(repo));
var result = await completer.CompleteAsync(cmd, CancellationToken.None);
Assert.True(result.IsFailure);
}
[InlineData("git ", new string[] { "clone", "init" })]
[Theory]
public async Task NullStatus(string command, string[] expected)
{
var completer = new TabCompleter(Task.FromResult<IRepositoryStatus>(null));
var fullResult = await completer.CompleteAsync(command, CancellationToken.None);
var result = GetResult(fullResult);
Assert.Equal(result, expected.OrderBy(o => o, StringComparer.Ordinal));
}
[InlineData("git add ", new string[] { })]
[InlineData("git rm ", new string[] { })]
[Theory]
public async Task EmptyStatus(string command, string[] expected)
{
var repo = Substitute.For<IRepositoryStatus>();
var completer = new TabCompleter(Task.FromResult(repo));
var fullResult = await completer.CompleteAsync(command, CancellationToken.None);
var result = GetResult(fullResult);
Assert.Equal(result, expected.OrderBy(o => o, StringComparer.Ordinal));
}
[InlineData("git ", "stash")]
[InlineData("git s", "stash")]
[InlineData("git ", "push")]
[InlineData("git p", "push")]
[InlineData("git ", "pull")]
[InlineData("git p", "pull")]
[InlineData("git ", "bisect")]
[InlineData("git bis", "bisect")]
[InlineData("git ", "branch")]
[InlineData("git br", "branch")]
[InlineData("git ", "add")]
[InlineData("git a", "add")]
[InlineData("git ", "rm")]
[InlineData("git r", "rm")]
[InlineData("git ", "merge")]
[InlineData("git m", "merge")]
[InlineData("git ", "mergetool")]
[InlineData("git m", "mergetool")]
[Theory]
public async Task ResultContains(string command, string expected)
{
var completer = CreateTabCompleter();
var fullResult = await completer.CompleteAsync(command, CancellationToken.None);
var result = GetResult(fullResult);
Assert.Contains(expected, result);
}
// Verify command completion
[InlineData("git ", new[] { "add", "am", "annotate", "archive", "bisect", "blame", "branch", "bundle", "checkout", "cherry", "cherry-pick", "citool", "clean", "clone", "commit", "config", "describe", "diff", "difftool", "fetch", "format-patch", "gc", "grep", "gui", "help", "init", "instaweb", "log", "merge", "mergetool", "mv", "notes", "prune", "pull", "push", "rebase", "reflog", "remote", "rerere", "reset", "revert", "rm", "shortlog", "show", "stash", "status", "submodule", "svn", "tag", "whatchanged" })]
[InlineData("git.exe ", new[] { "add", "am", "annotate", "archive", "bisect", "blame", "branch", "bundle", "checkout", "cherry", "cherry-pick", "citool", "clean", "clone", "commit", "config", "describe", "diff", "difftool", "fetch", "format-patch", "gc", "grep", "gui", "help", "init", "instaweb", "log", "merge", "mergetool", "mv", "notes", "prune", "pull", "push", "rebase", "reflog", "remote", "rerere", "reset", "revert", "rm", "shortlog", "show", "stash", "status", "submodule", "svn", "tag", "whatchanged" })]
// git add
[InlineData("git add ", new[] { "working-duplicate", "working-modified", "working-added", "working-unmerged" })]
[InlineData("git add working-m", new[] { "working-modified" })]
// git rm
[InlineData("git rm ", new[] { "working-deleted", "working-duplicate" })]
[InlineData("git rm working-a", new string[] { })]
[InlineData("git rm working-d", new string[] { "working-deleted", "working-duplicate" })]
// git bisect
[InlineData("git bisect ", new[] { "start", "bad", "good", "skip", "reset", "visualize", "replay", "log", "run" })]
[InlineData("git bisect s", new[] { "start", "skip" })]
[InlineData("git bisect bad ", new string[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git bisect good ", new string[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git bisect reset ", new string[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git bisect skip ", new string[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git bisect bad f", new string[] { "feature1", "feature2" })]
[InlineData("git bisect good f", new string[] { "feature1", "feature2" })]
[InlineData("git bisect reset f", new string[] { "feature1", "feature2" })]
[InlineData("git bisect skip f", new string[] { "feature1", "feature2" })]
[InlineData("git bisect bad g", new string[] { })]
[InlineData("git bisect good g", new string[] { })]
[InlineData("git bisect reset g", new string[] { })]
[InlineData("git bisect skip g", new string[] { })]
[InlineData("git bisect skip H", new string[] { "HEAD" })]
// git notes
[InlineData("git notes ", new[] { "edit", "show" })]
[InlineData("git notes e", new[] { "edit" })]
// git reflog
[InlineData("git reflog ", new[] { "expire", "delete", "show" })]
[InlineData("git reflog e", new[] { "expire" })]
// git branch
[InlineData("git branch -d ", new string[] { "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git branch -D ", new string[] { "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git branch -m ", new string[] { "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git branch -M ", new string[] { "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git branch -d f", new string[] { "feature1", "feature2" })]
[InlineData("git branch -D f", new string[] { "feature1", "feature2" })]
[InlineData("git branch -m f", new string[] { "feature1", "feature2" })]
[InlineData("git branch -M f", new string[] { "feature1", "feature2" })]
[InlineData("git branch -d g", new string[] { })]
[InlineData("git branch -D g", new string[] { })]
[InlineData("git branch -m g", new string[] { })]
[InlineData("git branch -M g", new string[] { })]
[InlineData("git branch newBranch ", new string[] { "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git branch newBranch f", new string[] { "feature1", "feature2" })]
[InlineData("git branch newBranch g", new string[] { })]
// git push
[InlineData("git push ", new string[] { "origin", "other" })]
[InlineData("git push oth", new string[] { "other" })]
[InlineData("git push origin ", new string[] { "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git push origin fe", new string[] { "feature1", "feature2" })]
[InlineData("git push origin :", new string[] { ":remotefeature", ":cutfeature" })]
[InlineData("git push origin :re", new string[] { ":remotefeature" })]
// git pull
[InlineData("git pull ", new string[] { "origin", "other" })]
[InlineData("git pull oth", new string[] { "other" })]
[InlineData("git pull origin ", new string[] { "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git pull origin fe", new string[] { "feature1", "feature2" })]
// git fetch
[InlineData("git fetch ", new string[] { "origin", "other" })]
[InlineData("git fetch oth", new string[] { "other" })]
// git submodule
[InlineData("git submodule ", new string[] { "add", "status", "init", "update", "summary", "foreach", "sync" })]
[InlineData("git submodule s", new string[] { "status", "summary", "sync" })]
// git svn
[InlineData("git svn ", new string[] { "init", "fetch", "clone", "rebase", "dcommit", "branch", "tag", "log", "blame", "find-rev", "set-tree", "create-ignore", "show-ignore", "mkdirs", "commit-diff", "info", "proplist", "propget", "show-externals", "gc", "reset" })]
[InlineData("git svn f", new string[] { "fetch", "find-rev" })]
// git stash
[InlineData("git stash ", new string[] { "list", "save", "show", "drop", "pop", "apply", "branch", "clear", "create" })]
[InlineData("git stash s", new string[] { "save", "show" })]
[InlineData("git stash show ", new string[] { "stash", "wip" })]
[InlineData("git stash show w", new string[] { "wip" })]
[InlineData("git stash show d", new string[] { })]
[InlineData("git stash apply ", new string[] { "stash", "wip" })]
[InlineData("git stash apply w", new string[] { "wip" })]
[InlineData("git stash apply d", new string[] { })]
[InlineData("git stash drop ", new string[] { "stash", "wip" })]
[InlineData("git stash drop w", new string[] { "wip" })]
[InlineData("git stash drop d", new string[] { })]
[InlineData("git stash pop ", new string[] { "stash", "wip" })]
[InlineData("git stash pop w", new string[] { "wip" })]
[InlineData("git stash pop d", new string[] { })]
[InlineData("git stash branch ", new string[] { "stash", "wip" })]
[InlineData("git stash branch w", new string[] { "wip" })]
[InlineData("git stash branch d", new string[] { })]
// Tests for commit
[InlineData("git commit -C ", new string[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git commit -C O", new string[] { "ORIG_HEAD" })]
[InlineData("git commit -C o", new string[] { "origin/cutfeature", "origin/remotefeature" })]
// git remote
[InlineData("git remote ", new[] { "add", "rename", "rm", "set-head", "show", "prune", "update" })]
[InlineData("git remote r", new[] { "rename", "rm" })]
[InlineData("git remote rename ", new string[] { "origin", "other" })]
[InlineData("git remote rename or", new string[] { "origin" })]
[InlineData("git remote rm ", new string[] { "origin", "other" })]
[InlineData("git remote rm or", new string[] { "origin" })]
[InlineData("git remote set-head ", new string[] { "origin", "other" })]
[InlineData("git remote set-head or", new string[] { "origin" })]
[InlineData("git remote set-branches ", new string[] { "origin", "other" })]
[InlineData("git remote set-branches or", new string[] { "origin" })]
[InlineData("git remote set-url ", new string[] { "origin", "other" })]
[InlineData("git remote set-url or", new string[] { "origin" })]
[InlineData("git remote show ", new string[] { "origin", "other" })]
[InlineData("git remote show or", new string[] { "origin", })]
[InlineData("git remote prune ", new string[] { "origin", "other" })]
[InlineData("git remote prune or", new string[] { "origin" })]
// git help <cmd>
[InlineData("git help ", new[] { "add", "am", "annotate", "archive", "bisect", "blame", "branch", "bundle", "checkout", "cherry", "cherry-pick", "citool", "clean", "clone", "commit", "config", "describe", "diff", "difftool", "fetch", "format-patch", "gc", "grep", "gui", "help", "init", "instaweb", "log", "merge", "mergetool", "mv", "notes", "prune", "pull", "push", "rebase", "reflog", "remote", "rerere", "reset", "revert", "rm", "shortlog", "show", "stash", "status", "submodule", "svn", "tag", "whatchanged" })]
[InlineData("git help ch", new[] { "checkout", "cherry", "cherry-pick" })]
// git checkout -- <files>
[InlineData("git checkout -- ", new[] { "working-deleted", "working-duplicate", "working-modified", "working-unmerged" })]
[InlineData("git checkout -- working-d", new[] { "working-deleted", "working-duplicate" })]
// git merge|mergetool <files>
// TODO: Enable for merge state
//[InlineData("git merge ", new[] { "working-unmerged", "working-duplicate" })]
//[InlineData("git merge working-u", new[] { "working-unmerged" })]
//[InlineData("git merge j", new string[] { })]
//[InlineData("git mergetool ", new[] { "working-unmerged", "working-duplicate" })]
//[InlineData("git mergetool working-u", new[] { "working-unmerged" })]
//[InlineData("git mergetool j", new string[] { })]
// git checkout <branch>
[InlineData("git checkout ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git cherry-pick <branch>
[InlineData("git cherry ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git cherry-pick <branch>
[InlineData("git cherry-pick ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git diff <branch>
[InlineData("git diff ", new[] { "index-modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git diff --cached ", new[] { "working-modified", "working-duplicate", "working-unmerged", "index-modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git diff --staged ", new[] { "index-modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git difftool <branch>
[InlineData("git difftool ", new[] { "index-modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git difftool --cached ", new[] { "working-modified", "working-duplicate", "working-unmerged", "index-modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git difftool --staged ", new[] { "index-modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git log <branch>
[InlineData("git log ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git merge <branch>
[InlineData("git merge ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git rebase <branch>
[InlineData("git rebase ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git reflog <branch>
[InlineData("git reflog show ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git reset <branch>
[InlineData("git reset ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git reset HEAD <file>
[InlineData("git reset HEAD ", new[] { "index-added", "index-deleted", "index-modified", "index-unmerged" })]
[InlineData("git reset HEAD index-a", new[] { "index-added" })]
// git revert <branch>
[InlineData("git revert ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git show<branch>
[InlineData("git show ", new[] { "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[Theory]
public async Task CheckCompletion(string cmd, string[] expected)
{
var completer = CreateTabCompleter();
await CompareAsync(completer, cmd, expected.OrderBy(o => o, StringComparer.Ordinal));
}
// git add
[InlineData("git add ", new[] { "working duplicate", "working modified", "working added", "working unmerged" })]
[InlineData("git add \"working m", new[] { "working modified" })]
[InlineData("git add \'working m", new[] { "working modified" })]
// git rm
[InlineData("git rm ", new[] { "working deleted", "working duplicate" })]
[InlineData("git rm \"working d", new string[] { "working deleted", "working duplicate" })]
[InlineData("git rm \'working d", new string[] { "working deleted", "working duplicate" })]
// git checkout -- <files>
[InlineData("git checkout -- ", new[] { "working deleted", "working duplicate", "working modified", "working unmerged" })]
[InlineData("git checkout -- \"wor", new[] { "working deleted", "working duplicate", "working modified", "working unmerged" })]
[InlineData("git checkout -- \"working d", new[] { "working deleted", "working duplicate" })]
[InlineData("git checkout -- \'working d", new[] { "working deleted", "working duplicate" })]
// git merge|mergetool <files>
// TODO: Enable for merge state
//[InlineData("git merge ", new[] { "working unmerged", "working duplicate" })]
//[InlineData("git merge working u", new[] { "working unmerged" })]
//[InlineData("git merge j", new string[] { })]
//[InlineData("git mergetool ", new[] { "working unmerged", "working duplicate" })]
//[InlineData("git mergetool working u", new[] { "working unmerged" })]
//[InlineData("git mergetool j", new string[] { })]
// git diff <branch>
[InlineData("git diff ", new[] { "index modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git diff --cached ", new[] { "working modified", "working duplicate", "working unmerged", "index modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git diff --staged ", new[] { "index modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git difftool <branch>
[InlineData("git difftool ", new[] { "index modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git difftool --cached ", new[] { "working modified", "working duplicate", "working unmerged", "index modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
[InlineData("git difftool --staged ", new[] { "index modified", "FETCH_HEAD", "HEAD", "MERGE_HEAD", "ORIG_HEAD", "feature1", "feature2", "master", "origin/cutfeature", "origin/remotefeature" })]
// git reset HEAD <file>
[InlineData("git reset HEAD ", new[] { "index added", "index deleted", "index modified", "index unmerged" })]
[InlineData("git reset HEAD \"index a", new[] { "index added" })]
[InlineData("git reset HEAD \'index a", new[] { "index added" })]
[Theory]
public async Task CheckCompletionWithQuotations(string cmd, string[] initialExpected)
{
const string quot = "\"";
var completer = CreateTabCompleter(" ");
var expected = initialExpected
.OrderBy(o => o, StringComparer.Ordinal)
.Select(o => o.Contains(" ") ? $"{quot}{o}{quot}" : o);
await CompareAsync(completer, cmd, expected);
}
private async Task CompareAsync(ITabCompleter completer, string cmd, IEnumerable<string> expected)
{
var fullResult = await completer.CompleteAsync(cmd, CancellationToken.None);
var result = GetResult(fullResult);
_log.WriteLine("Expected output:");
_log.WriteLine(string.Join(Environment.NewLine, expected));
_log.WriteLine(string.Empty);
_log.WriteLine("Actual output:");
_log.WriteLine(string.Join(Environment.NewLine, result));
Assert.Equal(expected, result);
}
private static ITabCompleter CreateTabCompleter(string join = "-")
{
var status = Substitute.For<IRepositoryStatus>();
var working = new ChangedItemsCollection
{
Added = new[] { $"working{join}added", $"working{join}duplicate" },
Deleted = new[] { $"working{join}deleted", $"working{join}duplicate" },
Modified = new[] { $"working{join}modified", $"working{join}duplicate" },
Unmerged = new[] { $"working{join}unmerged", $"working{join}duplicate" }
};
var index = new ChangedItemsCollection
{
Added = new[] { $"index{join}added" },
Deleted = new[] { $"index{join}deleted" },
Modified = new[] { $"index{join}modified" },
Unmerged = new[] { $"index{join}unmerged" }
};
status.Index.Returns(index);
status.Working.Returns(working);
status.LocalBranches.Returns(new[] { "master", "feature1", "feature2" });
status.Remotes.Returns(new[] { "origin", "other" });
status.RemoteBranches.Returns(new[] { "origin/remotefeature", "origin/cutfeature" });
status.Stashes.Returns(new[] { "stash", "wip" });
return new TabCompleter(Task.FromResult(status));
}
private IEnumerable<string> GetResult(TabCompletionResult fullResult)
{
Assert.True(fullResult.IsSuccess);
return (fullResult as TabCompletionResult.Success).Item;
}
}
}
|
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 System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace TimeOut
{
public partial class partido : Form
{
Team local; // Equipo local
Team visitor; // Equipo visitante
List<Registro> minuteToMinute = new List<Registro>();
Counter count = new Counter();
// Constante que guarda la cantidad limite
// de faltas permitidas previo a la expulsión
const int maxFaltas = 6;
/*
* Hay dos largos procesos en un partido,
* suceden cuando hay Falta o cuando hay Balon Afuera.
*/
bool procesoFalta = false;
bool procesoBalonAfuera = false;
bool localTeamShoot = false;
// Cantidad de tiros libres a tirar tras la falta
int tirosLibresDisponibles = 0;
// This will be checked in the close event,
// avoiding unnintentional actions and lose of data.
bool closeWindow = false;
// Clase para guardar el registro completo del partido
Match partidoJugado;
// Archivo para guardar el registro del partido
string archivoPartidos = "";
public string ArchivoPartidos
{
get { return archivoPartidos; }
set { archivoPartidos = value; }
}
/// <summary>
/// El constructor de la clase.
/// </summary>
/// <param name="a">Equipo local</param>
/// <param name="b">Equipo visitante</param>
public partido(Team a, Team b)
{
InitializeComponent();
local = a;
visitor = b;
if (a != null && b != null) {
actualizarListbox();
this.label_tituloLocal.Text = local.Name;
this.label_tituloVisitante.Text = visitor.Name;
this.label_LTO_restante.Text = Team.TOmax.ToString();
this.label_VTO_restante.Text = Team.TOmax.ToString();
}
}
public void actualizarListbox()
{
cargarTitulares();
cargarVisitantes();
}
void cargarTitulares()
{
listBox_LocalRoster.Items.Clear();
comboBox_LocalSubs.Items.Clear();
foreach (Player p in this.local.Players) {
if (p.Starter)
listBox_LocalRoster.Items.Add(p);
else
comboBox_LocalSubs.Items.Add(p);
}
listBox_LocalRoster.DisplayMember = "CompleteName";
comboBox_LocalSubs.DisplayMember = "CompleteName";
}
void cargarVisitantes()
{
listBox_VisitorRoster.Items.Clear();
comboBox_VisitorSubs.Items.Clear();
foreach (Player p in this.visitor.Players) {
if (p.Starter)
listBox_VisitorRoster.Items.Add(p);
else
comboBox_VisitorSubs.Items.Add(p);
}
listBox_VisitorRoster.DisplayMember = "CompleteName";
comboBox_VisitorSubs.DisplayMember = "CompleteName";
}
/// <summary>
/// Agrega un partido en una lista generica.
/// </summary>
/// <param name="equipo">Partido que sera agregado a la lista.</param>
/// <param name="listaEquipos">Lista que tiene el resto de los partidos</param>
/// <returns>La misma lista con el partido agregado</returns>
List<Match> addMatchToList(Match partido, List<Match> listaPartidos)
{
if (listaPartidos == null)
listaPartidos = new List<Match>();
listaPartidos.Add(partido);
return listaPartidos;
}
/// <summary>
/// Guarda el partido y su información en el archivo
/// </summary>
void guardarPartidoEnArchivo()
{
// Load previous matchs from file
List<Match> listaDePartidos = Main.CargarPartidos();
// Add the new match to the list
listaDePartidos = addMatchToList(this.partidoJugado, listaDePartidos);
// Store the updated list to the file
StreamWriter flujo = new StreamWriter(this.archivoPartidos);
XmlSerializer serial = new XmlSerializer(typeof(List<Match>));
serial.Serialize(flujo, listaDePartidos);
flujo.Close();
}
/// <summary>
/// Guarda las estadísticas recogidas durante el partido.
/// </summary>
void guardarInformación()
{
// Crea la lista
this.partidoJugado = new Match();
// Add match's metadata
partidoJugado.Fecha = DateTime.Now;
partidoJugado.EquipoLocal = local.Name;
partidoJugado.EquipoVisitante = visitor.Name;
// Agrega los nombres de TODOS los jugadores
// y sus respectivas estadísticas
foreach(Player p in local.Players)
{
partidoJugado.JugadoresLocales.Add(p.CompleteName);
// Agrega las estadísticas sumandolas a las actuales
partidoJugado.EstadisticasLocal.Asistencias += p.AsistenciasLogradas;
partidoJugado.EstadisticasLocal.SimplesEncestados += p.TirosLibresAnotados;
partidoJugado.EstadisticasLocal.SimplesFallidos += p.TirosLibresFallados;
partidoJugado.EstadisticasLocal.DoblesEncestados += p.PuntosDoblesAnotados;
partidoJugado.EstadisticasLocal.DoblesFallidos += p.PuntosDoblesFallados;
partidoJugado.EstadisticasLocal.TriplesEncestados += p.PuntosTriplesAnotados;
partidoJugado.EstadisticasLocal.TriplesFallidos += p.PuntosTriplesFallados;
partidoJugado.EstadisticasLocal.RebotesDefensivos += p.RebotesDefensivos;
partidoJugado.EstadisticasLocal.RebotesOfensivos += p.RebotesOfensivos;
partidoJugado.EstadisticasLocal.Faltas += p.FaltasCometidas;
}
foreach(Player p in visitor.Players)
{
partidoJugado.JugadoresVisitantes.Add(p.CompleteName);
// Agrega las estadísticas sumandolas a las actuales
partidoJugado.EstadisticasVisitante.Asistencias += p.AsistenciasLogradas;
partidoJugado.EstadisticasVisitante.SimplesEncestados += p.TirosLibresAnotados;
partidoJugado.EstadisticasVisitante.SimplesFallidos += p.TirosLibresFallados;
partidoJugado.EstadisticasVisitante.DoblesEncestados += p.PuntosDoblesAnotados;
partidoJugado.EstadisticasVisitante.DoblesFallidos += p.PuntosDoblesFallados;
partidoJugado.EstadisticasVisitante.TriplesEncestados += p.PuntosTriplesAnotados;
partidoJugado.EstadisticasVisitante.TriplesFallidos += p.PuntosTriplesFallados;
partidoJugado.EstadisticasVisitante.RebotesDefensivos += p.RebotesDefensivos;
partidoJugado.EstadisticasVisitante.RebotesOfensivos += p.RebotesOfensivos;
partidoJugado.EstadisticasVisitante.Faltas += p.FaltasCometidas;
}
guardarPartidoEnArchivo();
}
/// <summary>
/// Activa el botón de Comienzo del partido
/// </summary>
void activarContinuacion()
{
timer1.Stop();
button1.Text = "Comenzar";
button1.Enabled = true;
this.button1.BackColor = Color.DeepSkyBlue;
}
/// <summary>
/// Congela/detiene el reloj del partido y desactiva el botón de Comienzo
/// </summary>
void congelarContinuacion()
{
timer1.Stop();
button1.Text = "Parado";
button1.Enabled = false;
this.button1.BackColor = Color.Red;
}
/// <summary>
/// Pone el reloj a correr y desactiva el botón
/// </summary>
void correrContinuacion()
{
timer1.Enabled = true;
button1.Text = "Pausar";
button1.Enabled = true;
this.button1.BackColor = Color.Red;
}
/// <summary>
/// Evento llamado cuando finaliza el encuentro.
/// </summary>
void finishMatch()
{
timer1.Stop();
button1.Text = "Finalizado";
button1.Enabled = false;
button1.BackColor = Color.Black;
// Almacena la información recolectada del encuentro
guardarInformación();
// Display a minute-to-minute chart
ShowEvents nuevo = new ShowEvents(this.minuteToMinute);
nuevo.ShowDialog();
// Desactiva la pregunta al salir
closeWindow = true;
this.Close();
}
/// <summary>
/// Cambia el contexto de la ventana deacuerdo al momento correspondiente
/// </summary>
void finalizarCuarto()
{
count.resetCounter();
activarContinuacion();
// Restablece los tiempos muertos
this.local.restartTO();
this.visitor.restartTO();
// Desactiva botones no disponibles
desactivarCambio();
desactivarTO();
desactivarPuntos();
desactivarFalta();
desactivarPerdida();
desactivarRebotes();
if (this.lblCuarto.Text[0] == '1')
this.lblCuarto.Text = "2do Cuarto";
else if (this.lblCuarto.Text[0] == '2')
this.lblCuarto.Text = "3er Cuarto";
else if (this.lblCuarto.Text[0] == '3')
this.lblCuarto.Text = "4to Cuarto";
else
finishMatch();
}
private void timer1_Tick(object sender, EventArgs e)
{
count.decCounter();
this.label_timer.Text = count.getCounter;
if (count.getCounter == "00:00:00")
finalizarCuarto();
}
#region Activar y Desactivar botones y labels
#region Desactivar y Activar puntos
void desactivarDoblesLocal()
{
btn_dobleEncestado_L.Enabled = false;
btn_dobleErrado_L.Enabled = false;
}
void desactivarDoblesVisitante()
{
btn_dobleEncestado_V.Enabled = false;
btn_dobleErrado_V.Enabled = false;
}
void desactivarTriplesLocal()
{
btn_tripleEncestado_L.Enabled = false;
btn_tripleErrado_L.Enabled = false;
}
void desactivarTriplesVisitante()
{
btn_tripleEncestado_V.Enabled = false;
btn_tripleErrado_V.Enabled = false;
}
void desactivarPuntos()
{
desactivarDoblesLocal();
desactivarDoblesVisitante();
desactivarTriplesLocal();
desactivarTriplesVisitante();
}
void activarDoblesLocal()
{
btn_dobleEncestado_L.Enabled = true;
btn_dobleErrado_L.Enabled = true;
}
void activarDoblesVisitante()
{
btn_dobleEncestado_V.Enabled = true;
btn_dobleErrado_V.Enabled = true;
}
void activarTriplesLocal()
{
btn_tripleEncestado_L.Enabled = true;
btn_tripleErrado_L.Enabled = true;
}
void activarTriplesVisitante()
{
btn_tripleEncestado_V.Enabled = true;
btn_tripleErrado_V.Enabled = true;
}
void activarPuntos()
{
activarDoblesLocal();
activarDoblesVisitante();
activarTriplesLocal();
activarTriplesVisitante();
}
#endregion
void activarFalta()
{
button_faltaL.Enabled = true;
button_faltaV.Enabled = true;
}
void desactivarFalta()
{
button_faltaL.Enabled = false;
button_faltaV.Enabled = false;
}
void activarPerdida()
{
//button_perdidaL.Enabled = true;
//button_perdidaV.Enabled = true;
}
void desactivarPerdida()
{
//button_perdidaL.Enabled = false;
//button_perdidaV.Enabled = false;
}
void activarCambio()
{
this.button_changeL.Visible = true;
this.button_changeV.Visible = true;
}
void desactivarCambio()
{
this.button_changeL.Visible = false;
this.button_changeV.Visible = false;
}
void activarTOLocal()
{
if (local.TiemposMuertosRestantes > 0)
this.LocalTO.Enabled = true;
}
void activarTOVisitante()
{
if (visitor.TiemposMuertosRestantes > 0)
this.VisitorTO.Enabled = true;
}
void activarTO()
{
activarTOLocal();
activarTOVisitante();
}
void desactivarTOLocal()
{
this.LocalTO.Enabled = false;
}
void desactivarTOVisitante()
{
this.VisitorTO.Enabled = false;
}
void desactivarTO()
{
desactivarTOLocal();
desactivarTOVisitante();
}
void activarLibreLocal()
{
btn_libreEncestado_L.Enabled = true;
btn_libreErrado_L.Enabled = true;
}
void desactivarLibreLocal()
{
btn_libreEncestado_L.Enabled = false;
btn_libreErrado_L.Enabled = false;
}
void activarLibreVisitante()
{
btn_libreEncestado_V.Enabled = true;
btn_libreErrado_V.Enabled = true;
}
void desactivarLibreVisitante()
{
btn_libreEncestado_V.Enabled = false;
btn_libreErrado_V.Enabled = false;
}
/// <summary>
/// Activa el rebote defensivo del equipo defensor y
/// el rebote ofensivo del equipo atacante
/// </summary>
/// <param name="defensivoLocal">Si es falso, el visitante esta defendiendo el rebote</param>
void activarRebotes(bool defensivoLocal = true)
{
if (defensivoLocal)
{
this.btn_rebote_Defensivo_L.Visible = true;
this.btn_rebote_Ofensivo_V.Visible = true;
}
else
{
this.btn_rebote_Ofensivo_L.Visible = true;
this.btn_rebote_Defensivo_V.Visible = true;
}
}
/// <summary>
/// Desactiva TODOS los rebotes de TODOS los equipos
/// </summary>
void desactivarRebotes()
{
// Locales
this.btn_rebote_Defensivo_L.Visible = false;
this.btn_rebote_Ofensivo_L.Visible = false;
// y Visitantes
this.btn_rebote_Ofensivo_V.Visible = false;
this.btn_rebote_Defensivo_V.Visible = false;
}
#endregion
#region Registros
void registrarSimple(string nombreJugador, bool encestado = true)
{
string cuarto = lblCuarto.Text[0].ToString();
string evento = (encestado) ? "Tiro Libre Anotado" : "Tiro Libre Fallado";
Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador);
minuteToMinute.Add(r);
}
void registrarDoble(string nombreJugador, bool encestado = true)
{
string cuarto = lblCuarto.Text[0].ToString();
string evento = (encestado) ? "Doble Anotado" : "Doble Fallado";
Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador);
minuteToMinute.Add(r);
}
void registrarTriple(string nombreJugador, bool encestado = true)
{
string cuarto = lblCuarto.Text[0].ToString();
string evento = (encestado) ? "Triple Anotado" : "Triple Fallado";
Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador);
minuteToMinute.Add(r);
}
void registrarRebote(string nombreJugador, bool ofensivo = false)
{
string cuarto = lblCuarto.Text[0].ToString();
string evento = (ofensivo) ? "Rebote Ofensivo" : "Rebote Defensivo";
Registro r = new Registro(cuarto, this.label_timer.Text, evento, nombreJugador);
minuteToMinute.Add(r);
}
void registrarFalta(string nombreJugador)
{
string cuarto = lblCuarto.Text[0].ToString();
Registro r = new Registro(cuarto, this.label_timer.Text, "Falta", nombreJugador);
minuteToMinute.Add(r);
}
/// <summary>
/// Registra una canasta simple, doble o triple Encestada. Cambia el anotador del partido
/// </summary>
/// <param name="valor">Puede ser 1, 2 o 3</param>
/// <param name="jugador">Jugador al que se le asignara el punto</param>
/// <param name="local">Si es falso, corresponde al equipo visitante</param>
void anotacion(int valor, Player jugador, bool local = true)
{
switch (valor)
{
case 1:
jugador.TirosLibresAnotados++;
registrarSimple(jugador.CompleteName);
break;
case 2:
jugador.PuntosDoblesAnotados++;
registrarDoble(jugador.CompleteName);
break;
case 3:
jugador.PuntosTriplesAnotados++;
registrarTriple(jugador.CompleteName);
break;
}
Label score = null;
if (local)
score = this.label_ptsLocal;
else
score = this.label_ptsVsitor;
int pts = Convert.ToInt32(score.Text) + valor;
score.Text = pts.ToString();
}
/// <summary>
/// Registra una canasta simple, doble o triple Fallida.
/// Of course it does not change the scorer
/// </summary>
/// <param name="valor">Puede ser 1, 2 o 3</param>
/// <param name="jugador">Jugador al que se le asignara el fallo</param>
void fallo(int valor, Player jugador)
{
switch (valor)
{
case 1:
jugador.TirosLibresFallados++;
registrarSimple(jugador.CompleteName, false);
break;
case 2:
jugador.PuntosDoblesFallados++;
registrarDoble(jugador.CompleteName, false);
break;
case 3:
jugador.PuntosTriplesFallados++;
registrarTriple(jugador.CompleteName, false);
break;
}
}
#endregion
// ******************** //
// * METODOS LLAMADOS * //
// * POR EL USUARIO * //
// ******************** //
/// <summary>
/// Sucede cuando el usuario presiona el boton de "Comienzo" del partido
/// </summary>
private void button1_Click(object sender, EventArgs e)
{
desactivarCambio();
desactivarRebotes();
desactivarPuntos();
desactivarPerdida();
desactivarFalta();
desactivarLibreLocal();
desactivarLibreVisitante();
if (procesoFalta)
{
MessageBox.Show("Se continua con los tiros libres..");
congelarContinuacion();
activarCambio();
// Check which team received fault and enable its free shoots
if (localTeamShoot)
activarLibreLocal();
else
activarLibreVisitante();
localTeamShoot = false;
}
else
{
// Check if time is running...
if (timer1.Enabled)
{ //... User want to stop timing
desactivarPerdida();
desactivarPuntos();
desactivarFalta();
activarContinuacion();
activarCambio();
}
else
{ //... User want to continue timing
activarFalta();
activarPerdida();
activarTO();
activarPuntos();
correrContinuacion();
}
}
}
/// <summary>
/// Sucede cuando el usuario realiza un Tiempo Muerto para el LOCAL
/// </summary>
private void LocalTO_Click(object sender, EventArgs e)
{
// Cambia la interfaz del usuario
// Parar reloj y dejarlo a disposición del usuario
activarContinuacion();
activarCambio();
// Desactiva los controles no disponibles
desactivarTO();
desactivarPuntos();
desactivarFalta();
desactivarPerdida();
desactivarLibreLocal();
desactivarRebotes();
// Asigna los tiempos muertos
local.TiemposMuertosRestantes--;
this.label_LTO_restante.Text = local.TiemposMuertosRestantes.ToString();
if (local.TiemposMuertosRestantes == 0)
this.LocalTO.Enabled = false;
if (procesoFalta) {
localTeamShoot = true;
}
}
/// <summary>
/// Sucede cuando el usuario realiza un Tiempo Muerto para el VISITANTE
/// </summary>
private void VisitorTO_Click(object sender, EventArgs e)
{
// Cambia la interfaz del usuario
// Parar reloj y dejarlo a disposición del usuario
activarContinuacion();
activarCambio();
// Desactiva los controles no disponibles
desactivarTO();
desactivarPuntos();
desactivarFalta();
desactivarPerdida();
desactivarLibreVisitante();
desactivarRebotes();
// Asigna los tiempos muertos
visitor.TiemposMuertosRestantes--;
this.label_VTO_restante.Text = visitor.TiemposMuertosRestantes.ToString();
if (visitor.TiemposMuertosRestantes == 0)
this.VisitorTO.Enabled = false;
}
/// <summary>
/// Sucede cuando el usuario quiere realizar un cambio del LOCAL
/// </summary>
private void button2_Click(object sender, EventArgs e)
{
if (listBox_LocalRoster.SelectedItem != null && comboBox_LocalSubs.SelectedItem != null)
{
Player p = (Player)listBox_LocalRoster.SelectedItem;
p.Starter = false;
p = (Player)comboBox_LocalSubs.SelectedItem;
p.Starter = true;
// Actualizar
cargarTitulares();
}
}
/// <summary>
/// Sucede cuando el usuario quiere realizar un cambio del VISITANTE
/// </summary>
private void button3_Click(object sender, EventArgs e)
{
if (listBox_VisitorRoster.SelectedItem != null && comboBox_VisitorSubs.SelectedItem != null)
{
Player p = (Player)listBox_VisitorRoster.SelectedItem;
p.Starter = false;
p = (Player)comboBox_VisitorSubs.SelectedItem;
p.Starter = true;
// Actualizar
cargarVisitantes();
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL comete una falta
/// </summary>
private void button_faltaL_Click(object sender, EventArgs e)
{
congelarContinuacion();
desactivarFalta();
desactivarPerdida();
desactivarTOLocal();
activarTOVisitante();
if (listBox_LocalRoster.SelectedItem != null)
{
// Agrega la Falta al Jugador y Registra el evento
Player p = (Player)listBox_LocalRoster.SelectedItem;
p.FaltasCometidas++;
registrarFalta(p.CompleteName);
// Fire player from game if reached limit of faults committed
if (p.FaltasCometidas == maxFaltas)
listBox_LocalRoster.Items.Remove(p);
// Check if player was shooting while received the fault
DialogResult userResponce = MessageBox.Show("El jugador estaba en posicion de Tiro?",
"Posicion de tiro",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (userResponce == DialogResult.Yes)
{
//desactivarTO();
procesoFalta = true; // Activa el proceso falta
desactivarDoblesLocal();
desactivarTriplesLocal();
}
else // Saque desde el costado
{
desactivarPuntos();
desactivarRebotes();
// Activa el boton de Comienzo
activarContinuacion();
procesoBalonAfuera = true; // Activa el proceso Balon Afuera
}
}
else // No se conoce el jugador que realizo la falta
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
button_faltaL_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE comete una falta
/// </summary>
private void button_faltaV_Click(object sender, EventArgs e)
{
congelarContinuacion();
desactivarFalta();
desactivarPerdida();
desactivarTOVisitante();
activarTOLocal();
if (listBox_VisitorRoster.SelectedItem != null)
{
// Agrega la Falta al Jugador y Registra el evento
Player p = (Player)listBox_VisitorRoster.SelectedItem;
p.FaltasCometidas++;
registrarFalta(p.CompleteName);
// Fire player from game if reached limit of faults committed
if (p.FaltasCometidas == maxFaltas)
listBox_VisitorRoster.Items.Remove(p);
// Check if player was shooting while received the fault
DialogResult userResponce = MessageBox.Show("El jugador estaba en posicion de Tiro?",
"Posicion de tiro",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (userResponce == DialogResult.Yes)
{
//desactivarTO();
procesoFalta = true; // Activa el proceso falta
desactivarDoblesVisitante();
desactivarTriplesVisitante();
}
else // Saque desde el costado
{
desactivarPuntos();
desactivarRebotes();
// Activa el boton de Comienzo
activarContinuacion();
procesoBalonAfuera = true; // Activa el proceso Balon Afuera
}
}
else // No se conoce el jugador que realizo la falta
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
button_faltaV_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL encesta un DOBLE
/// </summary>
private void btn_DobleEns_L_Click(object sender, EventArgs e)
{
// Detiene el reloj
timer1.Enabled = false;
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
anotacion(2, aux);
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Check if player has received a fault while shooting
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOLocal();
activarLibreLocal();
desactivarPuntos();
// Tira 1 tiro libre al recibir falta en zona de 2 punto
tirosLibresDisponibles = 1;
//TODO
// Muestra el Estado
//toolStripStatusLabel1.Text = ""
}
else
{
desactivarTOLocal();
// Activa el boton de Comienzo
activarContinuacion();
}
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_DobleEns_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE encesta un DOBLE
/// </summary>
private void btn_dobleEncestado_V_Click(object sender, EventArgs e)
{
// Detiene el reloj
timer1.Enabled = false;
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
anotacion(2, aux, false);
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Check if player has received a fault while shooting
if (procesoFalta)
{
// Cambia la interfaz gráfica
activarTOVisitante();
activarLibreVisitante();
desactivarPuntos();
// Tira 1 tiro libre al recibir falta en zona de 2 punto
// Tira 1 tiro libre
tirosLibresDisponibles = 1;
}
else
{
desactivarTOVisitante();
// Activa el boton de Comienzo
activarContinuacion();
}
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_dobleEncestado_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL encesta un TRIPLE
/// </summary>
private void btn_tripleEncestado_L_Click(object sender, EventArgs e)
{
// Detiene el reloj
timer1.Enabled = false;
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
anotacion(3, aux);
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Check if player has received a fault while shooting
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOLocal();
activarLibreLocal();
desactivarPuntos();
// Jugada de 4 puntos!! oh yeah!
tirosLibresDisponibles = 1; // Tira 1 tiro libre
}
else
{
desactivarTOLocal();
// Activa el boton de Comienzo
activarContinuacion();
}
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_DobleEns_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE encesta un TRIPLE
/// </summary>
private void btn_tripleEncestado_V_Click(object sender, EventArgs e)
{
// Detiene el reloj
timer1.Enabled = false;
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
anotacion(3, aux, false);
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Check if player has received a fault while shooting
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOVisitante();
activarLibreVisitante();
desactivarPuntos();
// Jugada de 4 puntos!! oh yeah!
tirosLibresDisponibles = 1; // Tira 1 tiro libre
}
else
{
desactivarTOVisitante();
// Activa el boton de Comienzo
activarContinuacion();
}
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_tripleEncestado_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL erra un DOBLE
/// </summary>
private void btn_DobleErrado_L_Click(object sender, EventArgs e)
{
desactivarPuntos();
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOLocal();
activarLibreLocal();
desactivarFalta();
desactivarPerdida();
// Tirara 2 tiros libres
tirosLibresDisponibles = 2;
}
else
{
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
fallo(2, aux);
// Change UI state
activarRebotes(false);
desactivarTOVisitante();
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_DobleErrado_L_Click(sender, e);
}
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE erra un DOBLE
/// </summary>
private void btn_dobleErrado_V_Click(object sender, EventArgs e)
{
desactivarPuntos();
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOVisitante();
activarLibreVisitante();
desactivarFalta();
desactivarPerdida();
// Tirara 2 tiros libres
tirosLibresDisponibles = 2;
}
else
{
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
fallo(2, aux);
// Change UI state
activarRebotes();
desactivarTOLocal();
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_dobleErrado_V_Click(sender, e);
}
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL erra un TRIPLE
/// </summary>
private void btn_tripleErrado_L_Click(object sender, EventArgs e)
{
desactivarPuntos();
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOLocal();
activarLibreLocal();
desactivarFalta();
desactivarPerdida();
// Tirara 3 tiros libres
tirosLibresDisponibles = 3;
}
else
{
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
fallo(3, aux);
// Change UI state
activarRebotes(false);
desactivarTOVisitante();
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_DobleErrado_L_Click(sender, e);
}
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE erra un TRIPLE
/// </summary>
private void btn_tripleErrado_V_Click(object sender, EventArgs e)
{
desactivarPuntos();
if (procesoFalta)
{
// Cambia la interfaz del usuario
activarTOVisitante();
activarLibreVisitante();
desactivarFalta();
desactivarPerdida();
// Tirara 3 tiros libres
tirosLibresDisponibles = 3;
}
else
{
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
fallo(3, aux);
// Change UI state
activarRebotes();
desactivarTOLocal();
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_dobleErrado_V_Click(sender, e);
}
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL logra un rebote OFENSIVO
/// </summary>
private void btn_rebote_L_Click(object sender, EventArgs e)
{
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if(aux != null)
{
// Registra el rebote
aux.RebotesOfensivos++;
registrarRebote(aux.CompleteName, true);
// Cambial el entorno
desactivarRebotes();
activarFalta();
activarPerdida();
activarPuntos();
// Activa TODOS los tiempos muertos
activarTO();
// Vuelve a correr el reloj!
correrContinuacion();
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_rebote_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE logra un rebote OFENSIVO
/// </summary>
private void btn_rebote_Ofensivo_V_Click(object sender, EventArgs e)
{
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
// Registra el rebote
aux.RebotesOfensivos++;
registrarRebote(aux.CompleteName, true);
// Cambial el entorno
desactivarRebotes();
activarFalta();
activarPerdida();
activarPuntos();
// Activa TODOS los tiempos muertos
activarTO();
// Vuelve a correr el reloj!
correrContinuacion();
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_rebote_Ofensivo_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL logra un rebote DEFENSIVO
/// </summary>
private void btn_rebote_Defensivo_L_Click(object sender, EventArgs e)
{
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
// Registra el rebote
aux.RebotesDefensivos++;
registrarRebote(aux.CompleteName);
// Cambial el entorno
desactivarRebotes();
activarFalta();
activarPerdida();
activarPuntos();
// Activa TODOS los tiempos muertos
activarTO();
// Vuelve a correr el reloj!
correrContinuacion();
}
else
{
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_rebote_Defensivo_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE logra un rebote DEFENSIVO
/// </summary>
private void btn_rebote_Defensivo_V_Click(object sender, EventArgs e)
{
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
// Registra el rebote
aux.RebotesDefensivos++;
registrarRebote(aux.CompleteName);
// Cambial el entorno
desactivarRebotes();
activarFalta();
activarPerdida();
activarPuntos();
// Activa TODOS los tiempos muertos
activarTO();
// Vuelve a correr el reloj!
correrContinuacion();
}
else
{
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_rebote_Defensivo_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL encesto un Tiro Libre
/// </summary>
private void btn_libreEncestado_L_Click(object sender, EventArgs e)
{
tirosLibresDisponibles--;
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
anotacion(1, aux);
if (tirosLibresDisponibles == 0)
{
// Cambia el tiempo muerto de mando
activarTO();
desactivarTOLocal();
// Desactiva los tiros libres
desactivarLibreLocal();
activarContinuacion();
procesoFalta = false;
}
}
else
{
// Selecciona el jugador LOCAL que ENCESTO el tiro
SelectPlayer nuevo = new SelectPlayer(local.Players);
nuevo.ShowDialog();
this.listBox_LocalRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_libreEncestado_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE encesto un Tiro Libre
/// </summary>
private void btn_libreEncestado_V_Click(object sender, EventArgs e)
{
tirosLibresDisponibles--;
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
anotacion(1, aux, false);
if (tirosLibresDisponibles == 0)
{
// Cambia el tiempo muerto de mando
activarTO();
desactivarTOVisitante();
desactivarLibreVisitante();
activarContinuacion();
procesoFalta = false;
}
}
else
{
// Selecciona el jugador VISITANTE que ENCESTO el tiro
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_libreEncestado_V_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo LOCAL erra un tiro libre
/// </summary>
private void btn_libreErrado_L_Click(object sender, EventArgs e)
{
tirosLibresDisponibles--;
Player aux = (Player)listBox_LocalRoster.SelectedItem;
if (aux != null)
{
fallo(1, aux);
if (tirosLibresDisponibles == 0)
{
desactivarLibreLocal();
correrContinuacion();
procesoFalta = false;
// Se encienden los rebotes
activarRebotes(false);
}
}
else
{
// Selecciona el jugador LOCAL que FALLO el tiro
SelectPlayer window = new SelectPlayer(local.Players);
window.ShowDialog();
this.listBox_LocalRoster.SelectedItem = window.JugadorSeleccionado;
btn_libreErrado_L_Click(sender, e);
}
}
/// <summary>
/// Sucede cuando el equipo VISITANTE erra un tiro libre
/// </summary>
private void btn_libreErrado_V_Click(object sender, EventArgs e)
{
tirosLibresDisponibles--;
Player aux = (Player)listBox_VisitorRoster.SelectedItem;
if (aux != null)
{
fallo(1, aux);
if (tirosLibresDisponibles == 0)
{
desactivarLibreVisitante();
correrContinuacion();
procesoFalta = false;
// Se encienden los rebotes
activarRebotes(false);
}
}
else
{
// Selecciona el jugador LOCAL que FALLO el tiro
SelectPlayer nuevo = new SelectPlayer(visitor.Players);
nuevo.ShowDialog();
this.listBox_VisitorRoster.SelectedItem = nuevo.JugadorSeleccionado;
btn_libreErrado_V_Click(sender, e);
}
}
/// <summary>
/// Abre un dialogo pidiendo confirmación al usuario para salir del programa
/// </summary>
private void partido_FormClosing(object sender, FormClosingEventArgs e)
{
if (!closeWindow)
{
DialogResult userResponce = MessageBox.Show("Esta seguro que desea cerrar la ventana?\n"+
"Los datos no seran guardados.",
"Cerrar ventana",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
if (userResponce == System.Windows.Forms.DialogResult.No)
e.Cancel = true;
}
}
private void button_perdidaL_Click(object sender, EventArgs e)
{
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Activa el boton de Comienzo
activarContinuacion();
procesoBalonAfuera = true; // Activa el proceso Balon Afuera
}
private void button_perdidaV_Click(object sender, EventArgs e)
{
desactivarPuntos();
desactivarRebotes();
desactivarFalta();
desactivarPerdida();
// Activa el boton de Comienzo
activarContinuacion();
procesoBalonAfuera = true; // Activa el proceso Balon Afuera
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LinqToDB.Data
{
using Linq;
using Common;
using SqlProvider;
using SqlQuery;
public partial class DataConnection
{
IQueryRunner IDataContext.GetQueryRunner(Query query, int queryNumber, Expression expression, object[] parameters)
{
CheckAndThrowOnDisposed();
return new QueryRunner(query, queryNumber, this, expression, parameters);
}
internal class QueryRunner : QueryRunnerBase
{
public QueryRunner(Query query, int queryNumber, DataConnection dataConnection, Expression expression, object[] parameters)
: base(query, queryNumber, dataConnection, expression, parameters)
{
_dataConnection = dataConnection;
}
readonly DataConnection _dataConnection;
readonly DateTime _startedOn = DateTime.UtcNow;
readonly Stopwatch _stopwatch = Stopwatch.StartNew();
bool _isAsync;
Expression _mapperExpression;
public override Expression MapperExpression
{
get => _mapperExpression;
set
{
_mapperExpression = value;
if (value != null && Common.Configuration.Linq.TraceMapperExpression &&
TraceSwitch.TraceInfo && _dataConnection.OnTraceConnection != null)
{
_dataConnection.OnTraceConnection(new TraceInfo(TraceInfoStep.MapperCreated)
{
TraceLevel = TraceLevel.Info,
DataConnection = _dataConnection,
MapperExpression = MapperExpression,
StartTime = _startedOn,
ExecutionTime = _stopwatch.Elapsed,
IsAsync = _isAsync,
});
}
}
}
public override string GetSqlText()
{
SetCommand(false);
var sqlProvider = _preparedQuery.SqlProvider ?? _dataConnection.DataProvider.CreateSqlBuilder();
var sb = new StringBuilder();
sb.Append("-- ").Append(_dataConnection.ConfigurationString);
if (_dataConnection.ConfigurationString != _dataConnection.DataProvider.Name)
sb.Append(' ').Append(_dataConnection.DataProvider.Name);
if (_dataConnection.DataProvider.Name != sqlProvider.Name)
sb.Append(' ').Append(sqlProvider.Name);
sb.AppendLine();
sqlProvider.PrintParameters(sb, _preparedQuery.Parameters);
var isFirst = true;
foreach (var command in _preparedQuery.Commands)
{
sb.AppendLine(command);
if (isFirst && _preparedQuery.QueryHints != null && _preparedQuery.QueryHints.Count > 0)
{
isFirst = false;
while (sb[sb.Length - 1] == '\n' || sb[sb.Length - 1] == '\r')
sb.Length--;
sb.AppendLine();
var sql = sb.ToString();
var sqlBuilder = _dataConnection.DataProvider.CreateSqlBuilder();
sql = sqlBuilder.ApplyQueryHints(sql, _preparedQuery.QueryHints);
sb = new StringBuilder(sql);
}
}
while (sb[sb.Length - 1] == '\n' || sb[sb.Length - 1] == '\r')
sb.Length--;
sb.AppendLine();
return sb.ToString();
}
public override void Dispose()
{
if (TraceSwitch.TraceInfo && _dataConnection.OnTraceConnection != null)
{
_dataConnection.OnTraceConnection(new TraceInfo(TraceInfoStep.Completed)
{
TraceLevel = TraceLevel.Info,
DataConnection = _dataConnection,
Command = _dataConnection.Command,
MapperExpression = MapperExpression,
StartTime = _startedOn,
ExecutionTime = _stopwatch.Elapsed,
RecordsAffected = RowsCount,
IsAsync = _isAsync,
});
}
base.Dispose();
}
public class PreparedQuery
{
public string[] Commands;
public List<SqlParameter> SqlParameters;
public IDbDataParameter[] Parameters;
public SqlStatement Statement;
public ISqlBuilder SqlProvider;
public List<string> QueryHints;
}
PreparedQuery _preparedQuery;
static PreparedQuery GetCommand(DataConnection dataConnection, IQueryContext query, int startIndent = 0)
{
if (query.Context != null)
{
return new PreparedQuery
{
Commands = (string[])query.Context,
SqlParameters = query.Statement.Parameters,
Statement = query.Statement,
QueryHints = query.QueryHints,
};
}
var sql = query.Statement.ProcessParameters(dataConnection.MappingSchema);
var newSql = dataConnection.ProcessQuery(sql);
if (!object.ReferenceEquals(sql, newSql))
{
sql = newSql;
sql.IsParameterDependent = true;
}
var sqlProvider = dataConnection.DataProvider.CreateSqlBuilder();
var cc = sqlProvider.CommandCount(sql);
var sb = new StringBuilder();
var commands = new string[cc];
for (var i = 0; i < cc; i++)
{
sb.Length = 0;
sqlProvider.BuildSql(i, sql, sb, startIndent);
commands[i] = sb.ToString();
}
if (!sql.IsParameterDependent)
query.Context = commands;
return new PreparedQuery
{
Commands = commands,
SqlParameters = sql.Parameters,
Statement = sql,
SqlProvider = sqlProvider,
QueryHints = query.QueryHints,
};
}
static void GetParameters(DataConnection dataConnection, IQueryContext query, PreparedQuery pq)
{
var parameters = query.GetParameters();
if (parameters.Length == 0 && pq.SqlParameters.Count == 0)
return;
var ordered = dataConnection.DataProvider.SqlProviderFlags.IsParameterOrderDependent;
var c = ordered ? pq.SqlParameters.Count : parameters.Length;
var parms = new List<IDbDataParameter>(c);
if (ordered)
{
for (var i = 0; i < pq.SqlParameters.Count; i++)
{
var sqlp = pq.SqlParameters[i];
if (sqlp.IsQueryParameter)
{
var parm = parameters.Length > i && object.ReferenceEquals(parameters[i], sqlp) ?
parameters[i] :
parameters.First(p => object.ReferenceEquals(p, sqlp));
AddParameter(dataConnection, parms, parm.Name, parm);
}
}
}
else
{
foreach (var parm in parameters)
{
if (parm.IsQueryParameter && pq.SqlParameters.Contains(parm))
AddParameter(dataConnection, parms, parm.Name, parm);
}
}
pq.Parameters = parms.ToArray();
}
static void AddParameter(DataConnection dataConnection, ICollection<IDbDataParameter> parms, string name, SqlParameter parm)
{
var p = dataConnection.Command.CreateParameter();
var systemType = parm.SystemType;
var dataType = parm.DataType;
var dbType = parm.DbType;
var dbSize = parm.DbSize;
var paramValue = parm.Value;
if (systemType == null)
{
if (paramValue != null)
systemType = paramValue.GetType();
}
if (dataType == DataType.Undefined)
{
dataType = dataConnection.MappingSchema.GetDataType(
parm.SystemType == typeof(object) && paramValue != null ?
paramValue.GetType() :
systemType).DataType;
}
dataConnection.DataProvider.SetParameter(p, name, new DbDataType(systemType, dataType, dbType, dbSize), paramValue);
parms.Add(p);
}
public static PreparedQuery SetQuery(DataConnection dataConnection, IQueryContext queryContext, int startIndent = 0)
{
var preparedQuery = GetCommand(dataConnection, queryContext, startIndent);
GetParameters(dataConnection, queryContext, preparedQuery);
return preparedQuery;
}
protected override void SetQuery()
{
_preparedQuery = SetQuery(_dataConnection, Query.Queries[QueryNumber]);
}
void SetCommand()
{
SetCommand(true);
_dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints);
if (_preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
}
#region ExecuteNonQuery
static int ExecuteNonQueryImpl(DataConnection dataConnection, PreparedQuery preparedQuery)
{
if (preparedQuery.Commands.Length == 1)
{
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints);
if (preparedQuery.Parameters != null)
foreach (var p in preparedQuery.Parameters)
dataConnection.Command.Parameters.Add(p);
return dataConnection.ExecuteNonQuery();
}
var rowsAffected = -1;
for (var i = 0; i < preparedQuery.Commands.Length; i++)
{
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[i], null, i == 0 ? preparedQuery.QueryHints : null);
if (i == 0 && preparedQuery.Parameters != null)
foreach (var p in preparedQuery.Parameters)
dataConnection.Command.Parameters.Add(p);
if (i < preparedQuery.Commands.Length - 1 && preparedQuery.Commands[i].StartsWith("DROP"))
{
try
{
dataConnection.ExecuteNonQuery();
}
catch (Exception)
{
}
}
else
{
var n = dataConnection.ExecuteNonQuery();
if (i == 0)
rowsAffected = n;
}
}
return rowsAffected;
}
public override int ExecuteNonQuery()
{
SetCommand(true);
return ExecuteNonQueryImpl(_dataConnection, _preparedQuery);
}
public static int ExecuteNonQuery(DataConnection dataConnection, IQueryContext context)
{
var preparedQuery = GetCommand(dataConnection, context);
GetParameters(dataConnection, context, preparedQuery);
return ExecuteNonQueryImpl(dataConnection, preparedQuery);
}
#endregion
#region ExecuteScalar
static object ExecuteScalarImpl(DataConnection dataConnection, PreparedQuery preparedQuery)
{
IDbDataParameter idParam = null;
if (dataConnection.DataProvider.SqlProviderFlags.IsIdentityParameterRequired)
{
if (preparedQuery.Statement.NeedsIdentity())
{
idParam = dataConnection.Command.CreateParameter();
idParam.ParameterName = "IDENTITY_PARAMETER";
idParam.Direction = ParameterDirection.Output;
idParam.DbType = DbType.Decimal;
dataConnection.Command.Parameters.Add(idParam);
}
}
if (preparedQuery.Commands.Length == 1)
{
if (idParam != null)
{
// This is because the firebird provider does not return any parameters via ExecuteReader
// the rest of the providers must support this mode
dataConnection.ExecuteNonQuery();
return idParam.Value;
}
return dataConnection.ExecuteScalar();
}
dataConnection.ExecuteNonQuery();
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[1], null, null);
return dataConnection.ExecuteScalar();
}
public static object ExecuteScalar(DataConnection dataConnection, IQueryContext context)
{
var preparedQuery = GetCommand(dataConnection, context);
GetParameters(dataConnection, context, preparedQuery);
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints);
if (preparedQuery.Parameters != null)
foreach (var p in preparedQuery.Parameters)
dataConnection.Command.Parameters.Add(p);
return ExecuteScalarImpl(dataConnection, preparedQuery);
}
public override object ExecuteScalar()
{
SetCommand();
return ExecuteScalarImpl(_dataConnection, _preparedQuery);
}
#endregion
#region ExecuteReader
public static IDataReader ExecuteReader(DataConnection dataConnection, IQueryContext context)
{
var preparedQuery = GetCommand(dataConnection, context);
GetParameters(dataConnection, context, preparedQuery);
dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints);
if (preparedQuery.Parameters != null)
foreach (var p in preparedQuery.Parameters)
dataConnection.Command.Parameters.Add(p);
return dataConnection.ExecuteReader();
}
public override IDataReader ExecuteReader()
{
SetCommand(true);
_dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints);
if (_preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
return _dataConnection.ExecuteReader();
}
#endregion
class DataReaderAsync : IDataReaderAsync
{
public DataReaderAsync(DbDataReader dataReader)
{
_dataReader = dataReader;
}
readonly DbDataReader _dataReader;
public IDataReader DataReader => _dataReader;
public Task<bool> ReadAsync(CancellationToken cancellationToken)
{
return _dataReader.ReadAsync(cancellationToken);
}
public void Dispose()
{
// call interface method, because at least MySQL provider incorrectly override
// methods for .net core 1x
DataReader.Dispose();
}
}
public override async Task<IDataReaderAsync> ExecuteReaderAsync(CancellationToken cancellationToken)
{
_isAsync = true;
await _dataConnection.EnsureConnectionAsync(cancellationToken);
base.SetCommand(true);
_dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints);
if (_preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
var dataReader = await _dataConnection.ExecuteReaderAsync(_dataConnection.GetCommandBehavior(CommandBehavior.Default), cancellationToken);
return new DataReaderAsync(dataReader);
}
public override async Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken)
{
_isAsync = true;
await _dataConnection.EnsureConnectionAsync(cancellationToken);
base.SetCommand(true);
if (_preparedQuery.Commands.Length == 1)
{
_dataConnection.InitCommand(
CommandType.Text, _preparedQuery.Commands[0], null, _preparedQuery.QueryHints);
if (_preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
return await _dataConnection.ExecuteNonQueryAsync(cancellationToken);
}
for (var i = 0; i < _preparedQuery.Commands.Length; i++)
{
_dataConnection.InitCommand(
CommandType.Text, _preparedQuery.Commands[i], null, i == 0 ? _preparedQuery.QueryHints : null);
if (i == 0 && _preparedQuery.Parameters != null)
foreach (var p in _preparedQuery.Parameters)
_dataConnection.Command.Parameters.Add(p);
if (i < _preparedQuery.Commands.Length - 1 && _preparedQuery.Commands[i].StartsWith("DROP"))
{
try
{
await _dataConnection.ExecuteNonQueryAsync(cancellationToken);
}
catch
{
}
}
else
{
await _dataConnection.ExecuteNonQueryAsync(cancellationToken);
}
}
return -1;
}
public override async Task<object> ExecuteScalarAsync(CancellationToken cancellationToken)
{
_isAsync = true;
await _dataConnection.EnsureConnectionAsync(cancellationToken);
SetCommand();
IDbDataParameter idparam = null;
if (_dataConnection.DataProvider.SqlProviderFlags.IsIdentityParameterRequired)
{
if (_preparedQuery.Statement.NeedsIdentity())
{
idparam = _dataConnection.Command.CreateParameter();
idparam.ParameterName = "IDENTITY_PARAMETER";
idparam.Direction = ParameterDirection.Output;
idparam.DbType = DbType.Decimal;
_dataConnection.Command.Parameters.Add(idparam);
}
}
if (_preparedQuery.Commands.Length == 1)
{
if (idparam != null)
{
// так сделано потому, что фаерберд провайдер не возвращает никаких параметров через ExecuteReader
// остальные провайдеры должны поддерживать такой режим
await _dataConnection.ExecuteNonQueryAsync(cancellationToken);
return idparam.Value;
}
return await _dataConnection.ExecuteScalarAsync(cancellationToken);
}
await _dataConnection.ExecuteNonQueryAsync(cancellationToken);
_dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[1], null, null);
return await _dataConnection.ExecuteScalarAsync(cancellationToken);
}
}
}
}
|
namespace TransferCavityLock2012
{
partial class LockControlPanel
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lockParams = new System.Windows.Forms.GroupBox();
this.lockedLED = new NationalInstruments.UI.WindowsForms.Led();
this.label10 = new System.Windows.Forms.Label();
this.setPointIncrementBox = new System.Windows.Forms.TextBox();
this.GainTextbox = new System.Windows.Forms.TextBox();
this.VoltageToLaserTextBox = new System.Windows.Forms.TextBox();
this.setPointAdjustMinusButton = new System.Windows.Forms.Button();
this.setPointAdjustPlusButton = new System.Windows.Forms.Button();
this.LaserSetPointTextBox = new System.Windows.Forms.TextBox();
this.lockEnableCheck = new System.Windows.Forms.CheckBox();
this.label4 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.SlaveLaserIntensityScatterGraph = new NationalInstruments.UI.WindowsForms.ScatterGraph();
this.SlaveDataPlot = new NationalInstruments.UI.ScatterPlot();
this.xAxis1 = new NationalInstruments.UI.XAxis();
this.yAxis1 = new NationalInstruments.UI.YAxis();
this.SlaveFitPlot = new NationalInstruments.UI.ScatterPlot();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.ErrorScatterGraph = new NationalInstruments.UI.WindowsForms.ScatterGraph();
this.ErrorPlot = new NationalInstruments.UI.ScatterPlot();
this.xAxis2 = new NationalInstruments.UI.XAxis();
this.yAxis2 = new NationalInstruments.UI.YAxis();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.slErrorResetButton = new System.Windows.Forms.Button();
this.VoltageTrackBar = new System.Windows.Forms.TrackBar();
this.lockParams.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.lockedLED)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.SlaveLaserIntensityScatterGraph)).BeginInit();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.ErrorScatterGraph)).BeginInit();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.VoltageTrackBar)).BeginInit();
this.SuspendLayout();
//
// lockParams
//
this.lockParams.Controls.Add(this.lockedLED);
this.lockParams.Controls.Add(this.label10);
this.lockParams.Controls.Add(this.setPointIncrementBox);
this.lockParams.Controls.Add(this.GainTextbox);
this.lockParams.Controls.Add(this.VoltageToLaserTextBox);
this.lockParams.Controls.Add(this.setPointAdjustMinusButton);
this.lockParams.Controls.Add(this.setPointAdjustPlusButton);
this.lockParams.Controls.Add(this.LaserSetPointTextBox);
this.lockParams.Controls.Add(this.lockEnableCheck);
this.lockParams.Controls.Add(this.label4);
this.lockParams.Controls.Add(this.label2);
this.lockParams.Controls.Add(this.label3);
this.lockParams.Controls.Add(this.VoltageTrackBar);
this.lockParams.Location = new System.Drawing.Point(589, 3);
this.lockParams.Name = "lockParams";
this.lockParams.Size = new System.Drawing.Size(355, 162);
this.lockParams.TabIndex = 13;
this.lockParams.TabStop = false;
this.lockParams.Text = "Lock Parameters";
//
// lockedLED
//
this.lockedLED.LedStyle = NationalInstruments.UI.LedStyle.Round3D;
this.lockedLED.Location = new System.Drawing.Point(310, 6);
this.lockedLED.Name = "lockedLED";
this.lockedLED.Size = new System.Drawing.Size(32, 30);
this.lockedLED.TabIndex = 34;
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(6, 66);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(123, 13);
this.label10.TabIndex = 33;
this.label10.Text = "Set Point Increment Size";
//
// setPointIncrementBox
//
this.setPointIncrementBox.Location = new System.Drawing.Point(168, 63);
this.setPointIncrementBox.Name = "setPointIncrementBox";
this.setPointIncrementBox.Size = new System.Drawing.Size(55, 20);
this.setPointIncrementBox.TabIndex = 32;
this.setPointIncrementBox.Text = "0.01";
this.setPointIncrementBox.TextChanged += new System.EventHandler(this.setPointIncrementBox_TextChanged);
//
// GainTextbox
//
this.GainTextbox.Location = new System.Drawing.Point(167, 15);
this.GainTextbox.Name = "GainTextbox";
this.GainTextbox.Size = new System.Drawing.Size(81, 20);
this.GainTextbox.TabIndex = 31;
this.GainTextbox.Text = "0.5";
this.GainTextbox.TextChanged += new System.EventHandler(this.GainChanged);
//
// VoltageToLaserTextBox
//
this.VoltageToLaserTextBox.Location = new System.Drawing.Point(167, 89);
this.VoltageToLaserTextBox.Name = "VoltageToLaserTextBox";
this.VoltageToLaserTextBox.Size = new System.Drawing.Size(100, 20);
this.VoltageToLaserTextBox.TabIndex = 30;
this.VoltageToLaserTextBox.Text = "0";
this.VoltageToLaserTextBox.TextChanged += new System.EventHandler(this.VoltageToLaserChanged);
//
// setPointAdjustMinusButton
//
this.setPointAdjustMinusButton.Location = new System.Drawing.Point(124, 37);
this.setPointAdjustMinusButton.Name = "setPointAdjustMinusButton";
this.setPointAdjustMinusButton.Size = new System.Drawing.Size(37, 23);
this.setPointAdjustMinusButton.TabIndex = 29;
this.setPointAdjustMinusButton.Text = "-";
this.setPointAdjustMinusButton.UseVisualStyleBackColor = true;
this.setPointAdjustMinusButton.Click += new System.EventHandler(this.setPointAdjustMinusButton_Click);
//
// setPointAdjustPlusButton
//
this.setPointAdjustPlusButton.Location = new System.Drawing.Point(81, 37);
this.setPointAdjustPlusButton.Name = "setPointAdjustPlusButton";
this.setPointAdjustPlusButton.Size = new System.Drawing.Size(37, 23);
this.setPointAdjustPlusButton.TabIndex = 28;
this.setPointAdjustPlusButton.Text = "+";
this.setPointAdjustPlusButton.UseVisualStyleBackColor = true;
this.setPointAdjustPlusButton.Click += new System.EventHandler(this.setPointAdjustPlusButton_Click);
//
// LaserSetPointTextBox
//
this.LaserSetPointTextBox.AcceptsReturn = true;
this.LaserSetPointTextBox.Location = new System.Drawing.Point(167, 39);
this.LaserSetPointTextBox.Name = "LaserSetPointTextBox";
this.LaserSetPointTextBox.Size = new System.Drawing.Size(57, 20);
this.LaserSetPointTextBox.TabIndex = 27;
this.LaserSetPointTextBox.Text = "0";
//
// lockEnableCheck
//
this.lockEnableCheck.AutoSize = true;
this.lockEnableCheck.Location = new System.Drawing.Point(254, 17);
this.lockEnableCheck.Name = "lockEnableCheck";
this.lockEnableCheck.Size = new System.Drawing.Size(50, 17);
this.lockEnableCheck.TabIndex = 9;
this.lockEnableCheck.Text = "Lock";
this.lockEnableCheck.UseVisualStyleBackColor = true;
this.lockEnableCheck.CheckedChanged += new System.EventHandler(this.lockEnableCheck_CheckedChanged);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(6, 18);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(29, 13);
this.label4.TabIndex = 20;
this.label4.Text = "Gain";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 92);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(122, 13);
this.label2.TabIndex = 17;
this.label2.Text = "Voltage sent to laser (V):";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 42);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(69, 13);
this.label3.TabIndex = 13;
this.label3.Text = "Set Point (V):";
//
// SlaveLaserIntensityScatterGraph
//
this.SlaveLaserIntensityScatterGraph.Location = new System.Drawing.Point(9, 17);
this.SlaveLaserIntensityScatterGraph.Name = "SlaveLaserIntensityScatterGraph";
this.SlaveLaserIntensityScatterGraph.Plots.AddRange(new NationalInstruments.UI.ScatterPlot[] {
this.SlaveDataPlot,
this.SlaveFitPlot});
this.SlaveLaserIntensityScatterGraph.Size = new System.Drawing.Size(567, 132);
this.SlaveLaserIntensityScatterGraph.TabIndex = 12;
this.SlaveLaserIntensityScatterGraph.XAxes.AddRange(new NationalInstruments.UI.XAxis[] {
this.xAxis1});
this.SlaveLaserIntensityScatterGraph.YAxes.AddRange(new NationalInstruments.UI.YAxis[] {
this.yAxis1});
//
// SlaveDataPlot
//
this.SlaveDataPlot.LineStyle = NationalInstruments.UI.LineStyle.None;
this.SlaveDataPlot.PointSize = new System.Drawing.Size(3, 3);
this.SlaveDataPlot.PointStyle = NationalInstruments.UI.PointStyle.SolidCircle;
this.SlaveDataPlot.XAxis = this.xAxis1;
this.SlaveDataPlot.YAxis = this.yAxis1;
//
// SlaveFitPlot
//
this.SlaveFitPlot.LineStyle = NationalInstruments.UI.LineStyle.None;
this.SlaveFitPlot.PointColor = System.Drawing.Color.LawnGreen;
this.SlaveFitPlot.PointStyle = NationalInstruments.UI.PointStyle.EmptyTriangleUp;
this.SlaveFitPlot.XAxis = this.xAxis1;
this.SlaveFitPlot.YAxis = this.yAxis1;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.ErrorScatterGraph);
this.groupBox1.Controls.Add(this.SlaveLaserIntensityScatterGraph);
this.groupBox1.Location = new System.Drawing.Point(4, 3);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(582, 286);
this.groupBox1.TabIndex = 15;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Slave laser";
//
// ErrorScatterGraph
//
this.ErrorScatterGraph.Location = new System.Drawing.Point(6, 155);
this.ErrorScatterGraph.Name = "ErrorScatterGraph";
this.ErrorScatterGraph.Plots.AddRange(new NationalInstruments.UI.ScatterPlot[] {
this.ErrorPlot});
this.ErrorScatterGraph.Size = new System.Drawing.Size(570, 125);
this.ErrorScatterGraph.TabIndex = 13;
this.ErrorScatterGraph.UseColorGenerator = true;
this.ErrorScatterGraph.XAxes.AddRange(new NationalInstruments.UI.XAxis[] {
this.xAxis2});
this.ErrorScatterGraph.YAxes.AddRange(new NationalInstruments.UI.YAxis[] {
this.yAxis2});
//
// ErrorPlot
//
this.ErrorPlot.LineColor = System.Drawing.Color.Red;
this.ErrorPlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor;
this.ErrorPlot.XAxis = this.xAxis2;
this.ErrorPlot.YAxis = this.yAxis2;
//
// xAxis2
//
this.xAxis2.Mode = NationalInstruments.UI.AxisMode.StripChart;
this.xAxis2.Range = new NationalInstruments.UI.Range(0D, 500D);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.slErrorResetButton);
this.groupBox2.Location = new System.Drawing.Point(589, 171);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(355, 118);
this.groupBox2.TabIndex = 16;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Error Signal Parameters";
//
// slErrorResetButton
//
this.slErrorResetButton.Location = new System.Drawing.Point(9, 19);
this.slErrorResetButton.Name = "slErrorResetButton";
this.slErrorResetButton.Size = new System.Drawing.Size(109, 23);
this.slErrorResetButton.TabIndex = 29;
this.slErrorResetButton.Text = "Reset Graph";
this.slErrorResetButton.UseVisualStyleBackColor = true;
this.slErrorResetButton.Click += new System.EventHandler(this.slErrorResetButton_Click);
//
// VoltageTrackBar
//
this.VoltageTrackBar.BackColor = System.Drawing.SystemColors.ButtonFace;
this.VoltageTrackBar.Location = new System.Drawing.Point(6, 114);
this.VoltageTrackBar.Maximum = 1000;
this.VoltageTrackBar.Name = "VoltageTrackBar";
this.VoltageTrackBar.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.VoltageTrackBar.Size = new System.Drawing.Size(343, 45);
this.VoltageTrackBar.TabIndex = 53;
this.VoltageTrackBar.Value = 100;
this.VoltageTrackBar.Scroll += new System.EventHandler(this.VoltageTrackBar_Scroll);
//
// LockControlPanel
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSize = true;
this.Controls.Add(this.lockParams);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Name = "LockControlPanel";
this.Size = new System.Drawing.Size(952, 294);
this.lockParams.ResumeLayout(false);
this.lockParams.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.lockedLED)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.SlaveLaserIntensityScatterGraph)).EndInit();
this.groupBox1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.ErrorScatterGraph)).EndInit();
this.groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.VoltageTrackBar)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox lockParams;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.TextBox setPointIncrementBox;
private System.Windows.Forms.TextBox GainTextbox;
private System.Windows.Forms.TextBox VoltageToLaserTextBox;
private System.Windows.Forms.Button setPointAdjustMinusButton;
private System.Windows.Forms.Button setPointAdjustPlusButton;
private System.Windows.Forms.TextBox LaserSetPointTextBox;
private System.Windows.Forms.CheckBox lockEnableCheck;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
public NationalInstruments.UI.WindowsForms.ScatterGraph SlaveLaserIntensityScatterGraph;
public NationalInstruments.UI.ScatterPlot SlaveDataPlot;
private NationalInstruments.UI.XAxis xAxis1;
private NationalInstruments.UI.YAxis yAxis1;
public NationalInstruments.UI.ScatterPlot SlaveFitPlot;
private System.Windows.Forms.GroupBox groupBox1;
private NationalInstruments.UI.WindowsForms.Led lockedLED;
private NationalInstruments.UI.WindowsForms.ScatterGraph ErrorScatterGraph;
private NationalInstruments.UI.ScatterPlot ErrorPlot;
private NationalInstruments.UI.XAxis xAxis2;
private NationalInstruments.UI.YAxis yAxis2;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Button slErrorResetButton;
public System.Windows.Forms.TrackBar VoltageTrackBar;
}
}
|
using System;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Castle.Core;
using DotJEM.Json.Storage.Adapter;
using DotJEM.Pipelines;
using DotJEM.Web.Host.Diagnostics.Performance;
using DotJEM.Web.Host.Providers.Concurrency;
using DotJEM.Web.Host.Providers.Services.DiffMerge;
using Newtonsoft.Json.Linq;
namespace DotJEM.Web.Host.Providers.Services
{
public interface IContentService
{
IStorageArea StorageArea { get; }
Task<JObject> GetAsync(Guid id, string contentType);
Task<JObject> PostAsync(string contentType, JObject entity);
Task<JObject> PutAsync(Guid id, string contentType, JObject entity);
Task<JObject> PatchAsync(Guid id, string contentType, JObject entity);
Task<JObject> DeleteAsync(Guid id, string contentType);
}
//TODO: Apply Pipeline for all requests.
[Interceptor(typeof(PerformanceLogAspect))]
public class ContentService : IContentService
{
private readonly IStorageArea area;
private readonly IStorageIndexManager manager;
private readonly IPipelines pipelines;
private readonly IContentMergeService merger;
public IStorageArea StorageArea => area;
public ContentService(IStorageArea area,
IStorageIndexManager manager,
IPipelines pipelines,
IJsonMergeVisitor merger)
{
this.area = area;
this.manager = manager;
this.pipelines = pipelines;
this.merger = new ContentMergeService(merger, area);
}
public Task<JObject> GetAsync(Guid id, string contentType)
{
HttpGetContext context = new (contentType, id);
ICompiledPipeline<JObject> pipeline = pipelines
.For(context, ctx => Task.Run(() => area.Get(ctx.Id)));
return pipeline.Invoke();
}
public async Task<JObject> PostAsync(string contentType, JObject entity)
{
HttpPostContext context = new (contentType, entity);
ICompiledPipeline<JObject> pipeline = pipelines
.For(context, ctx => Task.Run(() => area.Insert(ctx.ContentType, ctx.Entity)));
entity = await pipeline.Invoke().ConfigureAwait(false);
manager.QueueUpdate(entity);
return entity;
}
public async Task<JObject> PutAsync(Guid id, string contentType, JObject entity)
{
JObject prev = area.Get(id);
entity = merger.EnsureMerge(id, entity, prev);
HttpPutContext context = new (contentType, id, entity, prev);
ICompiledPipeline<JObject> pipeline = pipelines
.For(context, ctx => Task.Run(() => area.Update(ctx.Id, ctx.Entity)));
entity = await pipeline.Invoke().ConfigureAwait(false);
manager.QueueUpdate(entity);
return entity;
}
public async Task<JObject> PatchAsync(Guid id, string contentType, JObject entity)
{
JObject prev = area.Get(id);
//TODO: This can be done better by simply merging the prev into the entity but skipping
// values that are present in the entity. However, we might wan't to inclide the raw patch
// content in the pipeline as well, so we need to consider pro/cons
JObject clone = (JObject)prev.DeepClone();
clone.Merge(entity);
entity = clone;
entity = merger.EnsureMerge(id, entity, prev);
HttpPatchContext context = new (contentType, id, entity, prev);
ICompiledPipeline<JObject> pipeline = pipelines
.For(context, ctx => Task.Run(() => area.Update(ctx.Id, ctx.Entity)));
entity = await pipeline.Invoke().ConfigureAwait(false);
manager.QueueUpdate(entity);
return entity;
}
public async Task<JObject> DeleteAsync(Guid id, string contentType)
{
JObject prev = area.Get(id);
if (prev == null)
return null;
HttpDeleteContext context = new (contentType, id, prev);
ICompiledPipeline<JObject> pipeline = pipelines
.For(context, ctx => Task.Run(() => area.Delete(ctx.Id)));
JObject deleted = await pipeline.Invoke().ConfigureAwait(false);
//Note: This may pose a bit of a problem, because we don't lock so far out (performance),
// this can theoretically happen if two threads or two nodes are trying to delete the
// same object at the same time.
if (deleted == null)
return null;
manager.QueueDelete(deleted);
return deleted;
}
}
public class HttpPipelineContext : PipelineContext
{
public HttpPipelineContext(string method, string contentType)
{
this.Set(nameof(method), method);
this.Set(nameof(contentType), contentType);
}
}
public class HttpGetContext : HttpPipelineContext
{
public string ContentType => (string)Get("contentType");
public Guid Id => (Guid) Get("id");
public HttpGetContext(string contentType, Guid id)
: base("GET", contentType)
{
Set(nameof(id), id);
}
}
public class HttpPostContext : HttpPipelineContext
{
public string ContentType => (string)Get("contentType");
public JObject Entity => (JObject)Get("entity");
public HttpPostContext( string contentType, JObject entity)
: base("POST", contentType)
{
Set(nameof(entity), entity);
}
}
public class HttpPutContext : HttpPipelineContext
{
public string ContentType => (string)Get("contentType");
public Guid Id => (Guid) Get("id");
public JObject Entity => (JObject)Get("entity");
public JObject Previous => (JObject)Get("previous");
public HttpPutContext(string contentType, Guid id, JObject entity, JObject previous)
: base("PUT", contentType)
{
Set(nameof(id), id);
Set(nameof(entity), entity);
Set(nameof(previous), previous);
}
}
public class HttpPatchContext : HttpPipelineContext
{
public string ContentType => (string)Get("contentType");
public Guid Id => (Guid)Get("id");
public JObject Entity => (JObject)Get("entity");
public JObject Previous => (JObject)Get("previous");
public HttpPatchContext(string contentType, Guid id, JObject entity, JObject previous)
: base("PATCH", contentType)
{
Set(nameof(id), id);
Set(nameof(entity), entity);
Set(nameof(previous), previous);
}
}
public class HttpDeleteContext : HttpPipelineContext
{
public string ContentType => (string)Get("contentType");
public Guid Id => (Guid)Get("id");
public HttpDeleteContext(string contentType, Guid id, JObject previous)
: base("DELETE", contentType)
{
Set(nameof(id), id);
Set(nameof(previous), previous);
}
}
} |
namespace EnergyTrading.MDM.Test.Contracts.Validators
{
using System;
using System.Collections.Generic;
using System.Linq;
using EnergyTrading.MDM.ServiceHost.Unity.Configuration;
using global::MDM.ServiceHost.Unity.Sample.Configuration;
using Microsoft.Practices.Unity;
using NUnit.Framework;
using Moq;
using EnergyTrading.MDM.Contracts.Validators;
using EnergyTrading;
using EnergyTrading.Data;
using EnergyTrading.Validation;
using EnergyTrading.MDM;
using Broker = EnergyTrading.MDM.Contracts.Sample.Broker;
[TestFixture]
public partial class BrokerValidatorFixture : Fixture
{
[Test]
public void ValidatorResolution()
{
var container = CreateContainer();
var meConfig = new SimpleMappingEngineConfiguration(container);
meConfig.Configure();
var repository = new Mock<IRepository>();
container.RegisterInstance(repository.Object);
var config = new BrokerConfiguration(container);
config.Configure();
var validator = container.Resolve<IValidator<Broker>>("broker");
// Assert
Assert.IsNotNull(validator, "Validator resolution failed");
}
[Test]
public void ValidBrokerPasses()
{
// Assert
var start = new DateTime(1999, 1, 1);
var system = new MDM.SourceSystem { Name = "Test" };
var systemList = new List<MDM.SourceSystem> { system };
var systemRepository = new Mock<IRepository>();
var repository = new StubValidatorRepository();
systemRepository.Setup(x => x.Queryable<MDM.SourceSystem>()).Returns(systemList.AsQueryable());
var identifier = new EnergyTrading.Mdm.Contracts.MdmId
{
SystemName = "Test",
Identifier = "1",
StartDate = start.AddHours(-10),
EndDate = start.AddHours(-5)
};
var validatorEngine = new Mock<IValidatorEngine>();
var validator = new BrokerValidator(validatorEngine.Object, repository);
var broker = new Broker { Details = new EnergyTrading.MDM.Contracts.Sample.BrokerDetails{Name = "Test"}, Identifiers = new EnergyTrading.Mdm.Contracts.MdmIdList { identifier } };
this.AddRelatedEntities(broker);
// Act
var violations = new List<IRule>();
var result = validator.IsValid(broker, violations);
// Assert
Assert.IsTrue(result, "Validator failed");
Assert.AreEqual(0, violations.Count, "Violation count differs");
}
[Test]
public void OverlapsRangeFails()
{
// Assert
var start = new DateTime(1999, 1, 1);
var finish = new DateTime(2020, 12, 31);
var validity = new DateRange(start, finish);
var system = new MDM.SourceSystem { Name = "Test" };
var brokerMapping = new PartyRoleMapping { System = system, MappingValue = "1", Validity = validity };
var list = new List<PartyRoleMapping> { brokerMapping };
var repository = new Mock<IRepository>();
repository.Setup(x => x.Queryable<PartyRoleMapping>()).Returns(list.AsQueryable());
var systemList = new List<MDM.SourceSystem>();
var systemRepository = new Mock<IRepository>();
systemRepository.Setup(x => x.Queryable<MDM.SourceSystem>()).Returns(systemList.AsQueryable());
var overlapsRangeIdentifier = new EnergyTrading.Mdm.Contracts.MdmId
{
SystemName = "Test",
Identifier = "1",
StartDate = start.AddHours(10),
EndDate = start.AddHours(15)
};
var identifierValidator = new NexusIdValidator<PartyRoleMapping>(repository.Object);
var validatorEngine = new Mock<IValidatorEngine>();
validatorEngine.Setup(x => x.IsValid(It.IsAny<EnergyTrading.Mdm.Contracts.MdmId>(), It.IsAny<IList<IRule>>()))
.Returns((EnergyTrading.Mdm.Contracts.MdmId x, IList<IRule> y) => identifierValidator.IsValid(x, y));
var validator = new BrokerValidator(validatorEngine.Object, repository.Object);
var broker = new Broker { Identifiers = new EnergyTrading.Mdm.Contracts.MdmIdList { overlapsRangeIdentifier } };
// Act
var violations = new List<IRule>();
var result = validator.IsValid(broker, violations);
// Assert
Assert.IsFalse(result, "Validator succeeded");
}
[Test]
public void BadSystemFails()
{
// Assert
var start = new DateTime(1999, 1, 1);
var finish = new DateTime(2020, 12, 31);
var validity = new DateRange(start, finish);
var system = new MDM.SourceSystem { Name = "Test" };
var brokerMapping = new PartyRoleMapping { System = system, MappingValue = "1", Validity = validity };
var list = new List<PartyRoleMapping> { brokerMapping };
var repository = new Mock<IRepository>();
repository.Setup(x => x.Queryable<PartyRoleMapping>()).Returns(list.AsQueryable());
var badSystemIdentifier = new EnergyTrading.Mdm.Contracts.MdmId
{
SystemName = "Jim",
Identifier = "1",
StartDate = start.AddHours(-10),
EndDate = start.AddHours(-5)
};
var identifierValidator = new NexusIdValidator<PartyRoleMapping>(repository.Object);
var validatorEngine = new Mock<IValidatorEngine>();
validatorEngine.Setup(x => x.IsValid(It.IsAny<EnergyTrading.Mdm.Contracts.MdmId>(), It.IsAny<IList<IRule>>()))
.Returns((EnergyTrading.Mdm.Contracts.MdmId x, IList<IRule> y) => identifierValidator.IsValid(x, y));
var validator = new BrokerValidator(validatorEngine.Object, repository.Object);
var broker = new Broker { Identifiers = new EnergyTrading.Mdm.Contracts.MdmIdList { badSystemIdentifier } };
// Act
var violations = new List<IRule>();
var result = validator.IsValid(broker, violations);
// Assert
Assert.IsFalse(result, "Validator succeeded");
}
partial void AddRelatedEntities(EnergyTrading.MDM.Contracts.Sample.Broker contract);
}
}
|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MemoryStandardStream.Read.cs" company="Naos Project">
// Copyright (c) Naos Project 2019. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Database.Domain
{
using System;
using System.Collections.Generic;
using System.Linq;
using OBeautifulCode.Assertion.Recipes;
using OBeautifulCode.Serialization;
using static System.FormattableString;
public partial class MemoryStandardStream
{
/// <inheritdoc />
public override IReadOnlyCollection<long> Execute(
StandardGetInternalRecordIdsOp operation)
{
throw new NotImplementedException();
/*
operation.MustForArg(nameof(operation)).NotBeNull();
var memoryDatabaseLocator = operation.GetSpecifiedLocatorConverted<MemoryDatabaseLocator>() ?? this.TryGetSingleLocator();
lock (this.streamLock)
{
IReadOnlyCollection<long> ProcessDefaultReturn()
{
switch (operation.RecordNotFoundStrategy)
{
case RecordNotFoundStrategy.ReturnDefault:
return new long[0];
case RecordNotFoundStrategy.Throw:
throw new InvalidOperationException(Invariant($"Expected stream {this.StreamRepresentation} to contain a matching record for {operation}, none was found and {nameof(operation.RecordNotFoundStrategy)} is '{operation.RecordNotFoundStrategy}'."));
default:
throw new NotSupportedException(Invariant($"{nameof(RecordNotFoundStrategy)} {operation.RecordNotFoundStrategy} is not supported."));
}
}
this.locatorToRecordPartitionMap.TryGetValue(memoryDatabaseLocator, out var partition);
if (partition == null)
{
return ProcessDefaultReturn();
}
var result = partition
.Where(
_ => _.Metadata.FuzzyMatchTypes(
operation.RecordFilter.IdTypes,
operation.RecordFilter.ObjectTypes,
operation.RecordFilter.VersionMatchStrategy))
.Select(_ => _.InternalRecordId)
.Union(
operation.RecordFilter.Ids.Any()
partition
.Where(
_ => _.Metadata.FuzzyMatchTypesAndId(
operation.StringSerializedId,
operation.IdentifierType,
operation.ObjectType,
operation.VersionMatchStrategy))
.Select(_ => _.InternalRecordId))
.ToList();
if (result.Any())
{
return result;
}
else
{
return ProcessDefaultReturn();
}
}
*/
}
/// <inheritdoc />
public override IReadOnlyCollection<StringSerializedIdentifier> Execute(
StandardGetDistinctStringSerializedIdsOp operation)
{
operation.MustForArg(nameof(operation)).NotBeNull();
var result = new HashSet<StringSerializedIdentifier>();
lock (this.streamLock)
{
var locators = new List<MemoryDatabaseLocator>();
if (operation.SpecifiedResourceLocator != null)
{
locators.Add(operation.GetSpecifiedLocatorConverted<MemoryDatabaseLocator>());
}
else
{
var allLocators = this.ResourceLocatorProtocols.Execute(new GetAllResourceLocatorsOp());
foreach (var locator in allLocators)
{
locators.Add(locator.ConfirmAndConvert<MemoryDatabaseLocator>());
}
}
foreach (var memoryDatabaseLocator in locators)
{
this.locatorToRecordPartitionMap.TryGetValue(memoryDatabaseLocator, out var partition);
if (partition != null)
{
foreach (var streamRecord in partition)
{
if (streamRecord.Metadata.FuzzyMatchTypes(
operation.RecordFilter.IdTypes,
operation.RecordFilter.ObjectTypes,
operation.RecordFilter.VersionMatchStrategy)
&& ((!operation.RecordFilter.Tags?.Any() ?? true)
|| streamRecord.Metadata.Tags.FuzzyMatchTags(operation.RecordFilter.Tags, operation.RecordFilter.TagMatchStrategy)))
{
result.Add(
new StringSerializedIdentifier(
streamRecord.Metadata.StringSerializedId,
streamRecord.Metadata.TypeRepresentationOfId.GetTypeRepresentationByStrategy(
operation.RecordFilter.VersionMatchStrategy)));
}
}
}
}
}
return result;
}
/// <inheritdoc />
public override StreamRecord Execute(
StandardGetLatestRecordOp operation)
{
throw new NotImplementedException();
/*
operation.MustForArg(nameof(operation)).NotBeNull();
var memoryDatabaseLocator = operation.GetSpecifiedLocatorConverted<MemoryDatabaseLocator>() ?? this.TryGetSingleLocator();
lock (this.streamLock)
{
this.locatorToRecordPartitionMap.TryGetValue(memoryDatabaseLocator, out var partition);
var result = partition?
.OrderByDescending(_ => _.InternalRecordId)
.FirstOrDefault(
_ => _.Metadata.FuzzyMatchTypes(
operation.IdentifierType == null
? null
: new[]
{
operation.IdentifierType,
},
operation.ObjectType == null
? null
: new[]
{
operation.ObjectType,
},
operation.VersionMatchStrategy));
if (result != null)
{
return result;
}
switch (operation.RecordNotFoundStrategy)
{
case RecordNotFoundStrategy.ReturnDefault:
return null;
case RecordNotFoundStrategy.Throw:
throw new InvalidOperationException(Invariant($"Expected stream {this.StreamRepresentation} to contain a matching record for {operation}, none was found and {nameof(operation.RecordNotFoundStrategy)} is '{operation.RecordNotFoundStrategy}'."));
default:
throw new NotSupportedException(Invariant($"{nameof(RecordNotFoundStrategy)} {operation.RecordNotFoundStrategy} is not supported."));
}
}
*/
}
/// <inheritdoc />
public override string Execute(
StandardGetLatestStringSerializedObjectOp operation)
{
operation.MustForArg(nameof(operation)).NotBeNull();
var delegatedOp = new StandardGetLatestRecordOp(
operation.RecordFilter,
operation.RecordNotFoundStrategy,
StreamRecordItemsToInclude.MetadataAndPayload,
operation.SpecifiedResourceLocator);
var record = this.Execute(delegatedOp);
string result;
if (record == null)
{
result = null;
}
else
{
if (record.Payload is StringDescribedSerialization stringDescribedSerialization)
{
result = stringDescribedSerialization.SerializedPayload;
}
else
{
switch (operation.RecordNotFoundStrategy)
{
case RecordNotFoundStrategy.ReturnDefault:
result = null;
break;
case RecordNotFoundStrategy.Throw:
throw new NotSupportedException(Invariant($"record {nameof(SerializationFormat)} not {SerializationFormat.String}, it is {record.Payload.GetSerializationFormat()}, but {nameof(RecordNotFoundStrategy)} is not {nameof(RecordNotFoundStrategy.ReturnDefault)}"));
default:
throw new NotSupportedException(Invariant($"{nameof(RecordNotFoundStrategy)} {operation.RecordNotFoundStrategy} is not supported."));
}
}
}
return result;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Runtime.Remoting.Lifetime;
using System.Windows.Forms;
using System.Drawing;
using System.Linq;
using NationalInstruments;
using NationalInstruments.DAQmx;
using NationalInstruments.VisaNS;
using DAQ;
using DAQ.HAL;
using DAQ.Environment;
using DAQ.TransferCavityLock;
using IMAQ;
using NavAnalysis;
using Newtonsoft.Json;
namespace NavHardwareControl
{
/// <summary>
/// This is the interface to the sympathetic specific hardware.
///
/// Flow chart (under normal conditions): UI -> controller -> hardware. Basically, that's it.
/// Exceptions:
/// -controller can set values displayed on UI (only meant for special cases, like startup or re-loading a saved parameter set)
/// -Some public functions allow the HC to be controlled remotely (see below).
///
/// HardwareState:
/// There are 3 states which the controller can be in: OFF, LOCAL and REMOTE.
/// OFF just means the HC is idle.
/// The state is set to LOCAL when this program is actively upating the state of the hardware. It does this by
/// reading off what's on the UI, finding any discrepancies between the current state of the hardware and the values on the UI
/// and by updating the hardware accordingly.
/// After finishing with the update, it resets the state to OFF.
/// When the state is set to REMOTE, the UI is disactivated. The hardware controller saves all the parameter values upon switching from
/// LOCAL to REMOTE, then does nothing. When switching back, it reinstates the hardware state to what it was before it switched to REMOTE.
/// Use this when you want to control the hardware from somewhere else (e.g. MOTMaster).
///
/// Remoting functions (SetValue):
/// Having said that, you'll notice that there are also public functions for modifying parameter values without putting the HC in REMOTE.
/// I wrote it like this because you want to be able to do two different things:
/// -Have the hardware controller take a back seat and let something else control the hardware for a while (e.g. MOTMaster)
/// This is when you should use the REMOTE state.
/// -You still want the HC to keep track of the hardware (hence remaining in LOCAL), but you want to send commands to it remotely
/// (say from a console) instead of from the UI. This is when you would use the SetValue functions.
///
/// The Hardware Report:
/// The Hardware report is a way of passing a dictionary (gauges, temperature measurements, error signals) to another program
/// (MotMaster, say). MOTMaster can then save the dictionary along with the data. I hope this will help towards answering questions
/// like: "what was the source chamber pressure when we took this data?". At the moment, the hardware state is also included in the report.
///
/// </summary>
public class Controller : MarshalByRefObject, CameraControllable, ExperimentReportable, IHardwareRelease
{
#region Constants
//Put any constants and stuff here
private static string cameraAttributesPath = (string)Environs.FileSystem.Paths["CameraAttributesPath"];
private static string profilesPath = (string)Environs.FileSystem.Paths["settingsPath"] + "\\NavigatorHardwareController\\";
private static Hashtable calibrations = Environs.Hardware.Calibrations;
#endregion
#region Setup
// table of all digital analogTasks
Hashtable digitalTasks = new Hashtable();
HSDIOStaticChannelController HSchannels;
//Cameras
public CameraController ImageController;
public bool cameraLoaded = false;
// Declare that there will be a controlWindow
ControlWindow controlWindow;
//Add the window for analysis
AnalWindow analWindow;
//private bool sHCUIControl;
public enum HCUIControlState { OFF, LOCAL, REMOTE };
public HCUIControlState HCState = new HCUIControlState();
private class cameraNotFoundException : ArgumentException { };
HardwareState stateRecord;
private Dictionary<string, Task> analogTasks;
// without this method, any remote connections to this object will time out after
// five minutes of inactivity.
// It just overrides the lifetime lease system completely.
public override Object InitializeLifetimeService()
{
return null;
}
public void Start()
{
// make the digital analogTasks. The function "CreateDigitalTask" is defined later
//e.g CreateDigitalTask("notEOnOff");
// CreateDigitalTask("eOnOff");
//This is to keep track of the various things which the HC controls.
analogTasks = new Dictionary<string, Task>();
var temp = Environs.Info["HSDIOBoard"];
HSchannels = new HSDIOStaticChannelController((string)Environs.Hardware.GetInfo("HSDIOBoard"), "0-31");
stateRecord = new HardwareState();
CreateHSDigitalTask("do00");
CreateHSDigitalTask("do01");
CreateDigitalTask("testDigitalChannel");
// make the analog output analogTasks. The function "CreateAnalogOutputTask" is defined later
//e.g. bBoxAnalogOutputTask = CreateAnalogOutputTask("b");
// steppingBBiasAnalogOutputTask = CreateAnalogOutputTask("steppingBBias");
CreateAnalogOutputTask("motCoil");
CreateAnalogOutputTask("aom1freq");
CreateAnalogOutputTask("motShutter");
CreateAnalogOutputTask("imagingShutter");
CreateAnalogOutputTask("rfSwitch");
CreateAnalogOutputTask("rfAtten");
//CreateAnalogInputTask("testInput", -10, 10);
// make the control controlWindow
controlWindow = new ControlWindow();
controlWindow.controller = this;
HCState = HCUIControlState.OFF;
Application.Run(controlWindow);
}
// this method runs immediately after the GUI sets up
internal void ControllerLoaded()
{
HardwareState loadedState = loadParameters(profilesPath + "StoppedParameters.json");
if (!loadedState.Equals(stateRecord))
{
foreach (KeyValuePair<string, double> pair in loadedState.analogs)
{
if (stateRecord.analogs.ContainsKey(pair.Key))
{
stateRecord.analogs[pair.Key] = pair.Value;
}
}
foreach (KeyValuePair<string, bool> pair in loadedState.digitals)
{
if (stateRecord.digitals.ContainsKey(pair.Key))
{
stateRecord.digitals[pair.Key] = pair.Value;
}
}
}
setValuesDisplayedOnUI(stateRecord);
ApplyRecordedStateToHardware();
}
public void ControllerStopping()
{
// things like saving parameters, turning things off before quitting the program should go here
StoreParameters(profilesPath + "StoppedParameters.json");
}
#endregion
#region private methods for creating un-timed Tasks/channels
// a list of functions for creating various analogTasks
private void CreateAnalogInputTask(string channel)
{
analogTasks[channel] = new Task(channel);
((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[channel]).AddToTask(
analogTasks[channel],
0,
10
);
analogTasks[channel].Control(TaskAction.Verify);
}
// an overload to specify input range
private void CreateAnalogInputTask(string channel, double lowRange, double highRange)
{
analogTasks[channel] = new Task(channel);
((AnalogInputChannel)Environs.Hardware.AnalogInputChannels[channel]).AddToTask(
analogTasks[channel],
lowRange,
highRange
);
analogTasks[channel].Control(TaskAction.Verify);
}
private void CreateAnalogOutputTask(string channel)
{
stateRecord.analogs[channel] = (double)0.0;
analogTasks[channel] = new Task(channel);
AnalogOutputChannel c = ((AnalogOutputChannel)Environs.Hardware.AnalogOutputChannels[channel]);
c.AddToTask(
analogTasks[channel],
c.RangeLow,
c.RangeHigh
);
analogTasks[channel].Control(TaskAction.Verify);
}
// setting an analog voltage to an output
public void SetAnalogOutput(string channel, double voltage)
{
SetAnalogOutput(channel, voltage, false);
}
//Overload for using a calibration before outputting to hardware
public void SetAnalogOutput(string channelName, double voltage, bool useCalibration)
{
AnalogSingleChannelWriter writer = new AnalogSingleChannelWriter(analogTasks[channelName].Stream);
double output;
if (useCalibration)
{
try
{
output = ((Calibration)calibrations[channelName]).Convert(voltage);
}
catch (DAQ.HAL.Calibration.CalibrationRangeException)
{
MessageBox.Show("The number you have typed is out of the calibrated range! \n Try typing something more sensible.");
throw new CalibrationException();
}
catch
{
MessageBox.Show("Calibration error");
throw new CalibrationException();
}
}
else
{
output = voltage;
}
try
{
writer.WriteSingleSample(true, output);
analogTasks[channelName].Control(TaskAction.Unreserve);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
public class CalibrationException : ArgumentOutOfRangeException { };
// reading an analog voltage from input
public double ReadAnalogInput(string channel)
{
return ReadAnalogInput(channel, false);
}
public double ReadAnalogInput(string channelName, bool useCalibration)
{
AnalogSingleChannelReader reader = new AnalogSingleChannelReader(analogTasks[channelName].Stream);
double val = reader.ReadSingleSample();
analogTasks[channelName].Control(TaskAction.Unreserve);
if (useCalibration)
{
try
{
return ((Calibration)calibrations[channelName]).Convert(val);
}
catch
{
MessageBox.Show("Calibration error");
return val;
}
}
else
{
return val;
}
}
// overload for reading multiple samples
public double ReadAnalogInput(string channel, double sampleRate, int numOfSamples, bool useCalibration)
{
//Configure the timing parameters of the task
analogTasks[channel].Timing.ConfigureSampleClock("", sampleRate,
SampleClockActiveEdge.Rising, SampleQuantityMode.FiniteSamples, numOfSamples);
//Read in multiple samples
AnalogSingleChannelReader reader = new AnalogSingleChannelReader(analogTasks[channel].Stream);
double[] valArray = reader.ReadMultiSample(numOfSamples);
analogTasks[channel].Control(TaskAction.Unreserve);
//Calculate the average of the samples
double sum = 0;
for (int j = 0; j < numOfSamples; j++)
{
sum = sum + valArray[j];
}
double val = sum / numOfSamples;
if (useCalibration)
{
try
{
return ((Calibration)calibrations[channel]).Convert(val);
}
catch
{
MessageBox.Show("Calibration error");
return val;
}
}
else
{
return val;
}
}
private void CreateDigitalTask(String name)
{
stateRecord.digitals[name] = false;
Task digitalTask = new Task(name);
((DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels[name]).AddToTask(digitalTask);
digitalTask.Control(TaskAction.Verify);
digitalTasks.Add(name, digitalTask);
}
public void SetDigitalLine(string name, bool value)
{
Task digitalTask = ((Task)digitalTasks[name]);
DigitalSingleChannelWriter writer = new DigitalSingleChannelWriter(digitalTask.Stream);
writer.WriteSingleSampleSingleLine(true, value);
digitalTask.Control(TaskAction.Unreserve);
}
private void CreateHSDigitalTask(String name)
{
DigitalOutputChannel channel = (DigitalOutputChannel)Environs.Hardware.DigitalOutputChannels[name];
stateRecord.HSdigitals[name] = false;
HSchannels.CreateHSDigitalTask(name, channel.BitNumber);
}
public void SetHSDigitalLine(string name, bool value)
{
HSchannels.SetHSDigitalLine(name, value);
}
#endregion
#region keeping track of the state of the hardware!
/// <summary>
/// There's this thing I've called a hardware state. It's something which keeps track of digital and analog values.
/// I then have something called stateRecord (defines above as an instance of hardwareState) which keeps track of
/// what the hardware is doing.
/// Anytime the hardware gets modified by this program, the stateRecord get updated. Don't hack this.
/// It's useful to know what the hardware is doing at all times.
/// When switching to REMOTE, the updates no longer happen. That's why we store the state before switching to REMOTE and apply the state
/// back again when returning to LOCAL.
/// </summary>
[Serializable]
public class HardwareState
{
public Dictionary<string, double> analogs;
public Dictionary<string, bool> digitals;
public Dictionary<string, bool> HSdigitals;
public HardwareState()
{
analogs = new Dictionary<string, double>();
digitals = new Dictionary<string, bool>();
HSdigitals = new Dictionary<string, bool>();
}
}
#endregion
#region Saving and loading experimental parameters
// Saving the parameters when closing the controller
public void SaveParametersWithDialog()
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "shc parameters|*.json";
saveFileDialog1.Title = "Save parameters";
saveFileDialog1.InitialDirectory = profilesPath;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if (saveFileDialog1.FileName != "")
{
StoreParameters(saveFileDialog1.FileName);
}
}
}
private void StoreParameters(String dataStoreFilePath)
{
stateRecord = readValuesOnUI();
string record = JsonConvert.SerializeObject(stateRecord);
System.IO.File.WriteAllText(dataStoreFilePath, record);
controlWindow.WriteToConsole("Saved parameters to " + dataStoreFilePath);
}
//Load parameters when opening the controller
public void LoadParametersWithDialog()
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Nav HC|*.json";
dialog.Title = "Load parameters";
dialog.InitialDirectory = profilesPath;
dialog.ShowDialog();
if (dialog.FileName != "") stateRecord = loadParameters(dialog.FileName);
setValuesDisplayedOnUI(stateRecord);
controlWindow.WriteToConsole("Parameters loaded from " + dialog.FileName);
}
private HardwareState loadParameters(String dataStoreFilePath)
{
if (!File.Exists(dataStoreFilePath))
{
controlWindow.WriteToConsole("Can't Find File");
return stateRecord;
}
HardwareState state;
using (StreamReader r = new StreamReader(dataStoreFilePath))
{
string json = r.ReadToEnd();
state = JsonConvert.DeserializeObject<HardwareState>(json);
}
return state;
}
#endregion
#region Controlling hardware and UI.
//This gets/sets the values on the GUI panel
#region Updating the hardware
public void ApplyRecordedStateToHardware()
{
applyToHardware(stateRecord);
}
public void UpdateHardware()
{
HardwareState uiState = readValuesOnUI();
DoUpdateHardware(uiState);
}
public void DoUpdateHardware(HardwareState newState)
{
HardwareState changes = getDiscrepancies(stateRecord, newState);
applyToHardware(changes);
updateStateRecord(changes);
setValuesDisplayedOnUI(stateRecord);
}
private void applyToHardware(HardwareState state)
{
if (state.analogs.Count != 0 || state.digitals.Count != 0 || state.HSdigitals.Count != 0)
{
if (HCState == HCUIControlState.OFF)
{
HCState = HCUIControlState.LOCAL;
controlWindow.UpdateUIState(HCState);
applyAnalogs(state);
applyDigitals(state);
applyHSDigitals(state);
HCState = HCUIControlState.OFF;
controlWindow.UpdateUIState(HCState);
}
}
else
{
controlWindow.WriteToConsole("The values on the UI are identical to those on the controller's records. Hardware must be up to date.");
}
}
private HardwareState getDiscrepancies(HardwareState oldState, HardwareState newState)
{
HardwareState state = new HardwareState();
state.analogs = new Dictionary<string, double>();
state.digitals = new Dictionary<string, bool>();
state.HSdigitals = new Dictionary<string, bool>();
foreach(KeyValuePair<string, double> pairs in oldState.analogs)
{
if (oldState.analogs[pairs.Key] != newState.analogs[pairs.Key])
{
state.analogs[pairs.Key] = newState.analogs[pairs.Key];
}
}
foreach (KeyValuePair<string, bool> pairs in oldState.digitals)
{
if (oldState.digitals[pairs.Key] != newState.digitals[pairs.Key])
{
state.digitals[pairs.Key] = newState.digitals[pairs.Key];
}
}
foreach (KeyValuePair<string, bool> pairs in oldState.HSdigitals)
{
if (oldState.HSdigitals[pairs.Key] != newState.HSdigitals[pairs.Key])
{
state.HSdigitals[pairs.Key] = newState.HSdigitals[pairs.Key];
}
}
return state;
}
private void updateStateRecord(HardwareState changes)
{
foreach (KeyValuePair<string, double> pairs in changes.analogs)
{
stateRecord.analogs[pairs.Key] = changes.analogs[pairs.Key];
}
foreach (KeyValuePair<string, bool> pairs in changes.digitals)
{
stateRecord.digitals[pairs.Key] = changes.digitals[pairs.Key];
}
foreach (KeyValuePair<string, bool> pairs in changes.HSdigitals)
{
stateRecord.HSdigitals[pairs.Key] = changes.HSdigitals[pairs.Key];
}
}
private void applyAnalogs(HardwareState state)
{
List<string> toRemove = new List<string>(); //In case of errors, keep track of things to delete from the list of changes.
foreach (KeyValuePair<string, double> pairs in state.analogs)
{
try
{
if (calibrations.ContainsKey(pairs.Key))
{
SetAnalogOutput(pairs.Key, pairs.Value, true);
}
else
{
SetAnalogOutput(pairs.Key, pairs.Value);
}
controlWindow.WriteToConsole("Set channel '" + pairs.Key.ToString() + "' to " + pairs.Value.ToString());
}
catch (CalibrationException)
{
controlWindow.WriteToConsole("Failed to set channel '"+ pairs.Key.ToString() + "' to new value");
toRemove.Add(pairs.Key);
}
}
foreach (string s in toRemove) //Remove those from the list of changes, as nothing was done to the Hardware.
{
state.analogs.Remove(s);
}
}
private void applyDigitals(HardwareState state)
{
foreach (KeyValuePair<string, bool> pairs in state.digitals)
{
SetDigitalLine(pairs.Key, pairs.Value);
controlWindow.WriteToConsole("Set channel '" + pairs.Key.ToString() + "' to " + pairs.Value.ToString());
}
}
private void applyHSDigitals(HardwareState state)
{
foreach (KeyValuePair<string, bool> pairs in state.HSdigitals)
{
SetHSDigitalLine(pairs.Key, pairs.Value);
controlWindow.WriteToConsole("Set channel '" + pairs.Key.ToString() + "' to " + pairs.Value.ToString());
}
}
#endregion
#region Reading and Writing to UI
private HardwareState readValuesOnUI()
{
HardwareState state = new HardwareState();
state.analogs = readUIAnalogs(stateRecord.analogs.Keys);
state.digitals = readUIDigitals(stateRecord.digitals.Keys);
state.HSdigitals = readUIHSDigitals(stateRecord.HSdigitals.Keys);
return state;
}
private Dictionary<string, double> readUIAnalogs(Dictionary<string, double>.KeyCollection keys)
{
Dictionary<string, double> analogs = new Dictionary<string, double>();
string[] keyArray = new string[keys.Count];
keys.CopyTo(keyArray, 0);
for (int i = 0; i < keys.Count; i++)
{
analogs[keyArray[i]] = controlWindow.ReadAnalog(keyArray[i]);
}
return analogs;
}
private Dictionary<string, bool> readUIDigitals(Dictionary<string, bool>.KeyCollection keys)
{
Dictionary<string, bool> digitals = new Dictionary<string,bool>();
string[] keyArray = new string[keys.Count];
keys.CopyTo(keyArray, 0);
for (int i = 0; i < keys.Count; i++)
{
digitals[keyArray[i]] = controlWindow.ReadDigital(keyArray[i]);
}
return digitals;
}
private Dictionary<string, bool> readUIHSDigitals(Dictionary<string, bool>.KeyCollection keys)
{
Dictionary<string, bool> digitals = new Dictionary<string, bool>();
string[] keyArray = new string[keys.Count];
keys.CopyTo(keyArray, 0);
for (int i = 0; i < keys.Count; i++)
{
digitals[keyArray[i]] = controlWindow.ReadHSDigital(keyArray[i]);
}
return digitals;
}
private void setValuesDisplayedOnUI(HardwareState state)
{
setUIAnalogs(state);
setUIDigitals(state);
setUIHSDigitals(state);
}
private void setUIAnalogs(HardwareState state)
{
foreach (KeyValuePair<string, double> pairs in state.analogs)
{
try
{
controlWindow.SetAnalog(pairs.Key, (double)pairs.Value);
}
catch
{
MessageBox.Show("Some parameters couldn't be loaded, check the parameter file in the settings folder");
}
}
}
private void setUIDigitals(HardwareState state)
{
foreach (KeyValuePair<string, bool> pairs in state.digitals)
{
controlWindow.SetDigital(pairs.Key, (bool)pairs.Value);
}
}
private void setUIHSDigitals(HardwareState state)
{
foreach (KeyValuePair<string, bool> pairs in state.HSdigitals)
{
controlWindow.SetHSDigital(pairs.Key, (bool)pairs.Value);
}
}
#endregion
#region Remoting stuff
/// <summary>
/// This is used when you want another program to take control of some/all of the hardware. The hc then just saves the
/// last hardware state, then prevents you from making any changes to the UI. Use this if your other program wants direct control of hardware.
/// </summary>
public void StartRemoteControl()
{
if (HCState == HCUIControlState.OFF)
{
if (!ImageController.IsCameraFree())
{
StopCameraStream();
}
StoreParameters(profilesPath + "tempParameters.json");
HCState = HCUIControlState.REMOTE;
controlWindow.UpdateUIState(HCState);
controlWindow.WriteToConsole("Remoting Started!");
}
else
{
MessageBox.Show("Controller is busy");
}
}
public void StopRemoteControl()
{
try
{
controlWindow.WriteToConsole("Remoting Stopped!");
setValuesDisplayedOnUI(loadParameters(profilesPath + "tempParameters.json"));
if (System.IO.File.Exists(profilesPath + "tempParameters.json"))
{
System.IO.File.Delete(profilesPath + "tempParameters.json");
}
}
catch (Exception)
{
controlWindow.WriteToConsole("Unable to load Parameters.");
}
HCState = HCUIControlState.OFF;
controlWindow.UpdateUIState(HCState);
ApplyRecordedStateToHardware();
}
/// <summary>
/// These SetValue functions are for giving commands to the hc from another program, while keeping the hc in control of hardware.
/// Use this if you want the HC to keep control, but you want to control the HC from some other program
/// </summary>
public void SetValue(string channel, double value)
{
HCState = HCUIControlState.LOCAL;
stateRecord.analogs[channel] = value;
SetAnalogOutput(channel, value, false);
setValuesDisplayedOnUI(stateRecord);
HCState = HCUIControlState.OFF;
}
public void SetValue(string channel, double value, bool useCalibration)
{
stateRecord.analogs[channel] = value;
HCState = HCUIControlState.LOCAL;
SetAnalogOutput(channel, value, useCalibration);
setValuesDisplayedOnUI(stateRecord);
HCState = HCUIControlState.OFF;
}
public void SetValue(string channel, bool value)
{
HCState = HCUIControlState.LOCAL;
if (stateRecord.digitals.ContainsKey(channel))
{
stateRecord.digitals[channel] = value;
SetDigitalLine(channel, value);
setValuesDisplayedOnUI(stateRecord);
}
else if (stateRecord.HSdigitals.ContainsKey(channel))
{
stateRecord.digitals[channel] = value;
SetHSDigitalLine(channel, value);
setValuesDisplayedOnUI(stateRecord);
}
HCState = HCUIControlState.OFF;
}
#endregion
#endregion
#region Local camera control
public void StartCameraControl()
{
try
{
ImageController = new CameraController("cam0");
ImageController.Initialize();
ImageController.SetCameraAttributes(cameraAttributesPath);
ImageController.PrintCameraAttributesToConsole();
cameraLoaded = true;
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Camera Initialization Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.Exit();
}
}
public void CameraStream()
{
try
{
ImageController.Stream(cameraAttributesPath);
}
catch { }
}
public void StopCameraStream()
{
try
{
ImageController.StopStream();
}
catch { }
}
public void CameraSnapshot()
{
try
{
ImageController.SingleSnapshot(cameraAttributesPath);
}
catch { }
}
public ushort[,] TempCameraSnapshot()
{
return ImageController.SingleSnapshot(cameraAttributesPath);
}
#endregion
#region Release/Reclaim Hardware
public void ReleaseHardware()
{
HSchannels.ReleaseHardware();
}
public void ReclaimHardware()
{
HSchannels.ReclaimHardware();
}
#endregion
#region Remote Camera Control
//Written for taking images triggered by TTL. This "Arm" sets the camera so it's expecting a TTL.
public ushort[,] GrabSingleImage(string cameraAttributesPath)
{
return ImageController.SingleSnapshot(cameraAttributesPath);
}
public ushort[][,] GrabMultipleImages(string cameraAttributesPath, int numberOfShots)
{
try
{
ushort[][,] images = ImageController.MultipleSnapshot(cameraAttributesPath, numberOfShots);
return images;
}
catch (TimeoutException)
{
FinishRemoteCameraControl();
return null;
}
}
public bool IsReadyForAcquisition()
{
return ImageController.IsReadyForAcqisition();
}
public void PrepareRemoteCameraControl()
{
StartRemoteControl();
}
public void FinishRemoteCameraControl()
{
StopRemoteControl();
}
public bool doesCameraExist()
{
return cameraLoaded;
}
#endregion
#region Saving Images
public void SaveImageWithDialog()
{
ImageController.SaveImageWithDialog();
}
public void SaveImage(string path)
{
ImageController.SaveImage(path);
}
#endregion
#region Hardware Monitor
#region Remote Access for Hardware Monitor
public Dictionary<String, Object> GetExperimentReport()
{
Dictionary<String, Object> report = new Dictionary<String, Object>();
report["testReport"] = "Report?";
foreach (KeyValuePair<string, double> pair in stateRecord.analogs)
{
report[pair.Key] = pair.Value;
}
foreach (KeyValuePair<string, bool> pair in stateRecord.digitals)
{
report[pair.Key] = pair.Value;
}
return report;
}
#endregion
#endregion
#region Stuff To Access from python
///In theory you can access any public method from python.
///In practice we only really want to access a small number of them.
///This region contains them. Hopefully by only putting functions in here we
///want to use we can get an idea of what, exactly we want this control
///software to do.
///
public void RemoteTest(object input)
{
controlWindow.WriteToConsole(input.ToString());
}
public string RemoteSetChannel(String channelName, object value)
{
if (digitalTasks.Contains(channelName))
{
if (value.GetType() != typeof(bool))
{
return "Can't set digital channel to non bool value";
}
HardwareState state = readValuesOnUI();
state.digitals[channelName] = (bool)value;
DoUpdateHardware(state);
return "";
}
if (analogTasks.ContainsKey(channelName))
{
float outValue;
bool didItParse = float.TryParse(value.ToString(), out outValue);
if (!didItParse)
{
return "Cant't set an analog channel to non numeric value";
}
HardwareState state = readValuesOnUI();
state.analogs[channelName] = outValue;
DoUpdateHardware(state);
return "";
}
return "Channel name not found";
}
public string[] RemoteGetChannels()
{
List<string> channels = new List<string>();
channels.AddRange(stateRecord.digitals.Keys);
channels.AddRange(stateRecord.analogs.Keys);
return channels.ToArray();
}
public string RemoteLoadParameters(string file)
{
if (!File.Exists(file))
{
return "file doesn't exist";
}
stateRecord = loadParameters(file);
setValuesDisplayedOnUI(stateRecord);
controlWindow.WriteToConsole("Loaded parameters from " + file);
return "";
}
public void CloseIt()
{
controlWindow.Close();
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Icy.Util;
namespace Icy.Database.Query
{
public class JoinClauseOptions{
public object first;
public string operator1;
public object second;
public string boolean;
public bool where;
public bool nested;
public JoinClause join;
}
// 4d8e4bb Dec 28, 2015
public class JoinClause
{
/**
* The type of join being performed.
*
* @var string
*/
public string _type;
/**
* The table the join clause is joining to.
*
* @var string
*/
public string _table;
/**
* The "on" clauses for the join.
*
* @var array
*/
public JoinClauseOptions[] _clauses = new JoinClauseOptions[0];
/**
* The "on" bindings for the join.
*
* @var array
*/
public object[] _bindings = new object[0];
/**
* Create a new join clause instance.
*
* @param string type
* @param string table
* @return void
*/
public JoinClause(string type, string table)
{
this._type = type;
this._table = table;
}
/**
* Add an "on" clause to the join.
*
* On clauses can be chained, e.g.
*
* join.on('contacts.user_id', '=', 'users.id')
* .on('contacts.info_id', '=', 'info.id')
*
* will produce the following SQL:
*
* on `contacts`.`user_id` = `users`.`id` and `contacts`.`info_id` = `info`.`id`
*
* @param string first
* @param string|null operator
* @param string|null second
* @param string boolean
* @param bool where
* @return this
*/
public JoinClause on(Action<JoinClause> first, string operator1 = null, object second = null, string boolean = "and", bool where = false)
{
return this.nest(first, boolean);
}
public JoinClause on(object first, string operator1 = null, object second = null, string boolean = "and", bool where = false)
{
if (where)
{
this._bindings = ArrayUtil.push(this._bindings, second);
}
if(where && (operator1 == "in" || operator1 == "not in") && (second is IList<object> || second is object[])){
second = ((IList<object>)second).Count;
}
JoinClauseOptions options = new JoinClauseOptions();
options.first = first;
options.operator1 = operator1;
options.second = second;
options.boolean = boolean;
options.where = where;
options.nested = false;
this._clauses = ArrayUtil.push(this._clauses, options);
return this;
}
/**
* Add an "or on" clause to the join.
*
* @param string first
* @param string|null operator
* @param string|null second
* @return \Illuminate\Database\Query\JoinClause
*/
public JoinClause orOn(object first, string operator1 = null, object second = null)
{
return this.on(first, operator1, second, "or");
}
/**
* Add an "on where" clause to the join.
*
* @param string first
* @param string|null operator
* @param string|null second
* @param string boolean
* @return \Illuminate\Database\Query\JoinClause
*/
public JoinClause where(object first, string operator1 = null, object second = null, string boolean = "and")
{
return this.on(first, operator1, second, boolean, true);
}
/**
* Add an "or on where" clause to the join.
*
* @param string first
* @param string|null operator
* @param string|null second
* @return \Illuminate\Database\Query\JoinClause
*/
public JoinClause orWhere(object first, string operator1 = null, object second = null)
{
return this.on(first, operator1, second, "or", true);
}
/**
* Add an "on where is null" clause to the join.
*
* @param string column
* @param string boolean
* @return \Illuminate\Database\Query\JoinClause
*/
public JoinClause whereNull(object column, string boolean = "and")
{
return this.on(column, "is", new Expression("null"), boolean, false);
}
/**
* Add an "or on where is null" clause to the join.
*
* @param string column
* @return \Illuminate\Database\Query\JoinClause
*/
public JoinClause orWhereNull(object column)
{
return this.whereNull(column, "or");
}
/**
* Add an "on where is not null" clause to the join.
*
* @param string column
* @param string boolean
* @return \Illuminate\Database\Query\JoinClause
*/
public JoinClause whereNotNull(object column, string boolean = "and")
{
return this.on(column, "is", new Expression("not null"), boolean, false);
}
/**
* Add an "or on where is not null" clause to the join.
*
* @param string column
* @return \Illuminate\Database\Query\JoinClause
*/
public JoinClause orWhereNotNull(object column)
{
return this.whereNotNull(column, "or");
}
/**
* Add an "on where in (...)" clause to the join.
*
* @param string column
* @param array values
* @return \Illuminate\Database\Query\JoinClause
*/
public JoinClause whereIn(object column, object[] values)
{
return this.on(column, "in", values, "and", true);
}
/**
* Add an "on where not in (...)" clause to the join.
*
* @param string column
* @param array values
* @return \Illuminate\Database\Query\JoinClause
*/
public JoinClause whereNotIn(object column, object[] values)
{
return this.on(column, "not in", values, "and", true);
}
/**
* Add an "or on where in (...)" clause to the join.
*
* @param string column
* @param array values
* @return \Illuminate\Database\Query\JoinClause
*/
public JoinClause orWhereIn(object column, object[] values)
{
return this.on(column, "in", values, "or", true);
}
/**
* Add an "or on where not in (...)" clause to the join.
*
* @param string column
* @param array values
* @return \Illuminate\Database\Query\JoinClause
*/
public JoinClause orWhereNotIn(object column, object[] values)
{
return this.on(column, "not in", values, "or", true);
}
/**
* Add a nested where statement to the query.
*
* @param \Closure $callback
* @param string $boolean
* @return \Illuminate\Database\Query\JoinClause
*/
public JoinClause nest(Action<JoinClause> callback, string boolean = "and")
{
JoinClause join = new JoinClause(this._type, this._table);
callback(join);
if (join._clauses.Length > 0) {
JoinClauseOptions options = new JoinClauseOptions();
options.nested = true;
options.join = join;
options.boolean = boolean;
this._clauses = ArrayUtil.push(this._clauses, options);
this._bindings = ArrayUtil.concat(this._bindings, join._bindings);
}
return this;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
namespace LibGit2Sharp.Core
{
/// <summary>
/// Ensure input parameters
/// </summary>
[DebuggerStepThrough]
internal static class Ensure
{
/// <summary>
/// Checks an argument to ensure it isn't null.
/// </summary>
/// <param name="argumentValue">The argument value to check.</param>
/// <param name="argumentName">The name of the argument.</param>
public static void ArgumentNotNull(object argumentValue, string argumentName)
{
if (argumentValue == null)
{
throw new ArgumentNullException(argumentName);
}
}
/// <summary>
/// Checks an array argument to ensure it isn't null or empty.
/// </summary>
/// <param name="argumentValue">The argument value to check.</param>
/// <param name="argumentName">The name of the argument.</param>
public static void ArgumentNotNullOrEmptyEnumerable<T>(IEnumerable<T> argumentValue, string argumentName)
{
ArgumentNotNull(argumentValue, argumentName);
if (!argumentValue.Any())
{
throw new ArgumentException("Enumerable cannot be empty", argumentName);
}
}
/// <summary>
/// Checks a string argument to ensure it isn't null or empty.
/// </summary>
/// <param name="argumentValue">The argument value to check.</param>
/// <param name="argumentName">The name of the argument.</param>
public static void ArgumentNotNullOrEmptyString(string argumentValue, string argumentName)
{
ArgumentNotNull(argumentValue, argumentName);
if (String.IsNullOrWhiteSpace (argumentValue))
{
throw new ArgumentException("String cannot be empty", argumentName);
}
}
/// <summary>
/// Checks a string argument to ensure it doesn't contain a zero byte.
/// </summary>
/// <param name="argumentValue">The argument value to check.</param>
/// <param name="argumentName">The name of the argument.</param>
public static void ArgumentDoesNotContainZeroByte(string argumentValue, string argumentName)
{
if (string.IsNullOrEmpty(argumentValue))
{
return;
}
int zeroPos = -1;
for (var i = 0; i < argumentValue.Length; i++)
{
if (argumentValue[i] == '\0')
{
zeroPos = i;
break;
}
}
if (zeroPos == -1)
{
return;
}
throw new ArgumentException(
string.Format(CultureInfo.InvariantCulture,
"Zero bytes ('\\0') are not allowed. A zero byte has been found at position {0}.", zeroPos), argumentName);
}
private static readonly Dictionary<GitErrorCode, Func<string, GitErrorCode, GitErrorCategory, LibGit2SharpException>>
GitErrorsToLibGit2SharpExceptions =
new Dictionary<GitErrorCode, Func<string, GitErrorCode, GitErrorCategory, LibGit2SharpException>>
{
{ GitErrorCode.User, (m, r, c) => new UserCancelledException(m, r, c) },
{ GitErrorCode.BareRepo, (m, r, c) => new BareRepositoryException(m, r, c) },
{ GitErrorCode.Exists, (m, r, c) => new NameConflictException(m, r, c) },
{ GitErrorCode.InvalidSpecification, (m, r, c) => new InvalidSpecificationException(m, r, c) },
{ GitErrorCode.UnmergedEntries, (m, r, c) => new UnmergedIndexEntriesException(m, r, c) },
{ GitErrorCode.NonFastForward, (m, r, c) => new NonFastForwardException(m, r, c) },
{ GitErrorCode.MergeConflict, (m, r, c) => new MergeConflictException(m, r, c) },
{ GitErrorCode.LockedFile, (m, r, c) => new LockedFileException(m, r, c) },
{ GitErrorCode.NotFound, (m, r, c) => new NotFoundException(m, r, c) },
{ GitErrorCode.Peel, (m, r, c) => new PeelException(m, r, c) },
};
private static void HandleError(int result)
{
string errorMessage;
GitError error = NativeMethods.giterr_last().MarshalAsGitError();
if (error == null)
{
error = new GitError { Category = GitErrorCategory.Unknown, Message = IntPtr.Zero };
errorMessage = "No error message has been provided by the native library";
}
else
{
errorMessage = LaxUtf8Marshaler.FromNative(error.Message);
}
Func<string, GitErrorCode, GitErrorCategory, LibGit2SharpException> exceptionBuilder;
if (!GitErrorsToLibGit2SharpExceptions.TryGetValue((GitErrorCode)result, out exceptionBuilder))
{
exceptionBuilder = (m, r, c) => new LibGit2SharpException(m, r, c);
}
throw exceptionBuilder(errorMessage, (GitErrorCode)result, error.Category);
}
/// <summary>
/// Check that the result of a C call was successful
/// <para>
/// The native function is expected to return strictly 0 for
/// success or a negative value in the case of failure.
/// </para>
/// </summary>
/// <param name="result">The result to examine.</param>
public static void ZeroResult(int result)
{
if (result == (int)GitErrorCode.Ok)
{
return;
}
HandleError(result);
}
/// <summary>
/// Check that the result of a C call returns a boolean value.
/// <para>
/// The native function is expected to return strictly 0 or 1.
/// </para>
/// </summary>
/// <param name="result">The result to examine.</param>
public static void BooleanResult(int result)
{
if (result == 0 || result == 1)
{
return;
}
HandleError(result);
}
/// <summary>
/// Check that the result of a C call that returns an integer
/// value was successful.
/// <para>
/// The native function is expected to return 0 or a positive
/// value for success or a negative value in the case of failure.
/// </para>
/// </summary>
/// <param name="result">The result to examine.</param>
public static void Int32Result(int result)
{
if (result >= (int)GitErrorCode.Ok)
{
return;
}
HandleError(result);
}
/// <summary>
/// Checks an argument by applying provided checker.
/// </summary>
/// <param name="argumentValue">The argument value to check.</param>
/// <param name="checker">The predicate which has to be satisfied</param>
/// <param name="argumentName">The name of the argument.</param>
public static void ArgumentConformsTo<T>(T argumentValue, Func<T, bool> checker, string argumentName)
{
if (checker(argumentValue))
{
return;
}
throw new ArgumentException(argumentName);
}
/// <summary>
/// Checks an argument is a positive integer.
/// </summary>
/// <param name="argumentValue">The argument value to check.</param>
/// <param name="argumentName">The name of the argument.</param>
public static void ArgumentPositiveInt32(long argumentValue, string argumentName)
{
if (argumentValue >= 0 && argumentValue <= uint.MaxValue)
{
return;
}
throw new ArgumentException(argumentName);
}
/// <summary>
/// Check that the result of a C call that returns a non-null GitObject
/// using the default exception builder.
/// <para>
/// The native function is expected to return a valid object value.
/// </para>
/// </summary>
/// <param name="gitObject">The <see cref="GitObject"/> to examine.</param>
/// <param name="identifier">The <see cref="GitObject"/> identifier to examine.</param>
public static void GitObjectIsNotNull(GitObject gitObject, string identifier)
{
Func<string, LibGit2SharpException> exceptionBuilder;
if (string.Equals("HEAD", identifier, StringComparison.Ordinal))
{
exceptionBuilder = m => new UnbornBranchException(m);
}
else
{
exceptionBuilder = m => new NotFoundException(m);
}
GitObjectIsNotNull(gitObject, identifier, exceptionBuilder);
}
/// <summary>
/// Check that the result of a C call that returns a non-null GitObject
/// using the default exception builder.
/// <para>
/// The native function is expected to return a valid object value.
/// </para>
/// </summary>
/// <param name="gitObject">The <see cref="GitObject"/> to examine.</param>
/// <param name="identifier">The <see cref="GitObject"/> identifier to examine.</param>
/// <param name="exceptionBuilder">The builder which constructs an <see cref="LibGit2SharpException"/> from a message.</param>
public static void GitObjectIsNotNull(
GitObject gitObject,
string identifier,
Func<string, LibGit2SharpException> exceptionBuilder)
{
if (gitObject != null)
{
return;
}
throw exceptionBuilder(string.Format(CultureInfo.InvariantCulture,
"No valid git object identified by '{0}' exists in the repository.",
identifier));
}
}
}
|
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using AgileSqlClub.MergeUi.DacServices;
using AgileSqlClub.MergeUi.Merge;
using AgileSqlClub.MergeUi.Metadata;
using AgileSqlClub.MergeUi.PackagePlumbing;
using AgileSqlClub.MergeUi.VSServices;
using MessageBox = System.Windows.Forms.MessageBox;
namespace AgileSqlClub.MergeUi.UI
{
public static class DebugLogging
{
public static bool Enable = true;
}
public partial class MyControl : UserControl, IStatus
{
private bool _currentDataGridDirty;
private VsProject _currentProject;
private ISchema _currentSchema;
private ITable _currentTable;
private ISolution _solution;
public MyControl()
{
InitializeComponent();
//Refresh();
}
public void SetStatus(string message)
{
Dispatcher.InvokeAsync(() => { LastStatusMessage.Text = message; });
}
private void Refresh()
{
Task.Run(() => DoRefresh());
}
private void DoRefresh()
{
Dispatcher.Invoke(() => { DebugLogging.Enable = Logging.IsChecked.Value; });
try
{
if (_currentDataGridDirty)
{
if (!CheckSaveChanges())
{
return;
}
}
var cursor = Cursors.Arrow;
Dispatcher.Invoke(() =>
{
cursor = Cursor;
RefreshButton.IsEnabled = false;
Projects.ItemsSource = null;
Schemas.ItemsSource = null;
Tables.ItemsSource = null;
DataGrid.DataContext = null;
Cursor = Cursors.Wait;
});
_solution = new SolutionParser(new ProjectEnumerator(), new DacParserBuilder(), this);
Dispatcher.Invoke(() =>
{
Projects.ItemsSource = _solution.GetProjects();
Cursor = cursor;
RefreshButton.IsEnabled = true;
});
}
catch (Exception e)
{
Dispatcher.Invoke(() => { LastStatusMessage.Text = "Error see output window"; });
OutputWindowMessage.WriteMessage("Error Enumerating projects:");
OutputWindowMessage.WriteMessage(e.Message);
}
}
[SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions")]
private void button1_Click(object sender, RoutedEventArgs e)
{
Refresh();
}
private void Projects_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
if (null == Projects.SelectedValue)
return;
var projectName = Projects.SelectedValue.ToString();
if (String.IsNullOrEmpty(projectName))
return;
Schemas.ItemsSource = null;
Tables.ItemsSource = null;
_currentProject = _solution.GetProject(projectName);
if (string.IsNullOrEmpty(_currentProject.GetScript(ScriptType.PreDeploy)) &&
string.IsNullOrEmpty(_currentProject.GetScript(ScriptType.PostDeploy)))
{
MessageBox.Show(
"The project needs a post deploy script - add one anywhere in the project and refresh", "MergeUi");
return;
}
LastBuildTime.Text = string.Format("Last Dacpac Build Time: {0}", _currentProject.GetLastBuildTime());
Schemas.ItemsSource = _currentProject.GetSchemas();
}
catch (Exception ex)
{
Dispatcher.Invoke(() => { LastStatusMessage.Text = "Error see output window "; });
OutputWindowMessage.WriteMessage("Error reading project: {0}", ex.Message);
}
}
private void Schemas_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
if (null == Schemas.SelectedValue)
return;
var schemaName = Schemas.SelectedValue.ToString();
if (String.IsNullOrEmpty(schemaName))
return;
_currentSchema = _currentProject.GetSchema(schemaName);
Tables.ItemsSource = _currentSchema.GetTables();
}
catch (Exception ex)
{
Dispatcher.Invoke(() => { LastStatusMessage.Text = "Error see output window"; });
OutputWindowMessage.WriteMessage("Error selecting schema:");
OutputWindowMessage.WriteMessage(ex.Message);
}
}
private void Tables_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
if (null == Tables.SelectedValue)
return;
var tableName = Tables.SelectedValue.ToString();
if (String.IsNullOrEmpty(tableName))
return;
_currentTable = _currentSchema.GetTable(tableName);
if (_currentTable.Data == null)
{
_currentTable.Data = new DataTableBuilder(tableName, _currentTable.Columns).Get();
}
DataGrid.DataContext = _currentTable.Data.DefaultView;
//TODO -= check for null and start adding a datatable when building the table (maybe need a lazy loading)
//we also need a repository of merge statements which is the on disk representation so we can grab those
//if they exist or just create a new one - then save them back and
}
catch (Exception ex)
{
Dispatcher.Invoke(() => { LastStatusMessage.Text = "Error Enumerating projects: " + ex.Message; });
OutputWindowMessage.WriteMessage("Error selecting table ({0}-):",
_currentTable == null ? "null" : _currentTable.Name,
Tables.SelectedValue == null ? "selected = null" : Tables.SelectedValue.ToString());
OutputWindowMessage.WriteMessage(ex.Message);
}
}
private bool CheckSaveChanges()
{
return true;
}
private void DataGrid_OnRowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
{
_currentDataGridDirty = true;
}
private void button1_Save(object sender, RoutedEventArgs e)
{
//need to finish off saving back to the files (need a radio button with pre/post deploy (not changeable when read from file) - futrue feature
//need a check to write files on window closing
//need lots of tests
try
{
_solution.Save();
}
catch (Exception ex)
{
Dispatcher.Invoke(() => { LastStatusMessage.Text = "Error see output window"; });
OutputWindowMessage.WriteMessage("Error saving solution files:");
OutputWindowMessage.WriteMessage(ex.Message);
}
}
private void ImportTable(object sender, RoutedEventArgs e)
{
if (_currentTable == null)
{
MessageBox.Show("Please choose a table in the drop down list", "MergeUi");
return;
}
try
{
new Importer().GetData(_currentTable);
}
catch (Exception ex)
{
Dispatcher.Invoke(() => { LastStatusMessage.Text = "Error see output window"; });
OutputWindowMessage.WriteMessage("Error importing data (table={0}):", _currentTable.Name);
OutputWindowMessage.WriteMessage(ex.Message);
}
DataGrid.DataContext = _currentTable.Data.DefaultView;
}
private void Logging_OnChecked(object sender, RoutedEventArgs e)
{
DebugLogging.Enable = Logging.IsChecked.Value;
}
}
public interface IStatus
{
void SetStatus(string message);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using ZitaAsteria;
using ZitaAsteria.World;
namespace ZAsteroids.World.HUD
{
class HUDSheilds : HUDComponent
{
public SpriteFont Font { get; set; }
public Texture2D SheildTexture { get; set; }
public Texture2D ActiveTexture { get; set; }
public Texture2D DamageTexture { get; set; }
private RelativeTexture SheildInfo;
private RelativeTexture WorkingValue;
private bool enabled;
private bool update = false;
private Vector2 safePositionTopRight;
private Color color;
public HUDSheilds()
{
}
public override void Initialize()
{
// Must initialize base to get safe draw area
base.Initialize();
SheildTexture = WorldContent.hudContent.sheilds;
ActiveTexture = WorldContent.hudContent.active;
DamageTexture = WorldContent.hudContent.damage;
SheildInfo = new RelativeTexture(SheildTexture);
SheildInfo.Children.Add("Base01", new RelativeTexture(ActiveTexture) { Position = new Vector2(129, 203), EnableDraw = true });
SheildInfo.Children.Add("Base02", new RelativeTexture(ActiveTexture) { Position = new Vector2(164.5f, 182.5f), EnableDraw = true });
SheildInfo.Children.Add("Base03", new RelativeTexture(ActiveTexture) { Position = new Vector2(129.5f, 123), EnableDraw = true });
SheildInfo.Children.Add("Base04", new RelativeTexture(ActiveTexture) { Position = new Vector2(147, 92.5f), EnableDraw = true });
SheildInfo.Children.Add("Base05", new RelativeTexture(ActiveTexture) { Position = new Vector2(199.5f, 42), EnableDraw = true });
SheildInfo.Children.Add("Base06", new RelativeTexture(ActiveTexture) { Position = new Vector2(234.5f, 102), EnableDraw = true });
SheildInfo.Children.Add("Damage01", new RelativeTexture(DamageTexture) { Position = new Vector2(94.5f, 143) });
SheildInfo.Children.Add("Damage02", new RelativeTexture(DamageTexture) { Position = new Vector2(112, 153) });
SheildInfo.Children.Add("Damage03", new RelativeTexture(DamageTexture) { Position = new Vector2(112, 133) });
SheildInfo.Children.Add("Damage04", new RelativeTexture(DamageTexture) { Position = new Vector2(112, 113) });
SheildInfo.Children.Add("Damage05", new RelativeTexture(DamageTexture) { Position = new Vector2(129.5f, 143) });
SheildInfo.Children.Add("Damage06", new RelativeTexture(DamageTexture) { Position = new Vector2(129.5f, 103) });
SheildInfo.Children.Add("Damage07", new RelativeTexture(DamageTexture) { Position = new Vector2(129.5f, 83) });
SheildInfo.Children.Add("Damage08", new RelativeTexture(DamageTexture) { Position = new Vector2(147, 173) });
SheildInfo.Children.Add("Damage09", new RelativeTexture(DamageTexture) { Position = new Vector2(147, 153) });
SheildInfo.Children.Add("Damage10", new RelativeTexture(DamageTexture) { Position = new Vector2(147, 133) });
SheildInfo.Children.Add("Damage11", new RelativeTexture(DamageTexture) { Position = new Vector2(147, 113) });
SheildInfo.Children.Add("Damage12", new RelativeTexture(DamageTexture) { Position = new Vector2(147, 73) });
SheildInfo.Children.Add("Damage13", new RelativeTexture(DamageTexture) { Position = new Vector2(147, 53) });
SheildInfo.Children.Add("Damage14", new RelativeTexture(DamageTexture) { Position = new Vector2(147, 12) });
SheildInfo.Children.Add("Damage15", new RelativeTexture(DamageTexture) { Position = new Vector2(164.5f, 162.5f) });
SheildInfo.Children.Add("Damage16", new RelativeTexture(DamageTexture) { Position = new Vector2(164.5f, 142.5f) });
SheildInfo.Children.Add("Damage17", new RelativeTexture(DamageTexture) { Position = new Vector2(164.5f, 122.5f) });
SheildInfo.Children.Add("Damage18", new RelativeTexture(DamageTexture) { Position = new Vector2(164.5f, 102.5f) });
SheildInfo.Children.Add("Damage19", new RelativeTexture(DamageTexture) { Position = new Vector2(164.5f, 82.5f) });
SheildInfo.Children.Add("Damage20", new RelativeTexture(DamageTexture) { Position = new Vector2(164.5f, 62.5f) });
SheildInfo.Children.Add("Damage21", new RelativeTexture(DamageTexture) { Position = new Vector2(164.5f, 42.5f) });
SheildInfo.Children.Add("Damage22", new RelativeTexture(DamageTexture) { Position = new Vector2(164.5f, 22.5f) });
SheildInfo.Children.Add("Damage23", new RelativeTexture(DamageTexture) { Position = new Vector2(182.5f, 173) });
SheildInfo.Children.Add("Damage24", new RelativeTexture(DamageTexture) { Position = new Vector2(182.5f, 153) });
SheildInfo.Children.Add("Damage25", new RelativeTexture(DamageTexture) { Position = new Vector2(182.5f, 133) });
SheildInfo.Children.Add("Damage26", new RelativeTexture(DamageTexture) { Position = new Vector2(182.5f, 113) });
SheildInfo.Children.Add("Damage27", new RelativeTexture(DamageTexture) { Position = new Vector2(182.5f, 73) });
SheildInfo.Children.Add("Damage28", new RelativeTexture(DamageTexture) { Position = new Vector2(182.5f, 53) });
SheildInfo.Children.Add("Damage29", new RelativeTexture(DamageTexture) { Position = new Vector2(199.5f, 62) });
SheildInfo.Children.Add("Damage30", new RelativeTexture(DamageTexture) { Position = new Vector2(199.5f, 82) });
SheildInfo.Children.Add("Damage31", new RelativeTexture(DamageTexture) { Position = new Vector2(199.5f, 102) });
SheildInfo.Children.Add("Damage32", new RelativeTexture(DamageTexture) { Position = new Vector2(199.5f, 122) });
SheildInfo.Children.Add("Damage33", new RelativeTexture(DamageTexture) { Position = new Vector2(199.5f, 142) });
SheildInfo.Children.Add("Damage34", new RelativeTexture(DamageTexture) { Position = new Vector2(199.5f, 162) });
SheildInfo.Children.Add("Damage35", new RelativeTexture(DamageTexture) { Position = new Vector2(199.5f, 182) });
SheildInfo.Children.Add("Damage36", new RelativeTexture(DamageTexture) { Position = new Vector2(217.5f, 112.5f) });
SheildInfo.Children.Add("Damage37", new RelativeTexture(DamageTexture) { Position = new Vector2(217.5f, 92.5f) });
SheildInfo.Children.Add("Damage38", new RelativeTexture(DamageTexture) { Position = new Vector2(217.5f, 72.5f) });
SheildInfo.Children.Add("Damage39", new RelativeTexture(DamageTexture) { Position = new Vector2(235, 122) });
SheildInfo.EnableDraw = true;
SheildInfo.Position = new Vector2(HUDDrawSafeArea.Right - (SheildTexture.Width / 2), HUDDrawSafeArea.Top + (SheildTexture.Height / 2));
safePositionTopRight = new Vector2(HUDDrawSafeArea.Right, HUDDrawSafeArea.Top);
Font = WorldContent.fontAL15pt;
}
public override void Update(GameTime gameTime)
{
//base.Update(gameTime);
// Fuck this sucks, but doing it at work, so will fix later
//DUUUUUUUUUDE, holy crap! 10 points for effort :) [GearsAD]
if (update)
{
if (HUDProperties.HealthAmount <= 97.0f)
{
SheildInfo.Children.TryGetValue("Damage32", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage32", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 95.0f)
{
SheildInfo.Children.TryGetValue("Damage39", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage39", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 93.0f)
{
SheildInfo.Children.TryGetValue("Damage02", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage02", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 90.0f)
{
SheildInfo.Children.TryGetValue("Damage38", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage38", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 87.0f)
{
SheildInfo.Children.TryGetValue("Damage03", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage03", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 85.0f)
{
SheildInfo.Children.TryGetValue("Damage37", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage37", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 83.0f)
{
SheildInfo.Children.TryGetValue("Damage04", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage04", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 80.0f)
{
SheildInfo.Children.TryGetValue("Damage36", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage36", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 77.0f)
{
SheildInfo.Children.TryGetValue("Damage05", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage05", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 75.0f)
{
SheildInfo.Children.TryGetValue("Damage35", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage35", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 73.0f)
{
SheildInfo.Children.TryGetValue("Damage06", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage06", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 70.0f)
{
SheildInfo.Children.TryGetValue("Damage34", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage34", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 67.0f)
{
SheildInfo.Children.TryGetValue("Damage07", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage07", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 65.0f)
{
SheildInfo.Children.TryGetValue("Damage33", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage33", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 63.0f)
{
SheildInfo.Children.TryGetValue("Damage22", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage22", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 60.0f)
{
SheildInfo.Children.TryGetValue("Damage01", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage01", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 57.0f)
{
SheildInfo.Children.TryGetValue("Damage09", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage09", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 55.0f)
{
SheildInfo.Children.TryGetValue("Damage31", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage31", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 53.0f)
{
SheildInfo.Children.TryGetValue("Damage10", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage10", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 50.0f)
{
SheildInfo.Children.TryGetValue("Damage30", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage30", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 47.0f)
{
SheildInfo.Children.TryGetValue("Damage11", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage11", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 45.0f)
{
SheildInfo.Children.TryGetValue("Damage29", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage29", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 43.0f)
{
SheildInfo.Children.TryGetValue("Damage12", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage12", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 40.0f)
{
SheildInfo.Children.TryGetValue("Damage28", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage28", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 37.0f)
{
SheildInfo.Children.TryGetValue("Damage13", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage13", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 35.0f)
{
SheildInfo.Children.TryGetValue("Damage27", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage27", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 33.0f)
{
SheildInfo.Children.TryGetValue("Damage14", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage14", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 30.0f)
{
SheildInfo.Children.TryGetValue("Damage26", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage26", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 27.0f)
{
SheildInfo.Children.TryGetValue("Damage15", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage15", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 25.0f)
{
SheildInfo.Children.TryGetValue("Damage25", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage25", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 23.0f)
{
SheildInfo.Children.TryGetValue("Damage16", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage16", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 20.0f)
{
SheildInfo.Children.TryGetValue("Damage24", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage24", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 17.0f)
{
SheildInfo.Children.TryGetValue("Damage17", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage17", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 15.0f)
{
SheildInfo.Children.TryGetValue("Damage23", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage23", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 13.0f)
{
SheildInfo.Children.TryGetValue("Damage18", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage18", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 10.0f)
{
SheildInfo.Children.TryGetValue("Damage08", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage08", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 7.0f)
{
SheildInfo.Children.TryGetValue("Damage19", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage19", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 5.0f)
{
SheildInfo.Children.TryGetValue("Damage21", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage21", out WorkingValue);
WorkingValue.EnableDraw = false;
}
if (HUDProperties.HealthAmount <= 0.0f)
{
SheildInfo.Children.TryGetValue("Damage20", out WorkingValue);
WorkingValue.EnableDraw = true;
}
else
{
SheildInfo.Children.TryGetValue("Damage20", out WorkingValue);
WorkingValue.EnableDraw = false;
}
}
update = !update;
}
public override void Draw()
{
if (enabled)
{
HUDSpriteBatch.Begin();
SheildInfo.Draw(HUDSpriteBatch);
string health = HUDProperties.HealthAmount.ToString();
if (HUDProperties.HealthAmount <= 80)
{
color = Color.Orange;
}
else if (HUDProperties.HealthAmount <= 40)
{
color = Color.Red;
}
else
{
color = WorldContent.hudContent.hudTextColor;
}
HUDSpriteBatch.DrawString(Font, health, safePositionTopRight + new Vector2(-SheildTexture.Width + 45, 22), color);
HUDSpriteBatch.End();
}
}
/// <summary>
/// Sets whether the component should be drawn.
/// </summary>
/// <param name="enabled">enable the component</param>
public void Enable(bool enabled)
{
this.enabled = enabled;
}
}
}
|
using System;
namespace Versioning
{
public class NominalData : Sage_Container, IData
{
/* Autogenerated by sage_wrapper_generator.pl */
SageDataObject110.NominalData nd11;
SageDataObject120.NominalData nd12;
SageDataObject130.NominalData nd13;
SageDataObject140.NominalData nd14;
SageDataObject150.NominalData nd15;
SageDataObject160.NominalData nd16;
SageDataObject170.NominalData nd17;
public NominalData(object inner, int version)
: base(version) {
switch (m_version) {
case 11: {
nd11 = (SageDataObject110.NominalData)inner;
m_fields = new Fields(nd11.Fields,m_version);
return;
}
case 12: {
nd12 = (SageDataObject120.NominalData)inner;
m_fields = new Fields(nd12.Fields,m_version);
return;
}
case 13: {
nd13 = (SageDataObject130.NominalData)inner;
m_fields = new Fields(nd13.Fields,m_version);
return;
}
case 14: {
nd14 = (SageDataObject140.NominalData)inner;
m_fields = new Fields(nd14.Fields,m_version);
return;
}
case 15: {
nd15 = (SageDataObject150.NominalData)inner;
m_fields = new Fields(nd15.Fields,m_version);
return;
}
case 16: {
nd16 = (SageDataObject160.NominalData)inner;
m_fields = new Fields(nd16.Fields,m_version);
return;
}
case 17: {
nd17 = (SageDataObject170.NominalData)inner;
m_fields = new Fields(nd17.Fields,m_version);
return;
}
default: throw new InvalidOperationException("ver");
}
}
/* Autogenerated with data_generator.pl */
const string ACCOUNT_REF = "ACCOUNT_REF";
const string NOMINALDATA = "NominalData";
public bool Open(OpenMode mode) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.Open((SageDataObject110.OpenMode)mode);
break;
}
case 12: {
ret = nd12.Open((SageDataObject120.OpenMode)mode);
break;
}
case 13: {
ret = nd13.Open((SageDataObject130.OpenMode)mode);
break;
}
case 14: {
ret = nd14.Open((SageDataObject140.OpenMode)mode);
break;
}
case 15: {
ret = nd15.Open((SageDataObject150.OpenMode)mode);
break;
}
case 16: {
ret = nd16.Open((SageDataObject160.OpenMode)mode);
break;
}
case 17: {
ret = nd17.Open((SageDataObject170.OpenMode)mode);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public void Close() {
switch (m_version) {
case 11: {
nd11.Close();
break;
}
case 12: {
nd12.Close();
break;
}
case 13: {
nd13.Close();
break;
}
case 14: {
nd14.Close();
break;
}
case 15: {
nd15.Close();
break;
}
case 16: {
nd16.Close();
break;
}
case 17: {
nd17.Close();
break;
}
default: throw new InvalidOperationException("ver");
}
}
public bool Read(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.Read(IRecNo);
break;
}
case 12: {
ret = nd12.Read(IRecNo);
break;
}
case 13: {
ret = nd13.Read(IRecNo);
break;
}
case 14: {
ret = nd14.Read(IRecNo);
break;
}
case 15: {
ret = nd15.Read(IRecNo);
break;
}
case 16: {
ret = nd16.Read(IRecNo);
break;
}
case 17: {
ret = nd17.Read(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Write(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.Write(IRecNo);
break;
}
case 12: {
ret = nd12.Write(IRecNo);
break;
}
case 13: {
ret = nd13.Write(IRecNo);
break;
}
case 14: {
ret = nd14.Write(IRecNo);
break;
}
case 15: {
ret = nd15.Write(IRecNo);
break;
}
case 16: {
ret = nd16.Write(IRecNo);
break;
}
case 17: {
ret = nd17.Write(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Seek(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.Seek(IRecNo);
break;
}
case 12: {
ret = nd12.Seek(IRecNo);
break;
}
case 13: {
ret = nd13.Seek(IRecNo);
break;
}
case 14: {
ret = nd14.Seek(IRecNo);
break;
}
case 15: {
ret = nd15.Seek(IRecNo);
break;
}
case 16: {
ret = nd16.Seek(IRecNo);
break;
}
case 17: {
ret = nd17.Seek(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Lock(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.Lock(IRecNo);
break;
}
case 12: {
ret = nd12.Lock(IRecNo);
break;
}
case 13: {
ret = nd13.Lock(IRecNo);
break;
}
case 14: {
ret = nd14.Lock(IRecNo);
break;
}
case 15: {
ret = nd15.Lock(IRecNo);
break;
}
case 16: {
ret = nd16.Lock(IRecNo);
break;
}
case 17: {
ret = nd17.Lock(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Unlock(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.Unlock(IRecNo);
break;
}
case 12: {
ret = nd12.Unlock(IRecNo);
break;
}
case 13: {
ret = nd13.Unlock(IRecNo);
break;
}
case 14: {
ret = nd14.Unlock(IRecNo);
break;
}
case 15: {
ret = nd15.Unlock(IRecNo);
break;
}
case 16: {
ret = nd16.Unlock(IRecNo);
break;
}
case 17: {
ret = nd17.Unlock(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool FindFirst(object varField, object varSearch) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.FindFirst(varField, varSearch);
break;
}
case 12: {
ret = nd12.FindFirst(varField, varSearch);
break;
}
case 13: {
ret = nd13.FindFirst(varField, varSearch);
break;
}
case 14: {
ret = nd14.FindFirst(varField, varSearch);
break;
}
case 15: {
ret = nd15.FindFirst(varField, varSearch);
break;
}
case 16: {
ret = nd16.FindFirst(varField, varSearch);
break;
}
case 17: {
ret = nd17.FindFirst(varField, varSearch);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool FindNext(object varField, object varSearch) {
bool ret;
switch (m_version) {
case 11: {
ret = nd11.FindNext(varField, varSearch);
break;
}
case 12: {
ret = nd12.FindNext(varField, varSearch);
break;
}
case 13: {
ret = nd13.FindNext(varField, varSearch);
break;
}
case 14: {
ret = nd14.FindNext(varField, varSearch);
break;
}
case 15: {
ret = nd15.FindNext(varField, varSearch);
break;
}
case 16: {
ret = nd16.FindNext(varField, varSearch);
break;
}
case 17: {
ret = nd17.FindNext(varField, varSearch);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public int Count {
get {
int ret;
switch (m_version) {
case 11: {
ret = nd11.Count();
break;
}
case 12: {
ret = nd12.Count();
break;
}
case 13: {
ret = nd13.Count();
break;
}
case 14: {
ret = nd14.Count();
break;
}
case 15: {
ret = nd15.Count();
break;
}
case 16: {
ret = nd16.Count();
break;
}
case 17: {
ret = nd17.Count();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
}
}
}
|
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright by Brian Nelson 2016. *
* See license in repo for more information *
* https://github.com/sharpHDF/sharpHDF *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
using System;
using System.Collections.Generic;
using NUnit.Framework;
using sharpHDF.Library.Enums;
using sharpHDF.Library.Exceptions;
using sharpHDF.Library.Objects;
namespace sharpHDF.Library.Tests.Objects
{
[TestFixture]
public class Hdf5AttributeTests : BaseTest
{
[OneTimeSetUp]
public void Setup()
{
DirectoryName = @"c:\temp\hdf5tests\attributetests";
CleanDirectory();
}
[Test]
public void CreateAttributeOnFile()
{
string fileName = GetFilename("createattributeonfile.h5");
Hdf5File file = Hdf5File.Create(fileName);
file.Attributes.Add("attribute1", "test");
file.Attributes.Add("attribute2", 5);
Assert.AreEqual(2, file.Attributes.Count);
file.Close();
}
[Test]
public void CreateAttributeTwiceOnFile()
{
string fileName = GetFilename("createattributetwiceonfile.h5");
Hdf5File file = Hdf5File.Create(fileName);
file.Attributes.Add("attribute1", "test");
try
{
file.Attributes.Add("attribute1", "test2");
Assert.Fail("Should have thrown an exception");
}
catch (Exception ex)
{
file.Close();
Assert.IsInstanceOf<Hdf5AttributeAlreadyExistException>(ex);
}
}
[Test]
public void CreateAttributeTwiceOnGroup()
{
string fileName = GetFilename("createattributetwiceongroup.h5");
Hdf5File file = Hdf5File.Create(fileName);
Hdf5Group group = file.Groups.Add("test");
group.Attributes.Add("attribute1", "test");
try
{
group.Attributes.Add("attribute1", "test2");
Assert.Fail("Should have thrown an exception");
}
catch (Exception ex)
{
file.Close();
Assert.IsInstanceOf<Hdf5AttributeAlreadyExistException>(ex);
}
}
[Test]
public void CreateAttributeTwiceOnDataset()
{
string fileName = GetFilename("createattributetwiceondataset.h5");
Hdf5File file = Hdf5File.Create(fileName);
Hdf5Group group = file.Groups.Add("test");
List<Hdf5DimensionProperty> dimensionProps = new List<Hdf5DimensionProperty>();
Hdf5DimensionProperty prop = new Hdf5DimensionProperty { CurrentSize = 1 };
dimensionProps.Add(prop);
Hdf5Dataset dataset = group.Datasets.Add("dataset1", Hdf5DataTypes.Int32, dimensionProps);
dataset.Attributes.Add("attribute1", "test");
try
{
dataset.Attributes.Add("attribute1", "test2");
Assert.Fail("Should have thrown an exception");
}
catch (Exception ex)
{
file.Close();
Assert.IsInstanceOf<Hdf5AttributeAlreadyExistException>(ex);
}
}
[Test]
public void UpdateAttributeWithMismatchOnFile()
{
string fileName = GetFilename("updateattributewithmistmachonfile.h5");
Hdf5File file = Hdf5File.Create(fileName);
Hdf5Attribute attribute = file.Attributes.Add("attribute1", "test");
try
{
attribute.Value = 5;
file.Attributes.Update(attribute);
Assert.Fail("Should have thrown an exception");
}
catch (Exception ex)
{
file.Close();
Assert.IsInstanceOf<Hdf5TypeMismatchException>(ex);
}
}
[Test]
public void UpdateAttributeWithMismatchOnGroup()
{
string fileName = GetFilename("updateattributewithmistmachongroup.h5");
Hdf5File file = Hdf5File.Create(fileName);
Hdf5Group group = file.Groups.Add("group");
Hdf5Attribute attribute = group.Attributes.Add("attribute1", "test");
try
{
attribute.Value = 5;
group.Attributes.Update(attribute);
Assert.Fail("Should have thrown an exception");
}
catch (Exception ex)
{
file.Close();
Assert.IsInstanceOf<Hdf5TypeMismatchException>(ex);
}
}
[Test]
public void UpdateAttributeWithMismatchOnDataset()
{
string fileName = GetFilename("updateattributewithmistmachondataset.h5");
Hdf5File file = Hdf5File.Create(fileName);
Hdf5Group group = file.Groups.Add("group");
List<Hdf5DimensionProperty> dimensionProps = new List<Hdf5DimensionProperty>();
Hdf5DimensionProperty prop = new Hdf5DimensionProperty { CurrentSize = 1 };
dimensionProps.Add(prop);
Hdf5Dataset dataset = group.Datasets.Add("dataset1", Hdf5DataTypes.Int32, dimensionProps);
Hdf5Attribute attribute = dataset.Attributes.Add("attribute1", "test");
try
{
attribute.Value = 5;
dataset.Attributes.Update(attribute);
Assert.Fail("Should have thrown an exception");
}
catch (Exception ex)
{
file.Close();
Assert.IsInstanceOf<Hdf5TypeMismatchException>(ex);
}
}
[Test]
public void UpdateStringAttributeOnFile()
{
string fileName = GetFilename("updatestringattributeonfile.h5");
Hdf5File file = Hdf5File.Create(fileName);
Hdf5Attribute attribute = file.Attributes.Add("attribute1", "test");
attribute.Value = "test2";
file.Attributes.Update(attribute);
file.Close();
file = new Hdf5File(fileName);
attribute = file.Attributes[0];
Assert.AreEqual("test2", attribute.Value);
}
[Test]
public void UpdateStringAttributeOnGroup()
{
string fileName = GetFilename("updatestringattributeongroup.h5");
Hdf5File file = Hdf5File.Create(fileName);
Hdf5Group group = file.Groups.Add("group");
Hdf5Attribute attribute = group.Attributes.Add("attribute1", "test");
attribute.Value = "test2";
group.Attributes.Update(attribute);
file.Close();
file = new Hdf5File(fileName);
group = file.Groups[0];
attribute = group.Attributes[0];
Assert.AreEqual("test2", attribute.Value);
}
[Test]
public void UpdateStringAttributeOnDataset()
{
string fileName = GetFilename("updatestringattributeondataset.h5");
Hdf5File file = Hdf5File.Create(fileName);
Hdf5Group group = file.Groups.Add("group");
List<Hdf5DimensionProperty> dimensionProps = new List<Hdf5DimensionProperty>();
Hdf5DimensionProperty prop = new Hdf5DimensionProperty { CurrentSize = 1 };
dimensionProps.Add(prop);
Hdf5Dataset dataset = group.Datasets.Add("dataset1", Hdf5DataTypes.Int32, dimensionProps);
Hdf5Attribute attribute = dataset.Attributes.Add("attribute1", "test");
attribute.Value = "test2";
dataset.Attributes.Update(attribute);
file.Close();
file = new Hdf5File(fileName);
group = file.Groups[0];
dataset = group.Datasets[0];
attribute = dataset.Attributes[0];
Assert.AreEqual("test2", attribute.Value);
}
[Test]
public void GetAttributeOnFile()
{
string fileName = GetFilename("getattributeonfile.h5");
Hdf5File file = Hdf5File.Create(fileName);
file.Attributes.Add("attribute1", "test");
file.Attributes.Add("attribute2", 5);
Assert.AreEqual(2, file.Attributes.Count);
file.Close();
file = new Hdf5File(fileName);
var attibutes = file.Attributes;
Assert.AreEqual(2, attibutes.Count);
var attribute1 = attibutes[0];
Assert.AreEqual("attribute1", attribute1.Name);
Assert.AreEqual("test", attribute1.Value);
var attribute2 = attibutes[1];
Assert.AreEqual("attribute2", attribute2.Name);
Assert.AreEqual(5, attribute2.Value);
}
[Test]
public void CreateAttributeOnGroup()
{
string fileName = GetFilename("createattributeongroup.h5");
Hdf5File file = Hdf5File.Create(fileName);
Hdf5Group group = file.Groups.Add("group1");
group.Attributes.Add("attribute1", "test");
group.Attributes.Add("attribute2", 5);
Assert.AreEqual(2, group.Attributes.Count);
file.Close();
}
[Test]
public void GetAttributeOnGroup()
{
string fileName = GetFilename("getattributeongroup.h5");
Hdf5File file = Hdf5File.Create(fileName);
Hdf5Group group = file.Groups.Add("group1");
group.Attributes.Add("attribute1", "test");
group.Attributes.Add("attribute2", 5);
Assert.AreEqual(2, group.Attributes.Count);
file.Close();
file = new Hdf5File(fileName);
group = file.Groups[0];
var attibutes = group.Attributes;
Assert.AreEqual(2, attibutes.Count);
var attribute1 = attibutes[0];
Assert.AreEqual("attribute1", attribute1.Name);
Assert.AreEqual("test", attribute1.Value);
var attribute2 = attibutes[1];
Assert.AreEqual("attribute2", attribute2.Name);
Assert.AreEqual(5, attribute2.Value);
}
[Test]
public void CreateAttributeOnDataset()
{
string fileName = GetFilename("createattributeondataset.h5");
Hdf5File file = Hdf5File.Create(fileName);
Hdf5Group group = file.Groups.Add("group1");
List<Hdf5DimensionProperty> dimensionProps = new List<Hdf5DimensionProperty>();
Hdf5DimensionProperty prop = new Hdf5DimensionProperty {CurrentSize = 1};
dimensionProps.Add(prop);
Hdf5Dataset dataset = group.Datasets.Add("dataset1", Hdf5DataTypes.Int32, dimensionProps);
dataset.Attributes.Add("attribute1", "test");
dataset.Attributes.Add("attribute2", 5);
Assert.AreEqual(2, dataset.Attributes.Count);
file.Close();
}
[Test]
public void GetAttributeOnDataset()
{
string fileName = GetFilename("getattributeondataset.h5");
Hdf5File file = Hdf5File.Create(fileName);
Hdf5Group group = file.Groups.Add("group1");
List<Hdf5DimensionProperty> dimensionProps = new List<Hdf5DimensionProperty>();
Hdf5DimensionProperty prop = new Hdf5DimensionProperty { CurrentSize = 1 };
dimensionProps.Add(prop);
Hdf5Dataset dataset = group.Datasets.Add("dataset1", Hdf5DataTypes.Int32, dimensionProps);
dataset.Attributes.Add("attribute1", "test");
dataset.Attributes.Add("attribute2", 5);
Assert.AreEqual(2, dataset.Attributes.Count);
file.Close();
file = new Hdf5File(fileName);
group = file.Groups[0];
dataset = group.Datasets[0];
var attibutes = dataset.Attributes;
Assert.AreEqual(2, attibutes.Count);
var attribute1 = attibutes[0];
Assert.AreEqual("attribute1", attribute1.Name);
Assert.AreEqual("test", attribute1.Value);
var attribute2 = attibutes[1];
Assert.AreEqual("attribute2", attribute2.Name);
Assert.AreEqual(5, attribute2.Value);
}
[Test]
public void DeleteAttributeOnFile()
{
string fileName = GetFilename("deleteattributeonfile.h5");
Hdf5File file = Hdf5File.Create(fileName);
file.Attributes.Add("attribute1", "test");
file.Attributes.Add("attribute2", 5);
Assert.AreEqual(2, file.Attributes.Count);
file.Close();
file = new Hdf5File(fileName);
var attibutes = file.Attributes;
Assert.AreEqual(2, attibutes.Count);
var attribute1 = attibutes[0];
Assert.AreEqual("attribute1", attribute1.Name);
Assert.AreEqual("test", attribute1.Value);
var attribute2 = attibutes[1];
Assert.AreEqual("attribute2", attribute2.Name);
Assert.AreEqual(5, attribute2.Value);
file.Attributes.Delete(attribute1);
Assert.AreEqual(1, attibutes.Count);
attribute2 = attibutes[0];
Assert.AreEqual("attribute2", attribute2.Name);
Assert.AreEqual(5, attribute2.Value);
file.Close();
file = new Hdf5File(fileName);
attibutes = file.Attributes;
Assert.AreEqual(1, attibutes.Count);
attribute2 = attibutes[0];
Assert.AreEqual("attribute2", attribute2.Name);
Assert.AreEqual(5, attribute2.Value);
}
[Test]
public void DeleteAttributeOnGroup()
{
string fileName = GetFilename("deleteattributeongroup.h5");
Hdf5File file = Hdf5File.Create(fileName);
Hdf5Group group = file.Groups.Add("group1");
group.Attributes.Add("attribute1", "test");
group.Attributes.Add("attribute2", 5);
Assert.AreEqual(2, group.Attributes.Count);
file.Close();
file = new Hdf5File(fileName);
group = file.Groups[0];
var attibutes = group.Attributes;
Assert.AreEqual(2, attibutes.Count);
var attribute1 = attibutes[0];
Assert.AreEqual("attribute1", attribute1.Name);
Assert.AreEqual("test", attribute1.Value);
var attribute2 = attibutes[1];
Assert.AreEqual("attribute2", attribute2.Name);
Assert.AreEqual(5, attribute2.Value);
group.Attributes.Delete(attribute1);
Assert.AreEqual(1, attibutes.Count);
attribute2 = attibutes[0];
Assert.AreEqual("attribute2", attribute2.Name);
Assert.AreEqual(5, attribute2.Value);
file.Close();
file = new Hdf5File(fileName);
group = file.Groups[0];
attibutes = group.Attributes;
Assert.AreEqual(1, attibutes.Count);
attribute2 = attibutes[0];
Assert.AreEqual("attribute2", attribute2.Name);
Assert.AreEqual(5, attribute2.Value);
}
[Test]
public void DeleteAttributeOnDataset()
{
string fileName = GetFilename("deleteattributeondataset.h5");
Hdf5File file = Hdf5File.Create(fileName);
Hdf5Group group = file.Groups.Add("group1");
List<Hdf5DimensionProperty> dimensionProps = new List<Hdf5DimensionProperty>();
Hdf5DimensionProperty prop = new Hdf5DimensionProperty { CurrentSize = 1 };
dimensionProps.Add(prop);
Hdf5Dataset dataset = group.Datasets.Add("dataset1", Hdf5DataTypes.Int32, dimensionProps);
dataset.Attributes.Add("attribute1", "test");
dataset.Attributes.Add("attribute2", 5);
Assert.AreEqual(2, dataset.Attributes.Count);
file.Close();
file = new Hdf5File(fileName);
group = file.Groups[0];
dataset = group.Datasets[0];
var attibutes = dataset.Attributes;
Assert.AreEqual(2, attibutes.Count);
var attribute1 = attibutes[0];
Assert.AreEqual("attribute1", attribute1.Name);
Assert.AreEqual("test", attribute1.Value);
var attribute2 = attibutes[1];
Assert.AreEqual("attribute2", attribute2.Name);
Assert.AreEqual(5, attribute2.Value);
dataset.Attributes.Delete(attribute1);
Assert.AreEqual(1, attibutes.Count);
attribute2 = attibutes[0];
Assert.AreEqual("attribute2", attribute2.Name);
Assert.AreEqual(5, attribute2.Value);
file.Close();
file = new Hdf5File(fileName);
group = file.Groups[0];
dataset = group.Datasets[0];
attibutes = dataset.Attributes;
Assert.AreEqual(1, attibutes.Count);
attribute2 = attibutes[0];
Assert.AreEqual("attribute2", attribute2.Name);
Assert.AreEqual(5, attribute2.Value);
}
[Test]
public void AllAttributeTypesOnFile()
{
string fileName = GetFilename("allattributetypesonfile.h5");
Hdf5File file = Hdf5File.Create(fileName);
file.Attributes.Add("attributea", "test");
sbyte b = sbyte.MaxValue;
file.Attributes.Add("attributeb", b);
Int16 c = Int16.MaxValue;
file.Attributes.Add("attributec", c);
Int32 d = Int32.MaxValue;
file.Attributes.Add("attributed", d);
Int64 e = Int64.MaxValue;
file.Attributes.Add("attributee", e);
byte f = Byte.MaxValue;
file.Attributes.Add("attibutef", f);
UInt16 g = UInt16.MaxValue;
file.Attributes.Add("attributeg", g);
UInt32 h = UInt32.MaxValue;
file.Attributes.Add("attibuteh", h);
UInt64 i = UInt64.MaxValue;
file.Attributes.Add("attributei", i);
float j = float.MaxValue;
file.Attributes.Add("attibutej", j);
double k = double.MaxValue;
file.Attributes.Add("attributek", k);
Assert.AreEqual(11, file.Attributes.Count);
file.Close();
file = new Hdf5File(fileName);
var attibutes = file.Attributes;
Assert.AreEqual(11, attibutes.Count);
var attribute1 = attibutes[0];
Assert.AreEqual("test", attribute1.Value);
var attribute2 = attibutes[1];
Assert.AreEqual(sbyte.MaxValue, attribute2.Value);
var attribute3 = attibutes[2];
Assert.AreEqual(Int16.MaxValue, attribute3.Value);
var attribute4 = attibutes[3];
Assert.AreEqual(Int32.MaxValue, attribute4.Value);
var attribute5 = attibutes[4];
Assert.AreEqual(Int64.MaxValue, attribute5.Value);
var attribute6 = attibutes[5];
Assert.AreEqual(byte.MaxValue, attribute6.Value);
var attribute7 = attibutes[6];
Assert.AreEqual(UInt16.MaxValue, attribute7.Value);
var attribute8 = attibutes[7];
Assert.AreEqual(UInt32.MaxValue, attribute8.Value);
var attribute9 = attibutes[8];
Assert.AreEqual(UInt64.MaxValue, attribute9.Value);
var attribute10 = attibutes[9];
Assert.AreEqual(float.MaxValue, attribute10.Value);
var attribute11 = attibutes[10];
Assert.AreEqual(double.MaxValue, attribute11.Value);
}
[Test]
public void UpdateAllAttributeTypesOnFile()
{
string fileName = GetFilename("updateallattributetypesonfile.h5");
Hdf5File file = Hdf5File.Create(fileName);
var atta = file.Attributes.Add("attributea", "test");
atta.Value = "test2";
file.Attributes.Update(atta);
sbyte b = sbyte.MaxValue;
var attb = file.Attributes.Add("attributeb", b);
attb.Value = sbyte.MinValue;
file.Attributes.Update(attb);
Int16 c = Int16.MaxValue;
var attc = file.Attributes.Add("attributec", c);
attc.Value = Int16.MinValue;
file.Attributes.Update(attc);
Int32 d = Int32.MaxValue;
var attd = file.Attributes.Add("attributed", d);
attd.Value = Int32.MinValue;
file.Attributes.Update(attd);
Int64 e = Int64.MaxValue;
var atte = file.Attributes.Add("attributee", e);
atte.Value = Int64.MinValue;
file.Attributes.Update(atte);
byte f = Byte.MaxValue;
var attf = file.Attributes.Add("attibutef", f);
attf.Value = Byte.MinValue;
file.Attributes.Update(attf);
UInt16 g = UInt16.MaxValue;
var attg = file.Attributes.Add("attributeg", g);
attg.Value = UInt16.MinValue;
file.Attributes.Update(attg);
UInt32 h = UInt32.MaxValue;
var atth = file.Attributes.Add("attibuteh", h);
atth.Value = UInt32.MinValue;
file.Attributes.Update(atth);
UInt64 i = UInt64.MaxValue;
var atti = file.Attributes.Add("attributei", i);
atti.Value = UInt64.MinValue;
file.Attributes.Update(atti);
float j = float.MaxValue;
var attj = file.Attributes.Add("attibutej", j);
attj.Value = float.MinValue;
file.Attributes.Update(attj);
double k = double.MaxValue;
var attk = file.Attributes.Add("attributek", k);
attk.Value = double.MinValue;
file.Attributes.Update(attk);
Assert.AreEqual(11, file.Attributes.Count);
file.Close();
file = new Hdf5File(fileName);
var attibutes = file.Attributes;
Assert.AreEqual(11, attibutes.Count);
var attribute1 = attibutes[0];
Assert.AreEqual("test2", attribute1.Value);
var attribute2 = attibutes[1];
Assert.AreEqual(sbyte.MinValue, attribute2.Value);
var attribute3 = attibutes[2];
Assert.AreEqual(Int16.MinValue, attribute3.Value);
var attribute4 = attibutes[3];
Assert.AreEqual(Int32.MinValue, attribute4.Value);
var attribute5 = attibutes[4];
Assert.AreEqual(Int64.MinValue, attribute5.Value);
var attribute6 = attibutes[5];
Assert.AreEqual(byte.MinValue, attribute6.Value);
var attribute7 = attibutes[6];
Assert.AreEqual(UInt16.MinValue, attribute7.Value);
var attribute8 = attibutes[7];
Assert.AreEqual(UInt32.MinValue, attribute8.Value);
var attribute9 = attibutes[8];
Assert.AreEqual(UInt64.MinValue, attribute9.Value);
var attribute10 = attibutes[9];
Assert.AreEqual(float.MinValue, attribute10.Value);
var attribute11 = attibutes[10];
Assert.AreEqual(double.MinValue, attribute11.Value);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Anarian.Interfaces;
using Anarian.Events;
namespace Anarian.DataStructures.Input
{
public class Controller : IUpdatable
{
PlayerIndex m_playerIndex;
GamePadType m_gamePadType;
GamePadCapabilities m_gamePadCapabilities;
GamePadState m_gamePadState;
GamePadState m_prevGamePadState;
bool m_isConnected;
public PlayerIndex PlayerIndex { get { return m_playerIndex; } }
public GamePadType GamePadType { get { return m_gamePadType; } }
public GamePadCapabilities GamePadCapabilities { get { return m_gamePadCapabilities; } }
public GamePadState GamePadState { get { return m_gamePadState; } }
public GamePadState PrevGamePadState { get { return m_prevGamePadState; } }
public bool IsConnected { get { return m_isConnected; } }
public Controller(PlayerIndex playerIndex)
{
m_playerIndex = playerIndex;
Reset();
}
public void Reset()
{
m_gamePadCapabilities = GamePad.GetCapabilities(m_playerIndex);
m_gamePadType = m_gamePadCapabilities.GamePadType;
m_gamePadState = GamePad.GetState(m_playerIndex);
m_prevGamePadState = m_gamePadState;
m_isConnected = m_gamePadState.IsConnected;
}
#region Interface Implimentations
void IUpdatable.Update(GameTime gameTime) { Update(gameTime); }
#endregion
public void Update(GameTime gameTime)
{
//if (!m_isConnected) return;
// Get the States
m_prevGamePadState = m_gamePadState;
m_gamePadState = GamePad.GetState(m_playerIndex);
// Update if it is connected or not
m_isConnected = m_gamePadState.IsConnected;
#region Preform Events
if (GamePadDown != null) {
if (IsButtonDown(Buttons.A)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.A, PlayerIndex)); }
if (IsButtonDown(Buttons.B)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.B, PlayerIndex)); }
if (IsButtonDown(Buttons.X)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.X, PlayerIndex)); }
if (IsButtonDown(Buttons.Y)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.Y, PlayerIndex)); }
if (IsButtonDown(Buttons.LeftShoulder)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.LeftShoulder, PlayerIndex)); }
if (IsButtonDown(Buttons.RightShoulder)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.RightShoulder, PlayerIndex)); }
if (IsButtonDown(Buttons.LeftStick)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.LeftStick, PlayerIndex)); }
if (IsButtonDown(Buttons.RightStick)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.RightStick, PlayerIndex)); }
if (IsButtonDown(Buttons.DPadUp)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadUp, PlayerIndex)); }
if (IsButtonDown(Buttons.DPadDown)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadDown, PlayerIndex)); }
if (IsButtonDown(Buttons.DPadLeft)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadLeft, PlayerIndex)); }
if (IsButtonDown(Buttons.DPadRight)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadRight, PlayerIndex)); }
}
if (GamePadClicked != null) {
if (ButtonPressed(Buttons.A)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.A, PlayerIndex)); }
if (ButtonPressed(Buttons.B)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.B, PlayerIndex)); }
if (ButtonPressed(Buttons.X)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.X, PlayerIndex)); }
if (ButtonPressed(Buttons.Y)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.Y, PlayerIndex)); }
if (ButtonPressed(Buttons.LeftShoulder)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.LeftShoulder, PlayerIndex)); }
if (ButtonPressed(Buttons.RightShoulder)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.RightShoulder, PlayerIndex)); }
if (ButtonPressed(Buttons.LeftStick)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.LeftStick, PlayerIndex)); }
if (ButtonPressed(Buttons.RightStick)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.RightStick, PlayerIndex)); }
if (ButtonPressed(Buttons.DPadUp)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadUp, PlayerIndex)); }
if (ButtonPressed(Buttons.DPadDown)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadDown, PlayerIndex)); }
if (ButtonPressed(Buttons.DPadLeft)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadLeft, PlayerIndex)); }
if (ButtonPressed(Buttons.DPadRight)) { GamePadClicked(this, new GamePadPressedEventArgs(gameTime, Buttons.DPadRight, PlayerIndex)); }
}
if (GamePadMoved != null) {
if (HasLeftThumbstickMoved()) {
GamePadMoved(this,
new GamePadMovedEventsArgs(
gameTime,
Buttons.LeftStick,
PlayerIndex,
m_gamePadState.ThumbSticks.Left,
m_prevGamePadState.ThumbSticks.Left - m_gamePadState.ThumbSticks.Left)
);
}
if (HasRightThumbstickMoved()) {
GamePadMoved(this,
new GamePadMovedEventsArgs(
gameTime,
Buttons.RightStick,
PlayerIndex,
m_gamePadState.ThumbSticks.Right,
m_prevGamePadState.ThumbSticks.Right - m_gamePadState.ThumbSticks.Right)
);
}
if (HasLeftTriggerMoved()) {
GamePadMoved(this,
new GamePadMovedEventsArgs(
gameTime,
Buttons.LeftTrigger,
PlayerIndex,
new Vector2(0.0f, m_gamePadState.Triggers.Left),
new Vector2(0.0f, m_prevGamePadState.Triggers.Left) - new Vector2(0.0f, m_gamePadState.Triggers.Left))
);
}
if (HasRightTriggerMoved()) {
GamePadMoved(this,
new GamePadMovedEventsArgs(
gameTime,
Buttons.RightTrigger,
PlayerIndex,
new Vector2(0.0f, m_gamePadState.Triggers.Right),
new Vector2(0.0f, m_prevGamePadState.Triggers.Right) - new Vector2(0.0f, m_gamePadState.Triggers.Right))
);
}
}
#endregion
}
#region Helper Methods
public bool ButtonPressed(Buttons button)
{
if (m_prevGamePadState.IsButtonDown(button) == true &&
m_gamePadState.IsButtonUp(button) == true)
return true;
return false;
}
public bool IsButtonDown(Buttons button)
{
return m_gamePadState.IsButtonDown(button);
}
public bool IsButtonUp(Buttons button)
{
return m_gamePadState.IsButtonUp(button);
}
public void SetVibration(float leftMotor, float rightMotor)
{
GamePad.SetVibration(m_playerIndex, leftMotor, rightMotor);
}
#region Thumbsticks
public bool HasLeftThumbstickMoved()
{
if (m_gamePadState.ThumbSticks.Left == Vector2.Zero) return false;
return true;
}
public bool HasRightThumbstickMoved()
{
if (m_gamePadState.ThumbSticks.Right == Vector2.Zero) return false;
return true;
}
#endregion
#region Triggers
public bool HasLeftTriggerMoved()
{
if (m_gamePadState.Triggers.Left == 0.0f) return false;
return true;
}
public bool HasRightTriggerMoved()
{
if (m_gamePadState.Triggers.Right == 0.0f) return false;
return true;
}
#endregion
public bool HasInputChanged(bool ignoreThumbsticks)
{
if ((m_gamePadState.IsConnected) && (m_gamePadState.PacketNumber != m_prevGamePadState.PacketNumber))
{
//ignore thumbstick movement
if ((ignoreThumbsticks == true) && ((m_gamePadState.ThumbSticks.Left.Length() != m_prevGamePadState.ThumbSticks.Left.Length()) && (m_gamePadState.ThumbSticks.Right.Length() != m_prevGamePadState.ThumbSticks.Right.Length())))
return false;
return true;
}
return false;
}
#endregion
#region Events
public static event GamePadDownEventHandler GamePadDown;
public static event GamePadPressedEventHandler GamePadClicked;
public static event GamePadMovedEventHandler GamePadMoved;
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Threading;
namespace Joddgewe
{
public partial class Form1 : Form
{
private string filenameOrto;
public Form1()
{
InitializeComponent();
toolStripStatusLabel1.Text = "Venter på at brukeren skal åpne ortofoto...";
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
addFiles();
}
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
closeApp();
}
public void closeApp()
{
this.Dispose();
}
public void addFiles()
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Ortofoto(*.tif;*.jpg;*.gif)|*.TIF;*.JPG;*.GIF";
openFileDialog1.FilterIndex = 3;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
string[] files = openFileDialog1.FileNames;
foreach (string file in files )
{
Image bm = Image.FromFile(file);
FileHandler fh = new FileHandler(file, bm.Width, bm.Height);
bm.Dispose();
listBoxFiler.Items.Add(fh);
}
myStream.Close();
enableButtons();
toolStripStatusLabel1.Text = "Venter på at brukeren skal velge utformat...";
}
myStream.Dispose();
lblVisEgenskaper.Visible = true;
lblUtformat.Visible = true;
}
openFileDialog1.Dispose();
}
private void removeFiles()
{
listBoxFiler.Items.Remove(listBoxFiler.SelectedItem);
textBoxMMM.Text = "";
textBoxJGW.Text = "";
textBoxSOSI.Text = "";
}
private void btnKonverter_Click(object sender, EventArgs e)
{
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 frm = new Form2(this);
frm.ShowDialog();
}
private void btnAdd_Click(object sender, EventArgs e)
{
addFiles();
}
private void btnRemove_Click(object sender, EventArgs e)
{
removeFiles();
}
private void listBoxFiler_SelectedIndexChanged(object sender, EventArgs e)
{
pictboxOrtofoto.Image.Dispose();
if (listBoxFiler.SelectedItems.Count == 0)
{
System.ComponentModel.ComponentResourceManager resources =
new System.ComponentModel.ComponentResourceManager(typeof(Form1));
pictboxOrtofoto.Image =
((System.Drawing.Image)(resources.GetObject("pictboxOrtofoto.Image")));
}
else
{
FileHandler fh = (FileHandler)listBoxFiler.SelectedItem;
filenameOrto = fh.ToString();
try
{
pictboxOrtofoto.Image = (Bitmap)Image.FromFile(filenameOrto);
displayStyringsfiler();
}
catch
{
System.ComponentModel.ComponentResourceManager resources =
new System.ComponentModel.ComponentResourceManager(typeof(Form1));
pictboxOrtofoto.Image =
((System.Drawing.Image)(resources.GetObject("pictboxOrtofoto.ErrorImage")));
}
}
if (listBoxFiler.Items.Count > 0) enableButtons();
else disableButtons();
}
private void disableButtons()
{
radioButtonJGW.Enabled = false;
radioButtonMMM.Enabled = false;
radioButtonSOSI.Enabled = false;
checkBoxFilliste.Enabled = false;
btnFullfør.Enabled = false;
}
private void enableButtons()
{
radioButtonJGW.Enabled = true;
radioButtonMMM.Enabled = true;
radioButtonSOSI.Enabled = true;
checkBoxFilliste.Enabled = true;
if (radioButtonJGW.Checked || radioButtonMMM.Checked || radioButtonSOSI.Checked)
btnFullfør.Enabled = true;
}
private void displayStyringsfiler()
{
try
{
FileHandler fh = (FileHandler) listBoxFiler.SelectedItem;
textBoxJGW.Text = fh.toJGW();
textBoxMMM.Text = fh.toMMM();
textBoxSOSI.Text = fh.toSOSI();
}
catch
{
textBoxMMM.Text = "";
textBoxJGW.Text = "";
textBoxSOSI.Text = "";
}
}
private void btnFullfør_Click(object sender, EventArgs e)
{
string fileList = "";
FileHandler fh1 = null;
foreach (FileHandler fh in listBoxFiler.Items)
{
if (checkBoxFilliste.Checked) fileList += fh.ToString() + "\r\n";
if (radioButtonJGW.Checked) fh.writeToFile(FileHandler.TYPE_JGW);
if (radioButtonMMM.Checked) fh.writeToFile(FileHandler.TYPE_MMM);
if (radioButtonSOSI.Checked) fh.writeToFile(FileHandler.TYPE_SOSI);
}
try
{
fh1 = (FileHandler)listBoxFiler.Items[0];
}
catch { }
if (fh1 != null && checkBoxFilliste.Checked)
{
fh1.createFileList(fileList);
}
toolStripStatusLabel1.Text = "Suksess!";
MessageBox.Show("Ferdig med å konvertere!", "JoddGewe 0.1",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void radioButtonJGW_CheckedChanged(object sender, EventArgs e)
{
btnFullfør.Enabled = true;
toolStripStatusLabel1.Text = "Klar til å konvertere styringsfiler!";
}
private void radioButtonMMM_CheckedChanged(object sender, EventArgs e)
{
btnFullfør.Enabled = true;
toolStripStatusLabel1.Text = "Klar til å konvertere styringsfiler!";
}
private void radioButtonSOSI_CheckedChanged(object sender, EventArgs e)
{
btnFullfør.Enabled = true;
toolStripStatusLabel1.Text = "Klar til å konvertere styringsfiler!";
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Moq;
using NUnit.Framework;
using Ploeh.AutoFixture;
using RememBeer.Models.Contracts;
using RememBeer.Models.Dtos;
using RememBeer.Models.Factories;
using RememBeer.Services.RankingStrategies;
using RememBeer.Tests.Utils;
namespace RememBeer.Tests.Services.RankingStrategies.DoubleOverallScoreStrategyTests
{
[TestFixture]
public class GetBeerRank_Should : TestClassBase
{
[Test]
public void ThrowArgumentNullException_WhenReviewsArgumentIsNull()
{
// Arrange
var factory = new Mock<IModelFactory>();
var beer = new Mock<IBeer>();
var strategy = new DoubleOverallScoreStrategy(factory.Object);
// Act & Assert
Assert.Throws<ArgumentNullException>(() => strategy.GetBeerRank(null, beer.Object));
}
[Test]
public void ThrowArgumentNullException_WhenBeerArgumentIsNull()
{
// Arrange
var factory = new Mock<IModelFactory>();
var reviews = new Mock<IEnumerable<IBeerReview>>();
var strategy = new DoubleOverallScoreStrategy(factory.Object);
// Act & Assert
Assert.Throws<ArgumentNullException>(() => strategy.GetBeerRank(reviews.Object, null));
}
[Test]
public void ThrowArgumentException_WhenReviewsAreEmpty()
{
// Arrange
var factory = new Mock<IModelFactory>();
var beer = new Mock<IBeer>();
var reviews = new List<IBeerReview>();
var strategy = new DoubleOverallScoreStrategy(factory.Object);
// Act & Assert
Assert.Throws<ArgumentException>(() => strategy.GetBeerRank(reviews, beer.Object));
}
[Test]
public void CallFactoryCreateBeerRankMethod_WithCorrectParamsOnce()
{
// Arrange
var overallScore = this.Fixture.Create<int>();
var tasteScore = this.Fixture.Create<int>();
var smellScore = this.Fixture.Create<int>();
var looksScore = this.Fixture.Create<int>();
var factory = new Mock<IModelFactory>();
var mockedReview = new Mock<IBeerReview>();
mockedReview.Setup(r => r.Overall).Returns(overallScore);
mockedReview.Setup(r => r.Taste).Returns(tasteScore);
mockedReview.Setup(r => r.Smell).Returns(smellScore);
mockedReview.Setup(r => r.Look).Returns(looksScore);
var mockedReview2 = new Mock<IBeerReview>();
mockedReview.Setup(r => r.Overall).Returns(overallScore + this.Fixture.Create<int>());
mockedReview.Setup(r => r.Taste).Returns(tasteScore + this.Fixture.Create<int>());
mockedReview.Setup(r => r.Smell).Returns(smellScore + this.Fixture.Create<int>());
mockedReview.Setup(r => r.Look).Returns(looksScore + this.Fixture.Create<int>());
var beer = new Mock<IBeer>();
var reviews = new List<IBeerReview>()
{
mockedReview.Object,
mockedReview2.Object
};
var expectedAggregateScore = reviews.Sum(beerReview =>
(decimal)(2 * beerReview.Overall
+ beerReview.Look
+ beerReview.Smell
+ beerReview.Taste)
/ 5) / reviews.Count;
var expectedOverall = (decimal)reviews.Sum(r => r.Overall) / reviews.Count;
var expectedTaste = (decimal)reviews.Sum(r => r.Taste) / reviews.Count;
var expectedSmell = (decimal)reviews.Sum(r => r.Smell) / reviews.Count;
var expectedLook = (decimal)reviews.Sum(r => r.Look) / reviews.Count;
var strategy = new DoubleOverallScoreStrategy(factory.Object);
// Act
var result = strategy.GetBeerRank(reviews, beer.Object);
// Assert
factory.Verify(
f => f.CreateBeerRank(expectedOverall,
expectedTaste,
expectedLook,
expectedSmell,
beer.Object,
expectedAggregateScore,
reviews.Count),
Times.Once);
}
[Test]
public void ReturnResultFromFactory()
{
// Arrange
var expectedRank = new Mock<IBeerRank>();
var overallScore = this.Fixture.Create<int>();
var tasteScore = this.Fixture.Create<int>();
var smellScore = this.Fixture.Create<int>();
var looksScore = this.Fixture.Create<int>();
var expectedAggregateScore = (decimal)((overallScore * 2) + tasteScore + smellScore + looksScore) / 5;
var mockedReview = new Mock<IBeerReview>();
mockedReview.Setup(r => r.Overall).Returns(overallScore);
mockedReview.Setup(r => r.Taste).Returns(tasteScore);
mockedReview.Setup(r => r.Smell).Returns(smellScore);
mockedReview.Setup(r => r.Look).Returns(looksScore);
var beer = new Mock<IBeer>();
var reviews = new List<IBeerReview>()
{
mockedReview.Object
};
var factory = new Mock<IModelFactory>();
factory.Setup(
f => f.CreateBeerRank(overallScore,
tasteScore,
looksScore,
smellScore,
beer.Object,
expectedAggregateScore,
1))
.Returns(expectedRank.Object);
var strategy = new DoubleOverallScoreStrategy(factory.Object);
// Act
var result = strategy.GetBeerRank(reviews, beer.Object);
// Assert
Assert.IsNotNull(result);
Assert.AreSame(expectedRank.Object, result);
}
}
}
|
//******************************************************************************************************
// FrequencyValue.cs - Gbtc
//
// Copyright © 2012, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
// not use this file except in compliance with the License. You may obtain a copy of the License at:
//
// http://www.opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 11/12/2004 - J. Ritchie Carroll
// Generated original version of source code.
// 09/15/2009 - Stephen C. Wills
// Added new header and license agreement.
// 12/17/2012 - Starlynn Danyelle Gilliam
// Modified Header.
//
//******************************************************************************************************
using System;
using System.Runtime.Serialization;
namespace GSF.PhasorProtocols.BPAPDCstream
{
/// <summary>
/// Represents the BPA PDCstream implementation of a <see cref="IFrequencyValue"/>.
/// </summary>
[Serializable]
public class FrequencyValue : FrequencyValueBase
{
#region [ Constructors ]
/// <summary>
/// Creates a new <see cref="FrequencyValue"/>.
/// </summary>
/// <param name="parent">The <see cref="IDataCell"/> parent of this <see cref="FrequencyValue"/>.</param>
/// <param name="frequencyDefinition">The <see cref="IFrequencyDefinition"/> associated with this <see cref="FrequencyValue"/>.</param>
public FrequencyValue(IDataCell parent, IFrequencyDefinition frequencyDefinition)
: base(parent, frequencyDefinition)
{
}
/// <summary>
/// Creates a new <see cref="FrequencyValue"/> from specified parameters.
/// </summary>
/// <param name="parent">The <see cref="DataCell"/> parent of this <see cref="FrequencyValue"/>.</param>
/// <param name="frequencyDefinition">The <see cref="FrequencyDefinition"/> associated with this <see cref="FrequencyValue"/>.</param>
/// <param name="frequency">The floating point value that represents this <see cref="FrequencyValue"/>.</param>
/// <param name="dfdt">The floating point value that represents the change in this <see cref="FrequencyValue"/> over time.</param>
public FrequencyValue(DataCell parent, FrequencyDefinition frequencyDefinition, double frequency, double dfdt)
: base(parent, frequencyDefinition, frequency, dfdt)
{
}
/// <summary>
/// Creates a new <see cref="FrequencyValue"/> from serialization parameters.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> with populated with data.</param>
/// <param name="context">The source <see cref="StreamingContext"/> for this deserialization.</param>
protected FrequencyValue(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endregion
#region [ Properties ]
/// <summary>
/// Gets or sets the <see cref="DataCell"/> parent of this <see cref="FrequencyValue"/>.
/// </summary>
public new virtual DataCell Parent
{
get => base.Parent as DataCell;
set => base.Parent = value;
}
/// <summary>
/// Gets or sets the <see cref="FrequencyDefinition"/> associated with this <see cref="FrequencyValue"/>.
/// </summary>
public new virtual FrequencyDefinition Definition
{
get => base.Definition as FrequencyDefinition;
set => base.Definition = value;
}
/// <summary>
/// Gets the length of the <see cref="BodyImage"/>.
/// </summary>
/// <remarks>
/// The base implementation assumes fixed integer values are represented as 16-bit signed
/// integers and floating point values are represented as 32-bit single-precision floating-point
/// values (i.e., short and float data types respectively).
/// </remarks>
protected override int BodyLength =>
Definition.Parent.IsPdcBlockSection ? 2 : base.BodyLength; // PMUs in PDC block do not include Df/Dt
/// <summary>
/// Gets the binary body image of the <see cref="FrequencyValue"/> object.
/// </summary>
protected override byte[] BodyImage
{
get
{
// PMUs in PDC block do not include Df/Dt
if (!Definition.Parent.IsPdcBlockSection)
return base.BodyImage;
byte[] buffer = new byte[2];
BigEndian.CopyBytes((short)UnscaledFrequency, buffer, 0);
return buffer;
}
}
#endregion
#region [ Methods ]
/// <summary>
/// Parses the binary body image.
/// </summary>
/// <param name="buffer">Binary image to parse.</param>
/// <param name="startIndex">Start index into <paramref name="buffer"/> to begin parsing.</param>
/// <param name="length">Length of valid data within <paramref name="buffer"/>.</param>
/// <returns>The length of the data that was parsed.</returns>
protected override int ParseBodyImage(byte[] buffer, int startIndex, int length)
{
// PMUs in PDC block do not include Df/Dt
if (Definition.Parent.IsPdcBlockSection)
{
UnscaledFrequency = BigEndian.ToInt16(buffer, startIndex);
return 2;
}
return base.ParseBodyImage(buffer, startIndex, length);
}
#endregion
#region [ Static ]
// Static Methods
// Calculates binary length of a frequency value based on its definition
internal static uint CalculateBinaryLength(IFrequencyDefinition definition)
{
// The frequency definition will determine the binary length based on data format
return (uint)new FrequencyValue(null, definition).BinaryLength;
}
// Delegate handler to create a new BPA PDCstream frequency value
internal static IFrequencyValue CreateNewValue(IDataCell parent, IFrequencyDefinition definition, byte[] buffer, int startIndex, out int parsedLength)
{
IFrequencyValue frequency = new FrequencyValue(parent, definition);
parsedLength = frequency.ParseBinaryImage(buffer, startIndex, 0);
return frequency;
}
#endregion
}
} |
using SMSServices.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using WebApi.ErrorHelper;
namespace SMSServices.Controllers
{
public class TeachersSubjectsController : ApiController
{
private SMSEntities entities = new SMSEntities();
// GET api/<controller>
[Route("api/TeachersSubjects/All/{teacherId}")]
//public IEnumerable<TeachersSubjects> Get()
public HttpResponseMessage Get(int teacherId)
{
entities.Configuration.ProxyCreationEnabled = false;
var query = entities.TeachersSubjects//.Include("Classes").Include("Shifts");
//query.Include("Sections")
.Where(t => t.TeacherID == teacherId)
.Select(e => new
{
e.TeacherSubjectID,
e.TeacherID,
TeacherName = e.Teachers.Name,
e.SubjectID,
SubjectCode = e.Subjects.Code,
SubjectName = e.Subjects.Name,
SubjectNameAr = e.Subjects.NameAr,
Id = e.SubjectID,
Code = e.Subjects.Code,
Name = e.Subjects.Name,
NameAr = e.Subjects.NameAr
});
//return query.ToList(); //entities.TeachersSubjects.Include("Classes").Include("Shifts").Include("Sections");
return this.Request.CreateResponse(HttpStatusCode.OK, query.ToList());
}
// POST api/<controller>
[Route("api/TeachersSubjects/{TeacherID}/{SubjectIDs}")]
public HttpResponseMessage Post(int TeacherID, string SubjectIDs)
{
try
{
foreach (string ID in SubjectIDs.Split(','))
{
entities.TeachersSubjects.Add(new TeachersSubjects()
{
TeacherID = TeacherID,
SubjectID = Convert.ToInt32(ID)
});
}
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, "Done ...");
}
//catch (Exception e)
//{
// return Request.CreateResponse(HttpStatusCode.BadRequest, "I have some issue ...");
//}
catch (DbUpdateException dbEx)
{
throw dbEx;
//return Request.CreateResponse(HttpStatusCode.BadRequest, "I have more issue ...");
//StringBuilder sb = new StringBuilder();
//foreach (var item in dbEx.EntityValidationErrors)
//{
// sb.Append(item + " errors: ");
// foreach (var i in item.ValidationErrors)
// {
// sb.Append(i.PropertyName + " : " + i.ErrorMessage);
// }
// sb.Append(Environment.NewLine);
//}
////throw new ApiDataException(GetErrorCode(dbEx), sb.ToString(), HttpStatusCode.BadRequest);
//throw new ApiDataException(1021, "too many errors ...", HttpStatusCode.BadRequest);
//return Request.CreateResponse(HttpStatusCode.OK, sb.ToString());
}
//catch (DbUpdateException ex)
//{
// throw ex;
// //return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
//}
}
//// GET api/<controller>/5/1/2
//[Route("api/TeachersSubjects/{ShiftId}/{ClassId}/{SectionId}")]
//public TeachersSubjects Get(int ShiftId, int ClassId, int SectionId)
//{
// entities.Configuration.ProxyCreationEnabled = false;
// TeachersSubjects TeacherSubject = entities.TeachersSubjects
// .Where(t => t.ShiftID == ShiftId && t.ClassID == ClassId && t.SectionID == SectionId).FirstOrDefault();
// if (TeacherSubject == null)
// {
// TeacherSubject = new TeachersSubjects() { ClassID = 0 };
// }
// return TeacherSubject;
//}
//[Route("api/TeachersSubjectsById/{id}")]
//public TeachersSubjects Get(int id)
//{
// entities.Configuration.ProxyCreationEnabled = false;
// return entities.TeachersSubjects.Where(t => t.TeacherSubjectID == id).FirstOrDefault();
//}
// POST api/<controller>
//public HttpResponseMessage Post(TeachersSubjects teacher)
//{
// try
// {
// entities.TeachersSubjects.Add(new TeachersSubjects()
// {
// TeacherID = teacher.TeacherID,
// SubjectID = teacher.SubjectID
// });
// entities.SaveChanges();
// return Request.CreateResponse(HttpStatusCode.OK, "Done ...");
// }
// //catch (Exception e)
// //{
// // return Request.CreateResponse(HttpStatusCode.BadRequest, "I have some issue ...");
// //}
// catch (DbUpdateException dbEx)
// {
// throw dbEx;
// //return Request.CreateResponse(HttpStatusCode.BadRequest, "I have more issue ...");
// //StringBuilder sb = new StringBuilder();
// //foreach (var item in dbEx.EntityValidationErrors)
// //{
// // sb.Append(item + " errors: ");
// // foreach (var i in item.ValidationErrors)
// // {
// // sb.Append(i.PropertyName + " : " + i.ErrorMessage);
// // }
// // sb.Append(Environment.NewLine);
// //}
// ////throw new ApiDataException(GetErrorCode(dbEx), sb.ToString(), HttpStatusCode.BadRequest);
// //throw new ApiDataException(1021, "too many errors ...", HttpStatusCode.BadRequest);
// //return Request.CreateResponse(HttpStatusCode.OK, sb.ToString());
// }
// //catch (DbUpdateException ex)
// //{
// // throw ex;
// // //return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
// //}
//}
private int GetErrorCode(DbEntityValidationException dbEx)
{
int ErrorCode = (int)HttpStatusCode.BadRequest;
if (dbEx.InnerException != null && dbEx.InnerException.InnerException != null)
{
if (dbEx.InnerException.InnerException is SqlException)
{
ErrorCode = (dbEx.InnerException.InnerException as SqlException).Number;
}
}
return ErrorCode;
}
// PUT api/<controller>/5
public void Put(TeachersSubjects TeacherSubject)
{
try
{
var entity = entities.TeachersSubjects.Find(TeacherSubject.TeacherSubjectID);
if (entity != null)
{
entities.Entry(entity).CurrentValues.SetValues(TeacherSubject);
entities.SaveChanges();
}
}
catch //(DbUpdateException)
{
throw;
}
}
/*
// DELETE api/<controller>/5
public void Delete(int id)
{
try
{
var teacher = new TeachersSubjects { TeacherId = id };
if (teacher != null)
{
entities.Entry(teacher).State = EntityState.Deleted;
entities.TeachersSubjects.Remove(teacher);
entities.SaveChanges();
}
}
catch (Exception)
{
throw;
}
}
*/
[HttpPost]
[Route("api/RemoveTeacherSubject/{id}")]
public HttpResponseMessage RemoveTeacherSubject(int id)
{
try
{
var TeacherSubject = new TeachersSubjects { TeacherSubjectID = id };
if (TeacherSubject != null)
{
entities.Entry(TeacherSubject).State = EntityState.Deleted;
entities.TeachersSubjects.Remove(TeacherSubject);
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, "Removed...");
}
else
return Request.CreateResponse(HttpStatusCode.NotFound, "not found...");
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
//return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message +
// " inner ex: " + ex.InnerException !=null ? ex.InnerException.Message : "null" );
//throw;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
entities.Dispose();
}
base.Dispose(disposing);
}
}
} |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
public class KinectManager : MonoBehaviour
{
public enum Smoothing : int { None, Default, Medium, Aggressive }
// Public Bool to determine how many players there are. Default of one user.
public bool TwoUsers = false;
// Public Bool to determine if the sensor is used in near mode.
public bool NearMode = false;
// Public Bool to determine whether to receive and compute the user map
public bool ComputeUserMap = false;
// Public Bool to determine whether to receive and compute the color map
public bool ComputeColorMap = false;
// Public Bool to determine whether to display user map on the GUI
public bool DisplayUserMap = false;
// Public Bool to determine whether to display color map on the GUI
public bool DisplayColorMap = false;
// Public Bool to determine whether to display the skeleton lines on user map
public bool DisplaySkeletonLines = false;
// Public Floats to specify the width and height of the depth and color maps as % of the camera width and height
// if percents are zero, they are calculated based on actual Kinect image´s width and height
public float MapsPercentWidth = 0f;
public float MapsPercentHeight = 0f;
// How high off the ground is the sensor (in meters).
public float SensorHeight = 1.0f;
// Kinect elevation angle (in degrees)
public int SensorAngle = 0;
// Minimum user distance in order to process skeleton data
public float MinUserDistance = 1.0f;
// Public Bool to determine whether to detect only the closest user or not
public bool DetectClosestUser = true;
// Public Bool to determine whether to use only the tracked joints (and ignore the inferred ones)
public bool IgnoreInferredJoints = true;
// Selection of smoothing parameters
public Smoothing smoothing = Smoothing.Default;
// Public Bool to determine the use of additional filters
public bool UseBoneOrientationsFilter = false;
public bool UseClippedLegsFilter = false;
public bool UseBoneOrientationsConstraint = true;
public bool UseSelfIntersectionConstraint = false;
// Lists of GameObjects that will be controlled by which player.
public List<GameObject> Player1Avatars;
public List<GameObject> Player2Avatars;
// Calibration poses for each player, if needed
public KinectGestures.Gestures Player1CalibrationPose;
public KinectGestures.Gestures Player2CalibrationPose;
// List of Gestures to detect for each player
public List<KinectGestures.Gestures> Player1Gestures;
public List<KinectGestures.Gestures> Player2Gestures;
// Minimum time between gesture detections
public float MinTimeBetweenGestures = 0f;
// List of Gesture Listeners. They must implement KinectGestures.GestureListenerInterface
public List<MonoBehaviour> GestureListeners;
// GUI Text to show messages.
public GameObject CalibrationText;
// GUI Texture to display the hand cursor for Player1
public GameObject HandCursor1;
// GUI Texture to display the hand cursor for Player1
public GameObject HandCursor2;
// Bool to specify whether Left/Right-hand-cursor and the Click-gesture control the mouse cursor and click
public bool ControlMouseCursor = false;
// Bool to keep track of whether Kinect has been initialized
private bool KinectInitialized = false;
// Bools to keep track of who is currently calibrated.
private bool Player1Calibrated = false;
private bool Player2Calibrated = false;
private bool AllPlayersCalibrated = false;
// Values to track which ID (assigned by the Kinect) is player 1 and player 2.
private uint Player1ID;
private uint Player2ID;
// Lists of AvatarControllers that will let the models get updated.
private List<AvatarController> Player1Controllers;
private List<AvatarController> Player2Controllers;
// User Map vars.
private Texture2D usersLblTex;
private Color32[] usersMapColors;
private ushort[] usersPrevState;
private Rect usersMapRect;
private int usersMapSize;
private Texture2D usersClrTex;
//Color[] usersClrColors;
private Rect usersClrRect;
//short[] usersLabelMap;
private short[] usersDepthMap;
private float[] usersHistogramMap;
// List of all users
private List<uint> allUsers;
// Image stream handles for the kinect
private IntPtr colorStreamHandle;
private IntPtr depthStreamHandle;
// Color image data, if used
private Color32[] colorImage;
private byte[] usersColorMap;
// Skeleton related structures
private KinectWrapper.NuiSkeletonFrame skeletonFrame;
private KinectWrapper.NuiTransformSmoothParameters smoothParameters;
private int player1Index, player2Index;
// Skeleton tracking states, positions and joints' orientations
private Vector3 player1Pos, player2Pos;
private Matrix4x4 player1Ori, player2Ori;
private bool[] player1JointsTracked, player2JointsTracked;
private bool[] player1PrevTracked, player2PrevTracked;
private Vector3[] player1JointsPos, player2JointsPos;
private Matrix4x4[] player1JointsOri, player2JointsOri;
private KinectWrapper.NuiSkeletonBoneOrientation[] jointOrientations;
// Calibration gesture data for each player
private KinectGestures.GestureData player1CalibrationData;
private KinectGestures.GestureData player2CalibrationData;
// Lists of gesture data, for each player
private List<KinectGestures.GestureData> player1Gestures = new List<KinectGestures.GestureData>();
private List<KinectGestures.GestureData> player2Gestures = new List<KinectGestures.GestureData>();
// general gesture tracking time start
private float[] gestureTrackingAtTime;
// List of Gesture Listeners. They must implement KinectGestures.GestureListenerInterface
public List<KinectGestures.GestureListenerInterface> gestureListeners;
private Matrix4x4 kinectToWorld, flipMatrix;
private static KinectManager instance;
// Timer for controlling Filter Lerp blends.
private float lastNuiTime;
// Filters
private TrackingStateFilter[] trackingStateFilter;
private BoneOrientationsFilter[] boneOrientationFilter;
private ClippedLegsFilter[] clippedLegsFilter;
private BoneOrientationsConstraint boneConstraintsFilter;
private SelfIntersectionConstraint selfIntersectionConstraint;
// returns the single KinectManager instance
public static KinectManager Instance
{
get
{
return instance;
}
}
// checks if Kinect is initialized and ready to use. If not, there was an error during Kinect-sensor initialization
public static bool IsKinectInitialized()
{
return instance != null ? instance.KinectInitialized : false;
}
// checks if Kinect is initialized and ready to use. If not, there was an error during Kinect-sensor initialization
public bool IsInitialized()
{
return KinectInitialized;
}
// this function is used internally by AvatarController
public static bool IsCalibrationNeeded()
{
return false;
}
// // returns the raw depth/user data,if ComputeUserMap is true
// public short[] GetUsersDepthMap()
// {
// return usersDepthMap;
// }
// returns the depth data for a specific pixel,if ComputeUserMap is true
public short GetDepthForPixel(int x, int y)
{
int index = y * KinectWrapper.Constants.ImageWidth + x;
if(index >= 0 && index < usersDepthMap.Length)
return usersDepthMap[index];
else
return 0;
}
// returns the depth map position for a 3d joint position
public Vector2 GetDepthMapPosForJointPos(Vector3 posJoint)
{
Vector3 vDepthPos = KinectWrapper.MapSkeletonPointToDepthPoint(posJoint);
Vector2 vMapPos = new Vector2(vDepthPos.x, vDepthPos.y);
return vMapPos;
}
// returns the color map position for a depth 2d position
public Vector2 GetColorMapPosForDepthPos(Vector2 posDepth)
{
int cx, cy;
KinectWrapper.NuiImageViewArea pcViewArea = new KinectWrapper.NuiImageViewArea
{
eDigitalZoom = 0,
lCenterX = 0,
lCenterY = 0
};
int hr = KinectWrapper.NuiImageGetColorPixelCoordinatesFromDepthPixelAtResolution(
KinectWrapper.Constants.ImageResolution,
KinectWrapper.Constants.ImageResolution,
ref pcViewArea,
(int)posDepth.x, (int)posDepth.y, GetDepthForPixel((int)posDepth.x, (int)posDepth.y),
out cx, out cy);
return new Vector2(cx, cy);
}
// returns the depth image/users histogram texture,if ComputeUserMap is true
public Texture2D GetUsersLblTex()
{
return usersLblTex;
}
// returns the color image texture,if ComputeColorMap is true
public Texture2D GetUsersClrTex()
{
return usersClrTex;
}
// returns true if at least one user is currently detected by the sensor
public bool IsUserDetected()
{
return KinectInitialized && (allUsers.Count > 0);
}
// returns the UserID of Player1, or 0 if no Player1 is detected
public uint GetPlayer1ID()
{
return Player1ID;
}
// returns the UserID of Player2, or 0 if no Player2 is detected
public uint GetPlayer2ID()
{
return Player2ID;
}
// returns true if the User is calibrated and ready to use
public bool IsPlayerCalibrated(uint UserId)
{
if(UserId == Player1ID)
return Player1Calibrated;
else if(UserId == Player2ID)
return Player2Calibrated;
return false;
}
// returns the raw unmodified joint position, as returned by the Kinect sensor
public Vector3 GetRawSkeletonJointPos(uint UserId, int joint)
{
if(UserId == Player1ID)
return joint >= 0 && joint < player1JointsPos.Length ? (Vector3)skeletonFrame.SkeletonData[player1Index].SkeletonPositions[joint] : Vector3.zero;
else if(UserId == Player2ID)
return joint >= 0 && joint < player2JointsPos.Length ? (Vector3)skeletonFrame.SkeletonData[player2Index].SkeletonPositions[joint] : Vector3.zero;
return Vector3.zero;
}
// returns the User position, relative to the Kinect-sensor, in meters
public Vector3 GetUserPosition(uint UserId)
{
if(UserId == Player1ID)
return player1Pos;
else if(UserId == Player2ID)
return player2Pos;
return Vector3.zero;
}
// returns the User rotation, relative to the Kinect-sensor
public Quaternion GetUserOrientation(uint UserId, bool flip)
{
if(UserId == Player1ID && player1JointsTracked[(int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter])
return ConvertMatrixToQuat(player1Ori, (int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter, flip);
else if(UserId == Player2ID && player2JointsTracked[(int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter])
return ConvertMatrixToQuat(player2Ori, (int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter, flip);
return Quaternion.identity;
}
// returns true if the given joint of the specified user is being tracked
public bool IsJointTracked(uint UserId, int joint)
{
if(UserId == Player1ID)
return joint >= 0 && joint < player1JointsTracked.Length ? player1JointsTracked[joint] : false;
else if(UserId == Player2ID)
return joint >= 0 && joint < player2JointsTracked.Length ? player2JointsTracked[joint] : false;
return false;
}
// returns the joint position of the specified user, relative to the Kinect-sensor, in meters
public Vector3 GetJointPosition(uint UserId, int joint)
{
if(UserId == Player1ID)
return joint >= 0 && joint < player1JointsPos.Length ? player1JointsPos[joint] : Vector3.zero;
else if(UserId == Player2ID)
return joint >= 0 && joint < player2JointsPos.Length ? player2JointsPos[joint] : Vector3.zero;
return Vector3.zero;
}
// returns the local joint position of the specified user, relative to the parent joint, in meters
public Vector3 GetJointLocalPosition(uint UserId, int joint)
{
int parent = KinectWrapper.GetSkeletonJointParent(joint);
if(UserId == Player1ID)
return joint >= 0 && joint < player1JointsPos.Length ?
(player1JointsPos[joint] - player1JointsPos[parent]) : Vector3.zero;
else if(UserId == Player2ID)
return joint >= 0 && joint < player2JointsPos.Length ?
(player2JointsPos[joint] - player2JointsPos[parent]) : Vector3.zero;
return Vector3.zero;
}
// returns the joint rotation of the specified user, relative to the Kinect-sensor
public Quaternion GetJointOrientation(uint UserId, int joint, bool flip)
{
if(UserId == Player1ID)
{
if(joint >= 0 && joint < player1JointsOri.Length && player1JointsTracked[joint])
return ConvertMatrixToQuat(player1JointsOri[joint], joint, flip);
}
else if(UserId == Player2ID)
{
if(joint >= 0 && joint < player2JointsOri.Length && player2JointsTracked[joint])
return ConvertMatrixToQuat(player2JointsOri[joint], joint, flip);
}
return Quaternion.identity;
}
// returns the joint rotation of the specified user, relative to the parent joint
public Quaternion GetJointLocalOrientation(uint UserId, int joint, bool flip)
{
int parent = KinectWrapper.GetSkeletonJointParent(joint);
if(UserId == Player1ID)
{
if(joint >= 0 && joint < player1JointsOri.Length && player1JointsTracked[joint])
{
Matrix4x4 localMat = (player1JointsOri[parent].inverse * player1JointsOri[joint]);
return Quaternion.LookRotation(localMat.GetColumn(2), localMat.GetColumn(1));
}
}
else if(UserId == Player2ID)
{
if(joint >= 0 && joint < player2JointsOri.Length && player2JointsTracked[joint])
{
Matrix4x4 localMat = (player2JointsOri[parent].inverse * player2JointsOri[joint]);
return Quaternion.LookRotation(localMat.GetColumn(2), localMat.GetColumn(1));
}
}
return Quaternion.identity;
}
// returns the direction between baseJoint and nextJoint, for the specified user
public Vector3 GetDirectionBetweenJoints(uint UserId, int baseJoint, int nextJoint, bool flipX, bool flipZ)
{
Vector3 jointDir = Vector3.zero;
if(UserId == Player1ID)
{
if(baseJoint >= 0 && baseJoint < player1JointsPos.Length && player1JointsTracked[baseJoint] &&
nextJoint >= 0 && nextJoint < player1JointsPos.Length && player1JointsTracked[nextJoint])
{
jointDir = player1JointsPos[nextJoint] - player1JointsPos[baseJoint];
}
}
else if(UserId == Player2ID)
{
if(baseJoint >= 0 && baseJoint < player2JointsPos.Length && player2JointsTracked[baseJoint] &&
nextJoint >= 0 && nextJoint < player2JointsPos.Length && player2JointsTracked[nextJoint])
{
jointDir = player2JointsPos[nextJoint] - player2JointsPos[baseJoint];
}
}
if(jointDir != Vector3.zero)
{
if(flipX)
jointDir.x = -jointDir.x;
if(flipZ)
jointDir.z = -jointDir.z;
}
return jointDir;
}
// adds a gesture to the list of detected gestures for the specified user
public void DetectGesture(uint UserId, KinectGestures.Gestures gesture)
{
int index = GetGestureIndex(UserId, gesture);
if(index >= 0)
DeleteGesture(UserId, gesture);
KinectGestures.GestureData gestureData = new KinectGestures.GestureData();
gestureData.userId = UserId;
gestureData.gesture = gesture;
gestureData.state = 0;
gestureData.joint = 0;
gestureData.progress = 0f;
gestureData.complete = false;
gestureData.cancelled = false;
gestureData.checkForGestures = new List<KinectGestures.Gestures>();
switch(gesture)
{
case KinectGestures.Gestures.ZoomIn:
gestureData.checkForGestures.Add(KinectGestures.Gestures.ZoomOut);
gestureData.checkForGestures.Add(KinectGestures.Gestures.Wheel);
break;
case KinectGestures.Gestures.ZoomOut:
gestureData.checkForGestures.Add(KinectGestures.Gestures.ZoomIn);
gestureData.checkForGestures.Add(KinectGestures.Gestures.Wheel);
break;
case KinectGestures.Gestures.Wheel:
gestureData.checkForGestures.Add(KinectGestures.Gestures.ZoomIn);
gestureData.checkForGestures.Add(KinectGestures.Gestures.ZoomOut);
break;
// case KinectGestures.Gestures.Jump:
// gestureData.checkForGestures.Add(KinectGestures.Gestures.Squat);
// break;
//
// case KinectGestures.Gestures.Squat:
// gestureData.checkForGestures.Add(KinectGestures.Gestures.Jump);
// break;
//
// case KinectGestures.Gestures.Push:
// gestureData.checkForGestures.Add(KinectGestures.Gestures.Pull);
// break;
//
// case KinectGestures.Gestures.Pull:
// gestureData.checkForGestures.Add(KinectGestures.Gestures.Push);
// break;
}
if(UserId == Player1ID)
player1Gestures.Add(gestureData);
else if(UserId == Player2ID)
player2Gestures.Add(gestureData);
}
// resets the gesture-data state for the given gesture of the specified user
public bool ResetGesture(uint UserId, KinectGestures.Gestures gesture)
{
int index = GetGestureIndex(UserId, gesture);
if(index < 0)
return false;
KinectGestures.GestureData gestureData = (UserId == Player1ID) ? player1Gestures[index] : player2Gestures[index];
gestureData.state = 0;
gestureData.joint = 0;
gestureData.progress = 0f;
gestureData.complete = false;
gestureData.cancelled = false;
gestureData.startTrackingAtTime = Time.realtimeSinceStartup + KinectWrapper.Constants.MinTimeBetweenSameGestures;
if(UserId == Player1ID)
player1Gestures[index] = gestureData;
else if(UserId == Player2ID)
player2Gestures[index] = gestureData;
return true;
}
// resets the gesture-data states for all detected gestures of the specified user
public void ResetPlayerGestures(uint UserId)
{
if(UserId == Player1ID)
{
int listSize = player1Gestures.Count;
for(int i = 0; i < listSize; i++)
{
ResetGesture(UserId, player1Gestures[i].gesture);
}
}
else if(UserId == Player2ID)
{
int listSize = player2Gestures.Count;
for(int i = 0; i < listSize; i++)
{
ResetGesture(UserId, player2Gestures[i].gesture);
}
}
}
// deletes the given gesture from the list of detected gestures for the specified user
public bool DeleteGesture(uint UserId, KinectGestures.Gestures gesture)
{
int index = GetGestureIndex(UserId, gesture);
if(index < 0)
return false;
if(UserId == Player1ID)
player1Gestures.RemoveAt(index);
else if(UserId == Player2ID)
player2Gestures.RemoveAt(index);
return true;
}
// clears detected gestures list for the specified user
public void ClearGestures(uint UserId)
{
if(UserId == Player1ID)
{
player1Gestures.Clear();
}
else if(UserId == Player2ID)
{
player2Gestures.Clear();
}
}
// returns the count of detected gestures in the list of detected gestures for the specified user
public int GetGesturesCount(uint UserId)
{
if(UserId == Player1ID)
return player1Gestures.Count;
else if(UserId == Player2ID)
return player2Gestures.Count;
return 0;
}
// returns the list of detected gestures for the specified user
public List<KinectGestures.Gestures> GetGesturesList(uint UserId)
{
List<KinectGestures.Gestures> list = new List<KinectGestures.Gestures>();
if(UserId == Player1ID)
{
foreach(KinectGestures.GestureData data in player1Gestures)
list.Add(data.gesture);
}
else if(UserId == Player2ID)
{
foreach(KinectGestures.GestureData data in player1Gestures)
list.Add(data.gesture);
}
return list;
}
// returns true, if the given gesture is in the list of detected gestures for the specified user
public bool IsGestureDetected(uint UserId, KinectGestures.Gestures gesture)
{
int index = GetGestureIndex(UserId, gesture);
return index >= 0;
}
// returns true, if the given gesture for the specified user is complete
public bool IsGestureComplete(uint UserId, KinectGestures.Gestures gesture, bool bResetOnComplete)
{
int index = GetGestureIndex(UserId, gesture);
if(index >= 0)
{
if(UserId == Player1ID)
{
KinectGestures.GestureData gestureData = player1Gestures[index];
if(bResetOnComplete && gestureData.complete)
{
ResetPlayerGestures(UserId);
return true;
}
return gestureData.complete;
}
else if(UserId == Player2ID)
{
KinectGestures.GestureData gestureData = player2Gestures[index];
if(bResetOnComplete && gestureData.complete)
{
ResetPlayerGestures(UserId);
return true;
}
return gestureData.complete;
}
}
return false;
}
// returns true, if the given gesture for the specified user is cancelled
public bool IsGestureCancelled(uint UserId, KinectGestures.Gestures gesture)
{
int index = GetGestureIndex(UserId, gesture);
if(index >= 0)
{
if(UserId == Player1ID)
{
KinectGestures.GestureData gestureData = player1Gestures[index];
return gestureData.cancelled;
}
else if(UserId == Player2ID)
{
KinectGestures.GestureData gestureData = player2Gestures[index];
return gestureData.cancelled;
}
}
return false;
}
// returns the progress in range [0, 1] of the given gesture for the specified user
public float GetGestureProgress(uint UserId, KinectGestures.Gestures gesture)
{
int index = GetGestureIndex(UserId, gesture);
if(index >= 0)
{
if(UserId == Player1ID)
{
KinectGestures.GestureData gestureData = player1Gestures[index];
return gestureData.progress;
}
else if(UserId == Player2ID)
{
KinectGestures.GestureData gestureData = player2Gestures[index];
return gestureData.progress;
}
}
return 0f;
}
// returns the current "screen position" of the given gesture for the specified user
public Vector3 GetGestureScreenPos(uint UserId, KinectGestures.Gestures gesture)
{
int index = GetGestureIndex(UserId, gesture);
if(index >= 0)
{
if(UserId == Player1ID)
{
KinectGestures.GestureData gestureData = player1Gestures[index];
return gestureData.screenPos;
}
else if(UserId == Player2ID)
{
KinectGestures.GestureData gestureData = player2Gestures[index];
return gestureData.screenPos;
}
}
return Vector3.zero;
}
// recreates and reinitializes the lists of avatar controllers, after the list of avatars for player 1/2 was changed
public void SetAvatarControllers()
{
if(Player1Avatars.Count == 0 && Player2Avatars.Count == 0)
{
AvatarController[] avatars = FindObjectsOfType(typeof(AvatarController)) as AvatarController[];
foreach(AvatarController avatar in avatars)
{
Player1Avatars.Add(avatar.gameObject);
}
}
if(Player1Controllers != null)
{
Player1Controllers.Clear();
foreach(GameObject avatar in Player1Avatars)
{
if(avatar != null && avatar.activeInHierarchy)
{
AvatarController controller = avatar.GetComponent<AvatarController>();
controller.RotateToInitialPosition();
controller.Start();
Player1Controllers.Add(controller);
}
}
}
if(Player2Controllers != null)
{
Player2Controllers.Clear();
foreach(GameObject avatar in Player2Avatars)
{
if(avatar != null && avatar.activeInHierarchy)
{
AvatarController controller = avatar.GetComponent<AvatarController>();
controller.RotateToInitialPosition();
controller.Start();
Player2Controllers.Add(controller);
}
}
}
}
// removes the currently detected kinect users, allowing a new detection/calibration process to start
public void ClearKinectUsers()
{
if(!KinectInitialized)
return;
// remove current users
for(int i = allUsers.Count - 1; i >= 0; i--)
{
uint userId = allUsers[i];
RemoveUser(userId);
}
ResetFilters();
}
// clears Kinect buffers and resets the filters
public void ResetFilters()
{
if(!KinectInitialized)
return;
// clear kinect vars
player1Pos = Vector3.zero; player2Pos = Vector3.zero;
player1Ori = Matrix4x4.identity; player2Ori = Matrix4x4.identity;
int skeletonJointsCount = (int)KinectWrapper.NuiSkeletonPositionIndex.Count;
for(int i = 0; i < skeletonJointsCount; i++)
{
player1JointsTracked[i] = false; player2JointsTracked[i] = false;
player1PrevTracked[i] = false; player2PrevTracked[i] = false;
player1JointsPos[i] = Vector3.zero; player2JointsPos[i] = Vector3.zero;
player1JointsOri[i] = Matrix4x4.identity; player2JointsOri[i] = Matrix4x4.identity;
}
if(trackingStateFilter != null)
{
for(int i = 0; i < trackingStateFilter.Length; i++)
if(trackingStateFilter[i] != null)
trackingStateFilter[i].Reset();
}
if(boneOrientationFilter != null)
{
for(int i = 0; i < boneOrientationFilter.Length; i++)
if(boneOrientationFilter[i] != null)
boneOrientationFilter[i].Reset();
}
if(clippedLegsFilter != null)
{
for(int i = 0; i < clippedLegsFilter.Length; i++)
if(clippedLegsFilter[i] != null)
clippedLegsFilter[i].Reset();
}
}
//----------------------------------- end of public functions --------------------------------------//
void Start()
{
//CalibrationText = GameObject.Find("CalibrationText");
int hr = 0;
try
{
hr = KinectWrapper.NuiInitialize(KinectWrapper.NuiInitializeFlags.UsesSkeleton |
KinectWrapper.NuiInitializeFlags.UsesDepthAndPlayerIndex |
(ComputeColorMap ? KinectWrapper.NuiInitializeFlags.UsesColor : 0));
if (hr != 0)
{
throw new Exception("NuiInitialize Failed");
}
hr = KinectWrapper.NuiSkeletonTrackingEnable(IntPtr.Zero, 8); // 0, 12,8
if (hr != 0)
{
throw new Exception("Cannot initialize Skeleton Data");
}
depthStreamHandle = IntPtr.Zero;
if(ComputeUserMap)
{
hr = KinectWrapper.NuiImageStreamOpen(KinectWrapper.NuiImageType.DepthAndPlayerIndex,
KinectWrapper.Constants.ImageResolution, 0, 2, IntPtr.Zero, ref depthStreamHandle);
if (hr != 0)
{
throw new Exception("Cannot open depth stream");
}
}
colorStreamHandle = IntPtr.Zero;
if(ComputeColorMap)
{
hr = KinectWrapper.NuiImageStreamOpen(KinectWrapper.NuiImageType.Color,
KinectWrapper.Constants.ImageResolution, 0, 2, IntPtr.Zero, ref colorStreamHandle);
if (hr != 0)
{
throw new Exception("Cannot open color stream");
}
}
// set kinect elevation angle
KinectWrapper.NuiCameraElevationSetAngle(SensorAngle);
// init skeleton structures
skeletonFrame = new KinectWrapper.NuiSkeletonFrame()
{
SkeletonData = new KinectWrapper.NuiSkeletonData[KinectWrapper.Constants.NuiSkeletonCount]
};
// values used to pass to smoothing function
smoothParameters = new KinectWrapper.NuiTransformSmoothParameters();
switch(smoothing)
{
case Smoothing.Default:
smoothParameters.fSmoothing = 0.5f;
smoothParameters.fCorrection = 0.5f;
smoothParameters.fPrediction = 0.5f;
smoothParameters.fJitterRadius = 0.05f;
smoothParameters.fMaxDeviationRadius = 0.04f;
break;
case Smoothing.Medium:
smoothParameters.fSmoothing = 0.5f;
smoothParameters.fCorrection = 0.1f;
smoothParameters.fPrediction = 0.5f;
smoothParameters.fJitterRadius = 0.1f;
smoothParameters.fMaxDeviationRadius = 0.1f;
break;
case Smoothing.Aggressive:
smoothParameters.fSmoothing = 0.7f;
smoothParameters.fCorrection = 0.3f;
smoothParameters.fPrediction = 1.0f;
smoothParameters.fJitterRadius = 1.0f;
smoothParameters.fMaxDeviationRadius = 1.0f;
break;
}
// init the tracking state filter
trackingStateFilter = new TrackingStateFilter[KinectWrapper.Constants.NuiSkeletonMaxTracked];
for(int i = 0; i < trackingStateFilter.Length; i++)
{
trackingStateFilter[i] = new TrackingStateFilter();
trackingStateFilter[i].Init();
}
// init the bone orientation filter
boneOrientationFilter = new BoneOrientationsFilter[KinectWrapper.Constants.NuiSkeletonMaxTracked];
for(int i = 0; i < boneOrientationFilter.Length; i++)
{
boneOrientationFilter[i] = new BoneOrientationsFilter();
boneOrientationFilter[i].Init();
}
// init the clipped legs filter
clippedLegsFilter = new ClippedLegsFilter[KinectWrapper.Constants.NuiSkeletonMaxTracked];
for(int i = 0; i < clippedLegsFilter.Length; i++)
{
clippedLegsFilter[i] = new ClippedLegsFilter();
}
// init the bone orientation constraints
boneConstraintsFilter = new BoneOrientationsConstraint();
boneConstraintsFilter.AddDefaultConstraints();
// init the self intersection constraints
selfIntersectionConstraint = new SelfIntersectionConstraint();
// create arrays for joint positions and joint orientations
int skeletonJointsCount = (int)KinectWrapper.NuiSkeletonPositionIndex.Count;
player1JointsTracked = new bool[skeletonJointsCount];
player2JointsTracked = new bool[skeletonJointsCount];
player1PrevTracked = new bool[skeletonJointsCount];
player2PrevTracked = new bool[skeletonJointsCount];
player1JointsPos = new Vector3[skeletonJointsCount];
player2JointsPos = new Vector3[skeletonJointsCount];
player1JointsOri = new Matrix4x4[skeletonJointsCount];
player2JointsOri = new Matrix4x4[skeletonJointsCount];
gestureTrackingAtTime = new float[KinectWrapper.Constants.NuiSkeletonMaxTracked];
//create the transform matrix that converts from kinect-space to world-space
Quaternion quatTiltAngle = new Quaternion();
quatTiltAngle.eulerAngles = new Vector3(-SensorAngle, 0.0f, 0.0f);
//float heightAboveHips = SensorHeight - 1.0f;
// transform matrix - kinect to world
//kinectToWorld.SetTRS(new Vector3(0.0f, heightAboveHips, 0.0f), quatTiltAngle, Vector3.one);
kinectToWorld.SetTRS(new Vector3(0.0f, SensorHeight, 0.0f), quatTiltAngle, Vector3.one);
flipMatrix = Matrix4x4.identity;
flipMatrix[2, 2] = -1;
instance = this;
DontDestroyOnLoad(gameObject);
}
catch(DllNotFoundException e)
{
string message = "Please check the Kinect SDK installation.";
Debug.LogError(message);
Debug.LogError(e.ToString());
if(CalibrationText != null)
CalibrationText.guiText.text = message;
return;
}
catch (Exception e)
{
string message = e.Message + " - " + KinectWrapper.GetNuiErrorString(hr);
Debug.LogError(message);
Debug.LogError(e.ToString());
if(CalibrationText != null)
CalibrationText.guiText.text = message;
return;
}
// get the main camera rectangle
Rect cameraRect = Camera.main.pixelRect;
// calculate map width and height in percent, if needed
if(MapsPercentWidth == 0f)
MapsPercentWidth = (KinectWrapper.GetDepthWidth() / 2) / cameraRect.width;
if(MapsPercentHeight == 0f)
MapsPercentHeight = (KinectWrapper.GetDepthHeight() / 2) / cameraRect.height;
if(ComputeUserMap)
{
// Initialize depth & label map related stuff
usersMapSize = KinectWrapper.GetDepthWidth() * KinectWrapper.GetDepthHeight();
usersLblTex = new Texture2D(KinectWrapper.GetDepthWidth(), KinectWrapper.GetDepthHeight());
usersMapColors = new Color32[usersMapSize];
usersPrevState = new ushort[usersMapSize];
//usersMapRect = new Rect(Screen.width, Screen.height - usersLblTex.height / 2, -usersLblTex.width / 2, usersLblTex.height / 2);
//usersMapRect = new Rect(cameraRect.width, cameraRect.height - cameraRect.height * MapsPercentHeight, -cameraRect.width * MapsPercentWidth, cameraRect.height * MapsPercentHeight);
usersMapRect = new Rect(cameraRect.width - cameraRect.width * MapsPercentWidth, cameraRect.height, cameraRect.width * MapsPercentWidth, -cameraRect.height * MapsPercentHeight);
usersDepthMap = new short[usersMapSize];
usersHistogramMap = new float[8192];
}
if(ComputeColorMap)
{
// Initialize color map related stuff
usersClrTex = new Texture2D(KinectWrapper.GetDepthWidth(), KinectWrapper.GetDepthHeight());
//usersClrRect = new Rect(cameraRect.width, cameraRect.height - cameraRect.height * MapsPercentHeight, -cameraRect.width * MapsPercentWidth, cameraRect.height * MapsPercentHeight);
usersClrRect = new Rect(cameraRect.width - cameraRect.width * MapsPercentWidth, cameraRect.height, cameraRect.width * MapsPercentWidth, -cameraRect.height * MapsPercentHeight);
if(ComputeUserMap)
usersMapRect.x -= cameraRect.width * MapsPercentWidth; //usersClrTex.width / 2;
colorImage = new Color32[KinectWrapper.GetDepthWidth() * KinectWrapper.GetDepthHeight()];
usersColorMap = new byte[colorImage.Length << 2];
}
// try to automatically find the available avatar controllers in the scene
if(Player1Avatars.Count == 0 && Player2Avatars.Count == 0)
{
AvatarController[] avatars = FindObjectsOfType(typeof(AvatarController)) as AvatarController[];
foreach(AvatarController avatar in avatars)
{
Player1Avatars.Add(avatar.gameObject);
}
}
// Initialize user list to contain ALL users.
allUsers = new List<uint>();
// Pull the AvatarController from each of the players Avatars.
Player1Controllers = new List<AvatarController>();
Player2Controllers = new List<AvatarController>();
// Add each of the avatars' controllers into a list for each player.
foreach(GameObject avatar in Player1Avatars)
{
if(avatar != null && avatar.activeInHierarchy)
{
Player1Controllers.Add(avatar.GetComponent<AvatarController>());
}
}
foreach(GameObject avatar in Player2Avatars)
{
if(avatar != null && avatar.activeInHierarchy)
{
Player2Controllers.Add(avatar.GetComponent<AvatarController>());
}
}
// create the list of gesture listeners
gestureListeners = new List<KinectGestures.GestureListenerInterface>();
foreach(MonoBehaviour script in GestureListeners)
{
if(script && (script is KinectGestures.GestureListenerInterface))
{
KinectGestures.GestureListenerInterface listener = (KinectGestures.GestureListenerInterface)script;
gestureListeners.Add(listener);
}
}
// GUI Text.
if(CalibrationText != null)
{
CalibrationText.guiText.text = "WAITING FOR USERS";
}
Debug.Log("Waiting for users.");
KinectInitialized = true;
}
void Update()
{
if(KinectInitialized)
{
// // for testing purposes only
// KinectWrapper.UpdateKinectSensor();
// If the players aren't all calibrated yet, draw the user map.
if(ComputeUserMap)
{
if(depthStreamHandle != IntPtr.Zero &&
KinectWrapper.PollDepth(depthStreamHandle, NearMode, ref usersDepthMap))
{
UpdateUserMap();
}
}
if(ComputeColorMap)
{
if(colorStreamHandle != IntPtr.Zero &&
KinectWrapper.PollColor(colorStreamHandle, ref usersColorMap, ref colorImage))
{
UpdateColorMap();
}
}
if(KinectWrapper.PollSkeleton(ref smoothParameters, ref skeletonFrame))
{
ProcessSkeleton();
}
// Update player 1's models if he/she is calibrated and the model is active.
if(Player1Calibrated)
{
foreach (AvatarController controller in Player1Controllers)
{
//if(controller.Active)
{
controller.UpdateAvatar(Player1ID, NearMode);
}
}
// Check for complete gestures
foreach(KinectGestures.GestureData gestureData in player1Gestures)
{
if(gestureData.complete)
{
if(gestureData.gesture == KinectGestures.Gestures.Click)
{
if(ControlMouseCursor)
{
MouseControl.MouseClick();
}
}
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
if(listener.GestureCompleted(Player1ID, 0, gestureData.gesture,
(KinectWrapper.SkeletonJoint)gestureData.joint, gestureData.screenPos))
{
ResetPlayerGestures(Player1ID);
}
}
}
else if(gestureData.cancelled)
{
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
if(listener.GestureCancelled(Player1ID, 0, gestureData.gesture,
(KinectWrapper.SkeletonJoint)gestureData.joint))
{
ResetGesture(Player1ID, gestureData.gesture);
}
}
}
else if(gestureData.progress >= 0.1f)
{
if((gestureData.gesture == KinectGestures.Gestures.RightHandCursor ||
gestureData.gesture == KinectGestures.Gestures.LeftHandCursor) &&
gestureData.progress >= 0.5f)
{
if(HandCursor1 != null)
{
HandCursor1.transform.position = Vector3.Lerp(HandCursor1.transform.position, gestureData.screenPos, 3 * Time.deltaTime);
}
if(ControlMouseCursor)
{
MouseControl.MouseMove(gestureData.screenPos);
}
}
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
listener.GestureInProgress(Player1ID, 0, gestureData.gesture, gestureData.progress,
(KinectWrapper.SkeletonJoint)gestureData.joint, gestureData.screenPos);
}
}
}
}
// Update player 2's models if he/she is calibrated and the model is active.
if(Player2Calibrated)
{
foreach (AvatarController controller in Player2Controllers)
{
//if(controller.Active)
{
controller.UpdateAvatar(Player2ID, NearMode);
}
}
// Check for complete gestures
foreach(KinectGestures.GestureData gestureData in player2Gestures)
{
if(gestureData.complete)
{
if(gestureData.gesture == KinectGestures.Gestures.Click)
{
if(ControlMouseCursor)
{
MouseControl.MouseClick();
}
}
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
if(listener.GestureCompleted(Player2ID, 1, gestureData.gesture,
(KinectWrapper.SkeletonJoint)gestureData.joint, gestureData.screenPos))
{
ResetPlayerGestures(Player2ID);
}
}
}
else if(gestureData.cancelled)
{
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
if(listener.GestureCancelled(Player2ID, 1, gestureData.gesture,
(KinectWrapper.SkeletonJoint)gestureData.joint))
{
ResetGesture(Player2ID, gestureData.gesture);
}
}
}
else if(gestureData.progress >= 0.1f)
{
if((gestureData.gesture == KinectGestures.Gestures.RightHandCursor ||
gestureData.gesture == KinectGestures.Gestures.LeftHandCursor) &&
gestureData.progress >= 0.5f)
{
if(HandCursor2 != null)
{
HandCursor2.transform.position = Vector3.Lerp(HandCursor2.transform.position, gestureData.screenPos, 3 * Time.deltaTime);
}
if(ControlMouseCursor)
{
MouseControl.MouseMove(gestureData.screenPos);
}
}
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
listener.GestureInProgress(Player2ID, 1, gestureData.gesture, gestureData.progress,
(KinectWrapper.SkeletonJoint)gestureData.joint, gestureData.screenPos);
}
}
}
}
}
// Kill the program with ESC.
if(Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
}
// Make sure to kill the Kinect on quitting.
void OnApplicationQuit()
{
if(KinectInitialized)
{
// Shutdown OpenNI
KinectWrapper.NuiShutdown();
instance = null;
}
}
// Draw the Histogram Map on the GUI.
void OnGUI()
{
if(KinectInitialized)
{
if(ComputeUserMap && (/**(allUsers.Count == 0) ||*/ DisplayUserMap))
{
GUI.DrawTexture(usersMapRect, usersLblTex);
}
if(ComputeColorMap && (/**(allUsers.Count == 0) ||*/ DisplayColorMap))
{
GUI.DrawTexture(usersClrRect, usersClrTex);
}
}
}
// Update the User Map
void UpdateUserMap()
{
int numOfPoints = 0;
Array.Clear(usersHistogramMap, 0, usersHistogramMap.Length);
// Calculate cumulative histogram for depth
for (int i = 0; i < usersMapSize; i++)
{
// Only calculate for depth that contains users
if ((usersDepthMap[i] & 7) != 0)
{
usersHistogramMap[usersDepthMap[i] >> 3]++;
numOfPoints++;
}
}
if (numOfPoints > 0)
{
for (int i = 1; i < usersHistogramMap.Length; i++)
{
usersHistogramMap[i] += usersHistogramMap[i-1];
}
for (int i = 0; i < usersHistogramMap.Length; i++)
{
usersHistogramMap[i] = 1.0f - (usersHistogramMap[i] / numOfPoints);
}
}
// dummy structure needed by the coordinate mapper
KinectWrapper.NuiImageViewArea pcViewArea = new KinectWrapper.NuiImageViewArea
{
eDigitalZoom = 0,
lCenterX = 0,
lCenterY = 0
};
// Create the actual users texture based on label map and depth histogram
Color32 clrClear = Color.clear;
for (int i = 0; i < usersMapSize; i++)
{
// Flip the texture as we convert label map to color array
int flipIndex = i; // usersMapSize - i - 1;
ushort userMap = (ushort)(usersDepthMap[i] & 7);
ushort userDepth = (ushort)(usersDepthMap[i] >> 3);
ushort nowUserPixel = userMap != 0 ? (ushort)((userMap << 13) | userDepth) : userDepth;
ushort wasUserPixel = usersPrevState[flipIndex];
// draw only the changed pixels
if(nowUserPixel != wasUserPixel)
{
usersPrevState[flipIndex] = nowUserPixel;
if (userMap == 0)
{
usersMapColors[flipIndex] = clrClear;
}
else
{
if(colorImage != null)
{
int x = i % KinectWrapper.Constants.ImageWidth;
int y = i / KinectWrapper.Constants.ImageWidth;
int cx, cy;
int hr = KinectWrapper.NuiImageGetColorPixelCoordinatesFromDepthPixelAtResolution(
KinectWrapper.Constants.ImageResolution,
KinectWrapper.Constants.ImageResolution,
ref pcViewArea,
x, y, usersDepthMap[i],
out cx, out cy);
if(hr == 0)
{
int colorIndex = cx + cy * KinectWrapper.Constants.ImageWidth;
//colorIndex = usersMapSize - colorIndex - 1;
if(colorIndex >= 0 && colorIndex < usersMapSize)
{
Color32 colorPixel = colorImage[colorIndex];
usersMapColors[flipIndex] = colorPixel; // new Color(colorPixel.r / 256f, colorPixel.g / 256f, colorPixel.b / 256f, 0.9f);
usersMapColors[flipIndex].a = 230; // 0.9f
}
}
}
else
{
// Create a blending color based on the depth histogram
float histDepth = usersHistogramMap[userDepth];
Color c = new Color(histDepth, histDepth, histDepth, 0.9f);
switch(userMap % 4)
{
case 0:
usersMapColors[flipIndex] = Color.red * c;
break;
case 1:
usersMapColors[flipIndex] = Color.green * c;
break;
case 2:
usersMapColors[flipIndex] = Color.blue * c;
break;
case 3:
usersMapColors[flipIndex] = Color.magenta * c;
break;
}
}
}
}
}
// Draw it!
usersLblTex.SetPixels32(usersMapColors);
usersLblTex.Apply();
}
// Update the Color Map
void UpdateColorMap()
{
usersClrTex.SetPixels32(colorImage);
usersClrTex.Apply();
}
// Assign UserId to player 1 or 2.
void CalibrateUser(uint UserId, ref KinectWrapper.NuiSkeletonData skeletonData)
{
// If player 1 hasn't been calibrated, assign that UserID to it.
if(!Player1Calibrated)
{
// Check to make sure we don't accidentally assign player 2 to player 1.
if (!allUsers.Contains(UserId))
{
if(CheckForCalibrationPose(UserId, ref Player1CalibrationPose, ref player1CalibrationData, ref skeletonData))
{
Player1Calibrated = true;
Player1ID = UserId;
allUsers.Add(UserId);
foreach(AvatarController controller in Player1Controllers)
{
controller.SuccessfulCalibration(UserId);
}
// add the gestures to detect, if any
foreach(KinectGestures.Gestures gesture in Player1Gestures)
{
DetectGesture(UserId, gesture);
}
print ("user.detected");
// notify the gesture listeners about the new user
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
listener.UserDetected(UserId, 0);
}
// reset skeleton filters
ResetFilters();
// If we're not using 2 users, we're all calibrated.
//if(!TwoUsers)
{
AllPlayersCalibrated = !TwoUsers ? allUsers.Count >= 1 : allUsers.Count >= 2; // true;
}
}
}
}
// Otherwise, assign to player 2.
else if(TwoUsers && !Player2Calibrated)
{
if (!allUsers.Contains(UserId))
{
if(CheckForCalibrationPose(UserId, ref Player2CalibrationPose, ref player2CalibrationData, ref skeletonData))
{
Player2Calibrated = true;
Player2ID = UserId;
allUsers.Add(UserId);
foreach(AvatarController controller in Player2Controllers)
{
controller.SuccessfulCalibration(UserId);
}
// add the gestures to detect, if any
foreach(KinectGestures.Gestures gesture in Player2Gestures)
{
DetectGesture(UserId, gesture);
}
// notify the gesture listeners about the new user
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
listener.UserDetected(UserId, 1);
}
// reset skeleton filters
ResetFilters();
// All users are calibrated!
AllPlayersCalibrated = !TwoUsers ? allUsers.Count >= 1 : allUsers.Count >= 2; // true;
}
}
}
// If all users are calibrated, stop trying to find them.
if(AllPlayersCalibrated)
{
Debug.Log("All players calibrated.");
if(CalibrationText != null)
{
CalibrationText.guiText.text = "";
}
}
}
// Remove a lost UserId
void RemoveUser(uint UserId)
{
// If we lose player 1...
if(UserId == Player1ID)
{
// Null out the ID and reset all the models associated with that ID.
Player1ID = 0;
Player1Calibrated = false;
foreach(AvatarController controller in Player1Controllers)
{
controller.RotateToCalibrationPose(UserId, IsCalibrationNeeded());
}
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
listener.UserLost(UserId, 0);
}
player1CalibrationData.userId = 0;
}
// If we lose player 2...
if(UserId == Player2ID)
{
// Null out the ID and reset all the models associated with that ID.
Player2ID = 0;
Player2Calibrated = false;
foreach(AvatarController controller in Player2Controllers)
{
controller.RotateToCalibrationPose(UserId, IsCalibrationNeeded());
}
foreach(KinectGestures.GestureListenerInterface listener in gestureListeners)
{
listener.UserLost(UserId, 1);
}
player2CalibrationData.userId = 0;
}
// clear gestures list for this user
ClearGestures(UserId);
// remove from global users list
allUsers.Remove(UserId);
AllPlayersCalibrated = !TwoUsers ? allUsers.Count >= 1 : allUsers.Count >= 2; // false;
// Try to replace that user!
Debug.Log("Waiting for users.");
if(CalibrationText != null)
{
CalibrationText.guiText.text = "WAITING FOR USERS";
}
}
// Some internal constants
private const int stateTracked = (int)KinectWrapper.NuiSkeletonPositionTrackingState.Tracked;
private const int stateNotTracked = (int)KinectWrapper.NuiSkeletonPositionTrackingState.NotTracked;
private int [] mustBeTrackedJoints = {
(int)KinectWrapper.NuiSkeletonPositionIndex.AnkleLeft,
(int)KinectWrapper.NuiSkeletonPositionIndex.FootLeft,
(int)KinectWrapper.NuiSkeletonPositionIndex.AnkleRight,
(int)KinectWrapper.NuiSkeletonPositionIndex.FootRight,
};
// Process the skeleton data
void ProcessSkeleton()
{
List<uint> lostUsers = new List<uint>();
lostUsers.AddRange(allUsers);
// calculate the time since last update
float currentNuiTime = Time.realtimeSinceStartup;
float deltaNuiTime = currentNuiTime - lastNuiTime;
for(int i = 0; i < KinectWrapper.Constants.NuiSkeletonCount; i++)
{
KinectWrapper.NuiSkeletonData skeletonData = skeletonFrame.SkeletonData[i];
uint userId = skeletonData.dwTrackingID;
if(skeletonData.eTrackingState == KinectWrapper.NuiSkeletonTrackingState.SkeletonTracked)
{
// get the skeleton position
Vector3 skeletonPos = kinectToWorld.MultiplyPoint3x4(skeletonData.Position);
if(!AllPlayersCalibrated)
{
// check if this is the closest user
bool bClosestUser = true;
if(DetectClosestUser)
{
for(int j = 0; j < KinectWrapper.Constants.NuiSkeletonCount; j++)
{
if(j != i)
{
KinectWrapper.NuiSkeletonData skeletonDataOther = skeletonFrame.SkeletonData[j];
if((skeletonDataOther.eTrackingState == KinectWrapper.NuiSkeletonTrackingState.SkeletonTracked) &&
(Mathf.Abs(kinectToWorld.MultiplyPoint3x4(skeletonDataOther.Position).z) < Mathf.Abs(skeletonPos.z)))
{
bClosestUser = false;
break;
}
}
}
}
if(bClosestUser)
{
CalibrateUser(userId, ref skeletonData);
}
}
//// get joints orientations
//KinectWrapper.NuiSkeletonBoneOrientation[] jointOrients = new KinectWrapper.NuiSkeletonBoneOrientation[(int)KinectWrapper.NuiSkeletonPositionIndex.Count];
//KinectWrapper.NuiSkeletonCalculateBoneOrientations(ref skeletonData, jointOrients);
if(userId == Player1ID && Mathf.Abs(skeletonPos.z) >= MinUserDistance)
{
player1Index = i;
// get player position
player1Pos = skeletonPos;
// apply tracking state filter first
trackingStateFilter[0].UpdateFilter(ref skeletonData);
// fixup skeleton to improve avatar appearance.
if(UseClippedLegsFilter && clippedLegsFilter[0] != null)
{
clippedLegsFilter[0].FilterSkeleton(ref skeletonData, deltaNuiTime);
}
if(UseSelfIntersectionConstraint && selfIntersectionConstraint != null)
{
selfIntersectionConstraint.Constrain(ref skeletonData);
}
// get joints' position and rotation
for (int j = 0; j < (int)KinectWrapper.NuiSkeletonPositionIndex.Count; j++)
{
bool playerTracked = IgnoreInferredJoints ? (int)skeletonData.eSkeletonPositionTrackingState[j] == stateTracked :
(Array.BinarySearch(mustBeTrackedJoints, j) >= 0 ? (int)skeletonData.eSkeletonPositionTrackingState[j] == stateTracked :
(int)skeletonData.eSkeletonPositionTrackingState[j] != stateNotTracked);
player1JointsTracked[j] = player1PrevTracked[j] && playerTracked;
player1PrevTracked[j] = playerTracked;
if(player1JointsTracked[j])
{
player1JointsPos[j] = kinectToWorld.MultiplyPoint3x4(skeletonData.SkeletonPositions[j]);
//player1JointsOri[j] = jointOrients[j].absoluteRotation.rotationMatrix * flipMatrix;
}
// if(j == (int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter)
// {
// string debugText = String.Format("{0} {1}", /**(int)skeletonData.eSkeletonPositionTrackingState[j], */
// player1JointsTracked[j] ? "T" : "F", player1JointsPos[j]/**, skeletonData.SkeletonPositions[j]*/);
//
// if(CalibrationText)
// CalibrationText.guiText.text = debugText;
// }
}
// draw the skeleton on top of texture
if(DisplaySkeletonLines && ComputeUserMap)
{
DrawSkeleton(usersLblTex, ref skeletonData, ref player1JointsTracked);
}
// calculate joint orientations
KinectWrapper.GetSkeletonJointOrientation(ref player1JointsPos, ref player1JointsTracked, ref player1JointsOri);
// filter orientation constraints
if(UseBoneOrientationsConstraint && boneConstraintsFilter != null)
{
boneConstraintsFilter.Constrain(ref player1JointsOri, ref player1JointsTracked);
}
// filter joint orientations.
// it should be performed after all joint position modifications.
if(UseBoneOrientationsFilter && boneOrientationFilter[0] != null)
{
boneOrientationFilter[0].UpdateFilter(ref skeletonData, ref player1JointsOri);
}
// get player rotation
player1Ori = player1JointsOri[(int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter];
// check for gestures
if(Time.realtimeSinceStartup >= gestureTrackingAtTime[0])
{
int listGestureSize = player1Gestures.Count;
float timestampNow = Time.realtimeSinceStartup;
for(int g = 0; g < listGestureSize; g++)
{
KinectGestures.GestureData gestureData = player1Gestures[g];
if((timestampNow >= gestureData.startTrackingAtTime) &&
!IsConflictingGestureInProgress(gestureData))
{
KinectGestures.CheckForGesture(userId, ref gestureData, Time.realtimeSinceStartup,
ref player1JointsPos, ref player1JointsTracked);
player1Gestures[g] = gestureData;
if(gestureData.complete)
{
gestureTrackingAtTime[0] = timestampNow + MinTimeBetweenGestures;
}
}
}
}
}
else if(userId == Player2ID && Mathf.Abs(skeletonPos.z) >= MinUserDistance)
{
player2Index = i;
// get player position
player2Pos = skeletonPos;
// apply tracking state filter first
trackingStateFilter[1].UpdateFilter(ref skeletonData);
// fixup skeleton to improve avatar appearance.
if(UseClippedLegsFilter && clippedLegsFilter[1] != null)
{
clippedLegsFilter[1].FilterSkeleton(ref skeletonData, deltaNuiTime);
}
if(UseSelfIntersectionConstraint && selfIntersectionConstraint != null)
{
selfIntersectionConstraint.Constrain(ref skeletonData);
}
// get joints' position and rotation
for (int j = 0; j < (int)KinectWrapper.NuiSkeletonPositionIndex.Count; j++)
{
bool playerTracked = IgnoreInferredJoints ? (int)skeletonData.eSkeletonPositionTrackingState[j] == stateTracked :
(Array.BinarySearch(mustBeTrackedJoints, j) >= 0 ? (int)skeletonData.eSkeletonPositionTrackingState[j] == stateTracked :
(int)skeletonData.eSkeletonPositionTrackingState[j] != stateNotTracked);
player2JointsTracked[j] = player2PrevTracked[j] && playerTracked;
player2PrevTracked[j] = playerTracked;
if(player2JointsTracked[j])
{
player2JointsPos[j] = kinectToWorld.MultiplyPoint3x4(skeletonData.SkeletonPositions[j]);
}
}
// draw the skeleton on top of texture
if(DisplaySkeletonLines && ComputeUserMap)
{
DrawSkeleton(usersLblTex, ref skeletonData, ref player2JointsTracked);
}
// calculate joint orientations
KinectWrapper.GetSkeletonJointOrientation(ref player2JointsPos, ref player2JointsTracked, ref player2JointsOri);
// filter orientation constraints
if(UseBoneOrientationsConstraint && boneConstraintsFilter != null)
{
boneConstraintsFilter.Constrain(ref player2JointsOri, ref player2JointsTracked);
}
// filter joint orientations.
// it should be performed after all joint position modifications.
if(UseBoneOrientationsFilter && boneOrientationFilter[1] != null)
{
boneOrientationFilter[1].UpdateFilter(ref skeletonData, ref player2JointsOri);
}
// get player rotation
player2Ori = player2JointsOri[(int)KinectWrapper.NuiSkeletonPositionIndex.HipCenter];
// check for gestures
if(Time.realtimeSinceStartup >= gestureTrackingAtTime[1])
{
int listGestureSize = player2Gestures.Count;
float timestampNow = Time.realtimeSinceStartup;
for(int g = 0; g < listGestureSize; g++)
{
KinectGestures.GestureData gestureData = player2Gestures[g];
if((timestampNow >= gestureData.startTrackingAtTime) &&
!IsConflictingGestureInProgress(gestureData))
{
KinectGestures.CheckForGesture(userId, ref gestureData, Time.realtimeSinceStartup,
ref player2JointsPos, ref player2JointsTracked);
player2Gestures[g] = gestureData;
if(gestureData.complete)
{
gestureTrackingAtTime[1] = timestampNow + MinTimeBetweenGestures;
}
}
}
}
}
lostUsers.Remove(userId);
}
}
// update the nui-timer
lastNuiTime = currentNuiTime;
// remove the lost users if any
if(lostUsers.Count > 0)
{
foreach(uint userId in lostUsers)
{
RemoveUser(userId);
}
lostUsers.Clear();
}
}
// draws the skeleton in the given texture
private void DrawSkeleton(Texture2D aTexture, ref KinectWrapper.NuiSkeletonData skeletonData, ref bool[] playerJointsTracked)
{
int jointsCount = (int)KinectWrapper.NuiSkeletonPositionIndex.Count;
for(int i = 0; i < jointsCount; i++)
{
int parent = KinectWrapper.GetSkeletonJointParent(i);
if(playerJointsTracked[i] && playerJointsTracked[parent])
{
Vector3 posParent = KinectWrapper.MapSkeletonPointToDepthPoint(skeletonData.SkeletonPositions[parent]);
Vector3 posJoint = KinectWrapper.MapSkeletonPointToDepthPoint(skeletonData.SkeletonPositions[i]);
// posParent.y = KinectWrapper.Constants.ImageHeight - posParent.y - 1;
// posJoint.y = KinectWrapper.Constants.ImageHeight - posJoint.y - 1;
// posParent.x = KinectWrapper.Constants.ImageWidth - posParent.x - 1;
// posJoint.x = KinectWrapper.Constants.ImageWidth - posJoint.x - 1;
//Color lineColor = playerJointsTracked[i] && playerJointsTracked[parent] ? Color.red : Color.yellow;
DrawLine(aTexture, (int)posParent.x, (int)posParent.y, (int)posJoint.x, (int)posJoint.y, Color.yellow);
}
}
aTexture.Apply();
}
// draws a line in a texture
private void DrawLine(Texture2D a_Texture, int x1, int y1, int x2, int y2, Color a_Color)
{
int width = KinectWrapper.Constants.ImageWidth;
int height = KinectWrapper.Constants.ImageHeight;
int dy = y2 - y1;
int dx = x2 - x1;
int stepy = 1;
if (dy < 0)
{
dy = -dy;
stepy = -1;
}
int stepx = 1;
if (dx < 0)
{
dx = -dx;
stepx = -1;
}
dy <<= 1;
dx <<= 1;
if(x1 >= 0 && x1 < width && y1 >= 0 && y1 < height)
for(int x = -1; x <= 1; x++)
for(int y = -1; y <= 1; y++)
a_Texture.SetPixel(x1 + x, y1 + y, a_Color);
if (dx > dy)
{
int fraction = dy - (dx >> 1);
while (x1 != x2)
{
if (fraction >= 0)
{
y1 += stepy;
fraction -= dx;
}
x1 += stepx;
fraction += dy;
if(x1 >= 0 && x1 < width && y1 >= 0 && y1 < height)
for(int x = -1; x <= 1; x++)
for(int y = -1; y <= 1; y++)
a_Texture.SetPixel(x1 + x, y1 + y, a_Color);
}
}
else
{
int fraction = dx - (dy >> 1);
while (y1 != y2)
{
if (fraction >= 0)
{
x1 += stepx;
fraction -= dy;
}
y1 += stepy;
fraction += dx;
if(x1 >= 0 && x1 < width && y1 >= 0 && y1 < height)
for(int x = -1; x <= 1; x++)
for(int y = -1; y <= 1; y++)
a_Texture.SetPixel(x1 + x, y1 + y, a_Color);
}
}
}
// convert the matrix to quaternion, taking care of the mirroring
private Quaternion ConvertMatrixToQuat(Matrix4x4 mOrient, int joint, bool flip)
{
Vector4 vZ = mOrient.GetColumn(2);
Vector4 vY = mOrient.GetColumn(1);
if(!flip)
{
vZ.y = -vZ.y;
vY.x = -vY.x;
vY.z = -vY.z;
}
else
{
vZ.x = -vZ.x;
vZ.y = -vZ.y;
vY.z = -vY.z;
}
if(vZ.x != 0.0f || vZ.y != 0.0f || vZ.z != 0.0f)
return Quaternion.LookRotation(vZ, vY);
else
return Quaternion.identity;
}
// return the index of gesture in the list, or -1 if not found
private int GetGestureIndex(uint UserId, KinectGestures.Gestures gesture)
{
if(UserId == Player1ID)
{
int listSize = player1Gestures.Count;
for(int i = 0; i < listSize; i++)
{
if(player1Gestures[i].gesture == gesture)
return i;
}
}
else if(UserId == Player2ID)
{
int listSize = player2Gestures.Count;
for(int i = 0; i < listSize; i++)
{
if(player2Gestures[i].gesture == gesture)
return i;
}
}
return -1;
}
private bool IsConflictingGestureInProgress(KinectGestures.GestureData gestureData)
{
foreach(KinectGestures.Gestures gesture in gestureData.checkForGestures)
{
int index = GetGestureIndex(gestureData.userId, gesture);
if(index >= 0)
{
if(gestureData.userId == Player1ID)
{
if(player1Gestures[index].progress > 0f)
return true;
}
else if(gestureData.userId == Player2ID)
{
if(player2Gestures[index].progress > 0f)
return true;
}
}
}
return false;
}
// check if the calibration pose is complete for given user
private bool CheckForCalibrationPose(uint userId, ref KinectGestures.Gestures calibrationGesture,
ref KinectGestures.GestureData gestureData, ref KinectWrapper.NuiSkeletonData skeletonData)
{
if(calibrationGesture == KinectGestures.Gestures.None)
return true;
// init gesture data if needed
if(gestureData.userId != userId)
{
gestureData.userId = userId;
gestureData.gesture = calibrationGesture;
gestureData.state = 0;
gestureData.joint = 0;
gestureData.progress = 0f;
gestureData.complete = false;
gestureData.cancelled = false;
}
// get temporary joints' position
int skeletonJointsCount = (int)KinectWrapper.NuiSkeletonPositionIndex.Count;
bool[] jointsTracked = new bool[skeletonJointsCount];
Vector3[] jointsPos = new Vector3[skeletonJointsCount];
int stateTracked = (int)KinectWrapper.NuiSkeletonPositionTrackingState.Tracked;
int stateNotTracked = (int)KinectWrapper.NuiSkeletonPositionTrackingState.NotTracked;
int [] mustBeTrackedJoints = {
(int)KinectWrapper.NuiSkeletonPositionIndex.AnkleLeft,
(int)KinectWrapper.NuiSkeletonPositionIndex.FootLeft,
(int)KinectWrapper.NuiSkeletonPositionIndex.AnkleRight,
(int)KinectWrapper.NuiSkeletonPositionIndex.FootRight,
};
for (int j = 0; j < skeletonJointsCount; j++)
{
jointsTracked[j] = Array.BinarySearch(mustBeTrackedJoints, j) >= 0 ? (int)skeletonData.eSkeletonPositionTrackingState[j] == stateTracked :
(int)skeletonData.eSkeletonPositionTrackingState[j] != stateNotTracked;
if(jointsTracked[j])
{
jointsPos[j] = kinectToWorld.MultiplyPoint3x4(skeletonData.SkeletonPositions[j]);
}
}
// estimate the gesture progess
KinectGestures.CheckForGesture(userId, ref gestureData, Time.realtimeSinceStartup,
ref jointsPos, ref jointsTracked);
// check if gesture is complete
if(gestureData.complete)
{
gestureData.userId = 0;
return true;
}
return false;
}
}
|
using Android.OS;
using Android.Text;
using Android.Util;
using REKT.Graphics;
using REKT.Graphics.Unsafe;
using REKT.DI;
using SkiaSharp;
using System;
using System.Text;
using D = System.Diagnostics.Debug;
using NativeActivity = Android.App.Activity;
using NativeBitmap = Android.Graphics.Bitmap;
using NativeBitmapFactory = Android.Graphics.BitmapFactory;
using NativeContext = Android.Content.Context;
using NativeRect = Android.Graphics.Rect;
using NativeDialog = Android.Support.V7.App.AlertDialog;
using NativeProgressDialog = Android.App.ProgressDialog;
using NativeColour = Android.Graphics.Color;
using NativeArrayAdapter = Android.Widget.ArrayAdapter;
using NativeView = Android.Views.View;
using System.Collections;
using NativeThread = System.Threading.Thread;
namespace REKT
{
public static class AndroidExtensions
{
/////////////////////////////////////////////////////////////////////
// STRINGS
/////////////////////////////////////////////////////////////////////
public static ISpanned ToSpannedHTML(this string rawHtml)
{
ISpanned html;
if (AndroidPlatform.Version >= BuildVersionCodes.N)
html = Html.FromHtml(rawHtml, FromHtmlOptions.ModeLegacy);
else
{
#pragma warning disable CS0618 //deprecation
html = Html.FromHtml(rawHtml);
#pragma warning restore CS0618
}
return html;
}
/////////////////////////////////////////////////////////////////////
// CONTEXTS
/////////////////////////////////////////////////////////////////////
public static SKColor ThemeColour(this NativeContext context, int themeColourID)
{
if (context == null)
throw new ArgumentNullException("context");
using (var typedValue = new TypedValue())
{
var theme = context.Theme;
theme.ResolveAttribute(themeColourID, typedValue, true);
var data = typedValue.Data;
return new SKColor(
(byte)NativeColour.GetRedComponent(data),
(byte)NativeColour.GetGreenComponent(data),
(byte)NativeColour.GetBlueComponent(data),
(byte)NativeColour.GetAlphaComponent(data));
}
}
public static NativeBitmap BitmapResource(this NativeContext context, int bitmapResourceID)
{
using (var opts = new NativeBitmapFactory.Options())
{
opts.InPreferQualityOverSpeed = true;
return NativeBitmapFactory.DecodeResource(context.Resources, bitmapResourceID, opts);
}
}
public static SKBitmap BitmapResourceSkia(this NativeContext context, int bitmapResourceID)
{
using (var nativeBmp = context.BitmapResource(bitmapResourceID))
return nativeBmp.ToSkia();
}
private static void RunOnUIThreadIfPossible(this NativeContext context, Action action)
{
if (context is NativeActivity activity)
activity.RunOnUiThread(action);
else
action();
}
public static void ShowYesNoDialog(this NativeContext context, string title, string text,
Action yesAction = null, Action noAction = null)
{
if (context == null)
throw new ArgumentNullException("context");
context.RunOnUIThreadIfPossible(() =>
{
using (var builder = new NativeDialog.Builder(context))
{
builder.SetTitle((title ?? "").Trim());
builder.SetMessage((text ?? "").Trim());
builder.SetCancelable(false);
builder.SetPositiveButton("Yes", (s, e) => { yesAction?.Invoke(); });
builder.SetNegativeButton("No", (s, e) => { noAction?.Invoke(); });
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void ShowOKDialog(this NativeContext context, string title, string text, Action okAction = null)
{
if (context == null)
throw new ArgumentNullException("context");
context.RunOnUIThreadIfPossible(() =>
{
using (var builder = new NativeDialog.Builder(context))
{
builder.SetTitle((title ?? "").Trim());
builder.SetMessage((text ?? "").Trim());
builder.SetCancelable(false);
builder.SetPositiveButton(Android.Resource.String.Ok, (s, e) => { okAction?.Invoke(); });
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void ShowWaitDialog(this NativeContext context, string title, string text, Action asyncTask)
{
if (context == null)
throw new ArgumentNullException("context");
if (asyncTask == null)
throw new ArgumentNullException("asyncTask");
context.RunOnUIThreadIfPossible(() =>
{
var dialog = NativeProgressDialog.Show(context, (title ?? "").Trim(), (text ?? "").Trim(), true, false);
new NativeThread(() =>
{
asyncTask?.Invoke();
dialog.Dismiss();
dialog.Dispose();
}).Start();
});
}
public static void ShowListDialog(this NativeContext context, string title, IList data, Action<int> selectionAction,
Action cancelAction = null)
{
if (context == null)
throw new ArgumentNullException("context");
if (selectionAction == null)
throw new ArgumentNullException("selectionAction");
if (data == null)
throw new ArgumentNullException("data");
context.RunOnUIThreadIfPossible(() =>
{
using (var builder = new NativeDialog.Builder(context))
{
var adapter = new NativeArrayAdapter(context, Android.Resource.Layout.SimpleListItem1, data);
builder.SetTitle((title ?? "").Trim())
.SetAdapter(adapter, (s, e) => { selectionAction.Invoke(e.Which); });
if (cancelAction != null)
builder.SetCancelable(true).SetNegativeButton(Android.Resource.String.Cancel, (s, e) => { cancelAction.Invoke(); });
else
builder.SetCancelable(false);
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void ShowCustomDialog(this Activity activity, string title, int viewResID,
Action<NativeView> initAction = null,
Action<NativeView> okAction = null,
Action<NativeView> cancelAction = null)
{
if (activity == null)
throw new ArgumentNullException("context");
activity.RunOnUIThreadIfPossible(() =>
{
using (var builder = new NativeDialog.Builder(activity))
{
builder.SetTitle((title ?? "").Trim());
var view = activity.LayoutInflater.Inflate(viewResID, null);
initAction?.Invoke(view);
builder.SetView(view);
builder.SetPositiveButton(Android.Resource.String.Ok,
(s, e) => { okAction?.Invoke(view); });
if (cancelAction != null)
builder.SetCancelable(true).SetNegativeButton(Android.Resource.String.Cancel,
(s, e) => { cancelAction.Invoke(view); });
else
builder.SetCancelable(false);
using (var dialog = builder.Create())
dialog.Show();
}
});
}
public static void Toast(this NativeContext context, string text)
{
Android.Widget.Toast.MakeText(context, text, Android.Widget.ToastLength.Long).Show();
}
public static void LaunchWebsite(this NativeContext context, string uri)
{
using (var _uri = Android.Net.Uri.Parse(uri))
using (var intent = new Android.Content.Intent(Android.Content.Intent.ActionView, _uri))
{
intent.AddFlags(Android.Content.ActivityFlags.NewTask);
intent.AddFlags(Android.Content.ActivityFlags.NoHistory);
intent.AddFlags(Android.Content.ActivityFlags.ExcludeFromRecents);
context.StartActivity(intent);
}
}
public static ISpanned GetSpannedHTML(this NativeContext context, int resid)
{
return context.GetString(resid).ToSpannedHTML();
}
public static void LaunchAppSettings(this NativeContext context)
{
using (var _uri = Android.Net.Uri.Parse("package:" + context.PackageName))
using (var intent = new Android.Content.Intent("android.settings.APPLICATION_DETAILS_SETTINGS", _uri))
{
intent.AddFlags(Android.Content.ActivityFlags.NewTask);
intent.AddFlags(Android.Content.ActivityFlags.NoHistory);
intent.AddFlags(Android.Content.ActivityFlags.ExcludeFromRecents);
context.StartActivity(intent);
}
}
/////////////////////////////////////////////////////////////////////
// ACTIVITIES
/////////////////////////////////////////////////////////////////////
public static float CanvasScaleHint(this NativeActivity activity)
{
using (var displayMetrics = new DisplayMetrics())
{
activity.WindowManager.DefaultDisplay.GetMetrics(displayMetrics);
if (displayMetrics.ScaledDensity.IsZero()) //can this even happen??
return 1.0f;
return (displayMetrics.ScaledDensity / 3.0f).Clamp(0.4f, 1.5f);
}
}
public static void With<T>(this NativeActivity activity, int id, Action<T> viewAction) where T : Android.Views.View
{
using (var view = activity.FindViewById<T>(id))
viewAction(view);
}
/////////////////////////////////////////////////////////////////////
// SKIA
/////////////////////////////////////////////////////////////////////
public static NativeRect ToREKT(this SKRect rect)
{
return new NativeRect((int)rect.Left, (int)rect.Top,
(int)rect.Right, (int)rect.Bottom);
}
public static NativeColour ToNative(this SKColor col)
{
return new NativeColour(col.Red, col.Green, col.Blue, col.Alpha);
}
public static SKColor ToREKT(this NativeColour col)
{
return new SKColor(col.R, col.G, col.B, col.A);
}
/////////////////////////////////////////////////////////////////////
// BITMAPS
/////////////////////////////////////////////////////////////////////
public static SKBitmap ToSkia(this NativeBitmap source)
{
if (source == null)
throw new ArgumentNullException("source");
//init destination bitmap
var output = new SKBitmap(
source.Width,
source.Height,
SKColorType.Rgba8888,
SKAlphaType.Unpremul
);
//get source pixels
//"The returned colors are non-premultiplied ARGB values in the sRGB color space.",
//per https://developer.android.com/reference/android/graphics/Bitmap.html
int[] sourcePixels = new int[source.Width * source.Height];
source.GetPixels(sourcePixels, 0, source.Width, 0, 0, source.Width, source.Height);
//copy into destination
try
{
output.LockPixels();
var buffer = output.GetPixels();
unsafe
{
int* firstPixelAddr = (int*)buffer.ToPointer();
System.Threading.Tasks.Parallel.For(0, output.Height, (y) =>
{
int p = y * output.Width;
int* pixel = firstPixelAddr + p;
for (int x = 0; x < output.Width; x++, p++, pixel++)
*pixel = sourcePixels[p].SwapBytes02();
});
}
output.UnlockPixels();
}
catch (Exception e)
{
e.WriteToLog();
output.Dispose();
throw;
}
return output;
}
public static Bitmap ToREKT(this NativeBitmap source)
{
if (source == null)
throw new ArgumentNullException("source");
#if DEBUG
StringBuilder sb = new StringBuilder("Bitmap: constructing from Android.Graphics.Bitmap:");
sb.AppendLine();
sb.AppendFormattedLine("Dimensions: {0} x {1}", source.Width, source.Height);
sb.AppendFormattedLine("AllocationByteCount: {0}", source.AllocationByteCount);
sb.AppendFormattedLine("ByteCount: {0}", source.ByteCount);
sb.AppendFormattedLine("RowBytes: {0}", source.RowBytes);
sb.AppendFormattedLine("Density: {0}", source.Density);
sb.AppendFormattedLine("HasAlpha: {0}", source.HasAlpha);
sb.AppendFormattedLine("IsPremultiplied: {0}", source.IsPremultiplied);
D.WriteLine(sb);
#endif
//init destination bitmap
var output = new Bitmap(source.Width, source.Height, SKColorType.Rgba8888);
//get source pixels
//"The returned colors are non-premultiplied ARGB values in the sRGB color space.",
//per https://developer.android.com/reference/android/graphics/Bitmap.html
int[] sourcePixels = new int[source.Width * source.Height];
source.GetPixels(sourcePixels, 0, source.Width, 0, 0, source.Width, source.Height);
//copy into destination
try
{
output.Lock((buffer) =>
{
unsafe
{
byte* firstPixelAddr = (byte*)buffer.ToPointer();
Thread.Distribute((threadIndex, threadCount) =>
{
for (long y = threadIndex; y < output.Height; y += threadCount)
{
long p = y * output.Width;
for (long x = 0; x < output.Width; x++, p++)
output.SetPixel(firstPixelAddr, x, y, ((uint)sourcePixels[p]));
}
});
}
});
}
catch (Exception e)
{
e.WriteToLog();
output.Dispose();
throw;
}
return output;
}
/////////////////////////////////////////////////////////////////////
// UUIDs
/////////////////////////////////////////////////////////////////////
public static bool Equals(this Java.Util.UUID uuid, string uuidString)
{
if (uuid == null)
throw new ArgumentNullException("uuid");
if (uuidString == null)
throw new ArgumentNullException("uuidString");
return uuid.ToString().ToUpper() == uuidString.ToUpper();
}
}
} |
using System;
using System.Collections.Generic;
namespace Paladino.Drawing
{
/// <summary>
/// The thumbnails class handles all thumbnails to different types of content
/// embedded in the core.
/// </summary>
public static class Thumbnails
{
#region Members
private static Dictionary<Guid, string> guidToThumb = null;
private static Dictionary<string, string> typeToThumb = null;
private static Dictionary<string, Guid> typeToGuid = null;
private static object mutex = new object();
#endregion
/// <summary>
/// Gets whether the current thumbnail collection contains a
/// thumbnail for the given mime-type.
/// </summary>
/// <param name="type">The mime-type</param>
/// <returns>Whether the key exists</returns>
public static bool ContainsKey(string type)
{
Ensure();
return typeToThumb.ContainsKey(type);
}
/// <summary>
/// Gets whether the current thumbnail collection contains a
/// thumbnail for the given thumbnail id.
/// </summary>
/// <param name="id">The id</param>
/// <returns>Whether the key exists</returns>
public static bool ContainsKey(Guid id)
{
Ensure();
return guidToThumb.ContainsKey(id);
}
/// <summary>
/// Gets the resource path for the thumbnail with the given id.
/// </summary>
/// <param name="id">The id</param>
/// <returns>The resource path</returns>
public static string GetById(Guid id)
{
Ensure();
return guidToThumb[id];
}
/// <summary>
/// Gets the resource path fo the thumbnail with the given mime-type.
/// </summary>
/// <param name="type">The mime-type</param>
/// <returns>The resource path</returns>
public static string GetByType(string type)
{
Ensure();
if (!String.IsNullOrEmpty(type))
return typeToThumb[type];
return typeToThumb["default"];
}
/// <summary>
/// Gets the internal thumbnail id for the given mime-type.
/// </summary>
/// <param name="type">The mime-type</param>
/// <returns>The thumbnail id</returns>
public static Guid GetIdByType(string type)
{
Ensure();
if (!String.IsNullOrEmpty(type))
{
if (ContainsKey(type))
return typeToGuid[type];
}
return Guid.Empty;
}
#region Private methods
/// <summary>
/// Ensures that the thumbnail collection is created.
/// </summary>
private static void Ensure()
{
if (guidToThumb == null)
{
lock (mutex)
{
if (guidToThumb == null)
{
guidToThumb = new Dictionary<Guid, string>();
typeToThumb = new Dictionary<string, string>();
typeToGuid = new Dictionary<string, Guid>();
// Pdf
Add(new Guid("6DC9DF6B-3378-4576-90B5-2E801C6484EA"), "application/pdf", "Piranha.Areas.Manager.Content.Img.ico-pdf-64.png");
// Excel
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/vnd.ms-excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/msexcel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-msexcel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-ms-excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-dos_ms_excel", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/xls", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/x-xls", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
Add(new Guid("A37627AD-5973-4FDF-BA15-857B2640D16C"), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Piranha.Areas.Manager.Content.Img.ico-excel-64.png");
// Mp3
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mpeg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpeg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mp3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mp3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mpeg3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpeg3", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mpg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-mpegaudio", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// Wma
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/x-ms-wma", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// Flac
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/flac", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// Ogg
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/ogg", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// M4a
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mp4a-latm", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
Add(new Guid("6356E47D-8926-456E-9A2D-B62CA7251FA9"), "audio/mp4", "Piranha.Areas.Manager.Content.Img.ico-sound-64.png");
// Avi
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/avi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/msvideo", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/x-msvideo", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "image/avi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/xmpg2", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "application/x-troff-msvideo", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/aiff", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/avi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
// Mpeg
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/mpeg", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/mp4", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
// Mov
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/quicktime", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "video/x-quicktime", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "image/mov", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/x-midi", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "audio/x-wav", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
// Ppt
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/vnd.ms-powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/mspowerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/ms-powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/mspowerpnt", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/vnd-mspowerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/x-powerpoint", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
Add(new Guid("264D7937-6B78-43D5-A6C9-44D142406DB1"), "application/x-m", "Piranha.Areas.Manager.Content.Img.ico-ppt-64.png");
// Zip
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/zip", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-zip", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-zip-compressed", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/octet-stream", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-compress", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "application/x-compressed", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
Add(new Guid("58A1653A-FF16-4D60-865C-156B76A9E038"), "multipart/x-zip", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
// Rar
Add(new Guid("F63BBF1C-93F5-4B90-9337-232EBBB65908"), "application/x-rar-compressed", "Piranha.Areas.Manager.Content.Img.ico-zip-64.png");
// Folder
Add(new Guid("D604308B-BDFC-42FA-AAAA-7D0E9FE8DE5A"), "folder", "Piranha.Areas.Manager.Content.Img.ico-folder-96.png");
Add(new Guid("D604308B-BDFC-42FA-AAAA-7D0E9FE8DE5A"), "folder-small", "Piranha.Areas.Manager.Content.Img.ico-folder-32.png");
// Reference
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "youtube.com", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(new Guid("DBAD9093-1672-41EE-A5F7-F0433DF109A5"), "vimeo.com", "Piranha.Areas.Manager.Content.Img.ico-movie-64.png");
Add(Guid.Empty, "reference", "Piranha.Areas.Manager.Content.Img.ico-doc-64.png");
// Default
Add(Guid.Empty, "default", "Piranha.Areas.Manager.Content.Img.ico-doc-64.png");
}
}
}
}
/// <summary>
/// Adds a thumbnail resource with the given id and mime-type.
/// </summary>
/// <param name="id">The thumbnail id</param>
/// <param name="type">The mime-type</param>
/// <param name="thumbnail">The resource path</param>
private static void Add(Guid id, string type, string thumbnail)
{
if (!guidToThumb.ContainsKey(id))
guidToThumb.Add(id, thumbnail);
if (!typeToThumb.ContainsKey(type))
typeToThumb.Add(type, thumbnail);
if (!typeToGuid.ContainsKey(type))
typeToGuid.Add(type, id);
}
#endregion
}
} |
using SuperScript.Configuration;
using SuperScript.Emitters;
using SuperScript.Modifiers;
using SuperScript.Modifiers.Converters;
using SuperScript.Modifiers.Post;
using SuperScript.Modifiers.Pre;
using SuperScript.Modifiers.Writers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace SuperScript.ExtensionMethods
{
/// <summary>
/// Contains extension methods which can be invoked upon the classes which are implemented in the web.config <superScript> section.
/// </summary>
public static class ConfigurationExtensions
{
/// <summary>
/// Enumerates the <see cref="PropertyCollection"/> and populates the properties specified therein on the specified <see cref="host"/> object.
/// </summary>
/// <param name="propertyElmnts">A <see cref="PropertyCollection"/> object containing a collection of <see cref="PropertyElement"/> objects.</param>
/// <param name="host">The object to which the value of each <see cref="PropertyElement"/> object should be transferred to. </param>
public static void AssignProperties(this PropertyCollection propertyElmnts, object host)
{
if (propertyElmnts == null || propertyElmnts.Count == 0)
{
return;
}
foreach (PropertyElement propertyElmnt in propertyElmnts)
{
// a Type may be specified on the <property> element for the following reasons:
// - to assign a derived type to the specified property
// - if no value is specified on the <property> element then a new instance (using the default constructor)
// will be created and assigned to the specified property. This branch will throw an exception if the
// specified type is a value type or does not have a public default constructor.
if (propertyElmnt.Type != null)
{
// enums have to be handled differently
if (propertyElmnt.Type.IsEnum)
{
if (!Enum.IsDefined(propertyElmnt.Type, propertyElmnt.Value))
{
throw new SpecifiedPropertyNotFoundException(propertyElmnt.Name);
}
var enumInfo = host.GetType().GetProperty(propertyElmnt.Name);
if (enumInfo == null)
{
if (propertyElmnt.ExceptionIfMissing)
{
throw new SpecifiedPropertyNotFoundException(propertyElmnt.Name);
}
continue;
}
enumInfo.SetValue(host, Enum.Parse(propertyElmnt.Type, propertyElmnt.Value));
continue;
}
// in the following call, passing customProperty.Type might be more secure, but cannot be done in case
// the target property has been specified using an interface.
var propInfo = host.GetType().GetProperty(propertyElmnt.Name, propertyElmnt.Type);
if (propInfo == null)
{
if (propertyElmnt.ExceptionIfMissing)
{
throw new SpecifiedPropertyNotFoundException(propertyElmnt.Name);
}
continue;
}
// if no value has been specified then assume that the intention is to assign a new instance of the
// specified type to the specified property.
if (String.IsNullOrWhiteSpace(propertyElmnt.Value) && !propertyElmnt.Type.IsValueType)
{
// check that the specified type has a public default (parameterless) constructor
if (propertyElmnt.Type.GetConstructor(Type.EmptyTypes) != null)
{
propInfo.SetValue(host,
Activator.CreateInstance(propertyElmnt.Type),
null);
}
}
else
{
// a Type and a value have been specified
// if the Type is System.TimeSpan then this needs to be parsed in a specific manner
if (propertyElmnt.Type == typeof (TimeSpan))
{
TimeSpan ts;
TimeSpan.TryParse(propertyElmnt.Value, out ts);
propInfo.SetValue(host,
ts,
null);
}
else
{
propInfo.SetValue(host,
Convert.ChangeType(propertyElmnt.Value, propertyElmnt.Type),
null);
}
}
}
else
{
var propInfo = host.GetType().GetProperty(propertyElmnt.Name);
if (propInfo == null)
{
if (propertyElmnt.ExceptionIfMissing)
{
throw new SpecifiedPropertyNotFoundException(propertyElmnt.Name);
}
continue;
}
propInfo.SetValue(host,
Convert.ChangeType(propertyElmnt.Value, propInfo.PropertyType),
null);
}
}
}
/// <summary>
/// Compares the specified <see cref="EmitMode"/> enumeration with the current context.
/// </summary>
/// <param name="emitMode">Determines for which modes (i.e., debug, live, or forced on or off) a property should be emitted.</param>
/// <returns><c>True</c> if the current context covers the specified <see cref="EmitMode"/>.</returns>
public static bool IsCurrentlyEmittable(this EmitMode emitMode)
{
if (emitMode == EmitMode.Always)
{
return true;
}
if (emitMode == EmitMode.Never)
{
return false;
}
if (Settings.IsDebuggingEnabled)
{
return emitMode == EmitMode.DebugOnly;
}
return emitMode == EmitMode.LiveOnly;
}
/// <summary>
/// Determines whether the specified <see cref="ModifierBase"/> should be implemented in the current emitting context.
/// </summary>
/// <param name="modifier">An instance of <see cref="ModifierBase"/> whose <see cref="EmitMode"/> property will be checked against the current emitting context.</param>
/// <returns><c>true</c> if the specified instance of <see cref="ModifierBase"/> should be emitted in the current emitting context.</returns>
public static bool ShouldEmitForCurrentContext(this ModifierBase modifier)
{
return modifier.EmitMode.IsCurrentlyEmittable();
}
/// <summary>
/// Converts the specified <see cref="AttributesCollection"/> into an <see cref="ICollection{KeyValuePair}"/>.
/// </summary>
public static ICollection<KeyValuePair<string, string>> ToAttributeCollection(this AttributesCollection attributeElmnts)
{
var attrs = new Collection<KeyValuePair<string, string>>();
foreach (AttributeElement attrElmnt in attributeElmnts)
{
attrs.Add(new KeyValuePair<string, string>(attrElmnt.Name, attrElmnt.Value));
}
return attrs;
}
/// <summary>
/// Creates an instance of <see cref="EmitterBundle"/> from the specified <see cref="EmitterBundleElement"/> object.
/// </summary>
/// <exception cref="ConfigurationException">Thrown when a static or abstract type is referenced for the custom object.</exception>
public static EmitterBundle ToEmitterBundle(this EmitterBundleElement bundledEmitterElmnt)
{
// create the instance...
var instance = new EmitterBundle(bundledEmitterElmnt.Key);
// instantiate the CustomObject, if declared
if (bundledEmitterElmnt.CustomObject != null && bundledEmitterElmnt.CustomObject.Type != null)
{
var coType = bundledEmitterElmnt.CustomObject.Type;
// rule out abstract and static classes
// - reason: static classes will cause problems when we try to call static properties on the arguments.CustomObject property.
if (coType.IsAbstract)
{
throw new ConfigurationException("Static or abstract types are not permitted for the custom object.");
}
var customObject = Activator.CreateInstance(coType);
// if the developer has configured custom property values in the config then set them here
bundledEmitterElmnt.CustomObject.CustomProperties.AssignProperties(customObject);
instance.CustomObject = customObject;
}
var bundledKeys = new List<string>(bundledEmitterElmnt.BundleKeys.Count);
bundledKeys.AddRange(bundledEmitterElmnt.BundleKeys.Cast<string>());
instance.EmitterKeys = bundledKeys;
// instantiate the collection processors
instance.PostModifiers = bundledEmitterElmnt.PostModifiers.ToModifiers<CollectionPostModifier>();
instance.HtmlWriter = bundledEmitterElmnt.Writers.ToModifier<HtmlWriter>(required: true);
return instance;
}
/// <summary>
/// Creates an <see cref="ICollection{EmitterBundle}"/> containing the instances of <see cref="EmitterBundle"/> specified by the <see cref="EmitterBundlesCollection"/>.
/// </summary>
public static IList<EmitterBundle> ToEmitterBundles(this EmitterBundlesCollection bundledEmitterElmnts)
{
var bundledEmitters = new Collection<EmitterBundle>();
foreach (EmitterBundleElement bundledEmitterElmnt in bundledEmitterElmnts)
{
// check that no existing BundledEmitters have the same key as we're about to assign
if (bundledEmitters.Any(e => e.Key == bundledEmitterElmnt.Key))
{
throw new EmitterConfigurationException("Multiple <emitter> elements have been declared with the same Key (" + bundledEmitterElmnt.Key + ").");
}
bundledEmitters.Add(bundledEmitterElmnt.ToEmitterBundle());
}
return bundledEmitters;
}
/// <summary>
/// Creates an instance of <see cref="IEmitter"/> from the specified <see cref="EmitterElement"/> object.
/// </summary>
/// <exception cref="ConfigurationException">Thrown when a static or abstract type is referenced for the custom object.</exception>
public static IEmitter ToEmitter(this EmitterElement emitterElmnt)
{
// create the instance...
var instance = emitterElmnt.ToInstance<IEmitter>();
instance.IsDefault = emitterElmnt.IsDefault;
instance.Key = emitterElmnt.Key;
// instantiate the CustomObject, if declared
if (emitterElmnt.CustomObject != null && emitterElmnt.CustomObject.Type != null)
{
var coType = emitterElmnt.CustomObject.Type;
// rule out abstract and static classes
// - reason: static classes will cause problems when we try to call static properties on the arguments.CustomObject property.
if (coType.IsAbstract)
{
throw new ConfigurationException("Static or abstract types are not permitted for the custom object.");
}
var customObject = Activator.CreateInstance(coType);
// if the developer has configured custom property values in the config then set them here
emitterElmnt.CustomObject.CustomProperties.AssignProperties(customObject);
instance.CustomObject = customObject;
}
// instantiate the collection processors
instance.PreModifiers = emitterElmnt.PreModifiers.ToModifiers<CollectionPreModifier>();
instance.Converter = emitterElmnt.Converters.ToModifier<CollectionConverter>(required: true);
instance.PostModifiers = emitterElmnt.PostModifiers.ToModifiers<CollectionPostModifier>();
instance.HtmlWriter = emitterElmnt.Writers.ToModifier<HtmlWriter>();
return instance;
}
/// <summary>
/// Creates an <see cref="IList{IEmitter}"/> containing instances of the Emitters specified by the <see cref="EmittersCollection"/>.
/// </summary>
public static IList<IEmitter> ToEmitterCollection(this EmittersCollection emitterElmnts)
{
var emitters = new Collection<IEmitter>();
foreach (var emitterElmnt in from EmitterElement emitterElement in emitterElmnts
select emitterElement.ToEmitter())
{
// should we check if any other Emitters have been set to isDefault=true
if (emitterElmnt.IsDefault && emitters.Any(e => e.IsDefault))
{
throw new EmitterConfigurationException("Multiple <emitter> elements have been declared with 'isDefault' set to TRUE.");
}
// check that no existing emitters have the same key as we're about to assign
if (emitters.Any(e => e.Key == emitterElmnt.Key))
{
throw new EmitterConfigurationException("Multiple <emitter> elements have been declared with the same Key (" + emitterElmnt.Key + ").");
}
emitters.Add(emitterElmnt);
}
return emitters;
}
/// <summary>
/// Returns the first instance of T which is eligible for the context emit mode (i.e., <see cref="EmitMode.Always"/>, <see cref="EmitMode.DebugOnly"/>, etc.).
/// </summary>
/// <typeparam name="T">A type derived from <see cref="ModifierBase"/>.</typeparam>
/// <param name="modifierElmnts">Contains a collection of instances of <see cref="ModifierBase"/>.</param>
/// <param name="required">Indicates whether this method must return a <see cref="ModifierBase"/> or whether these are optional.</param>
/// <exception cref="ConfigurationException">Thrown if multiple declarations have been made for the context emit mode.</exception>
/// <exception cref="ConfigurablePropertyNotSpecifiedException">Thrown if no declarations have been made for the context emit mode.</exception>
public static T ToModifier<T>(this ModifiersCollection modifierElmnts, bool required = false) where T : ModifierBase
{
T instanceToBeUsed = null;
foreach (ModifierElement modifierElmnt in modifierElmnts)
{
var modInstance = modifierElmnt.ToInstance<T>();
modInstance.EmitMode = modifierElmnt.EmitMode;
if (!modInstance.ShouldEmitForCurrentContext())
{
continue;
}
if (instanceToBeUsed != null)
{
throw new ConfigurationException("Only one instance of HtmlWriter (in a <writer> element) may be specified per context mode.");
}
modifierElmnt.ModifierProperties.AssignProperties(modInstance);
var bundled = modInstance as IUseWhenBundled;
if (bundled != null)
{
bundled.UseWhenBundled = modifierElmnt.UseWhenBundled;
instanceToBeUsed = (T) bundled;
}
else
{
instanceToBeUsed = modInstance;
}
}
if (required && instanceToBeUsed == null)
{
throw new ConfigurablePropertyNotSpecifiedException("writer");
}
return instanceToBeUsed;
}
/// <summary>
/// Creates an <see cref="ICollection{T}"/> containing instances of objects specified in each <see cref="ModifierElement"/>.
/// </summary>
/// <typeparam name="T">A type derived from <see cref="ModifierBase"/>.</typeparam>
/// <param name="modifierElmnts">Contains a collection of instances of <see cref="ModifierBase"/>.</param>
public static ICollection<T> ToModifiers<T>(this ModifiersCollection modifierElmnts) where T : ModifierBase
{
var instances = new Collection<T>();
foreach (ModifierElement modifierElmnt in modifierElmnts)
{
var modInstance = modifierElmnt.ToInstance<T>();
modInstance.EmitMode = modifierElmnt.EmitMode;
if (!modInstance.ShouldEmitForCurrentContext())
{
continue;
}
modifierElmnt.ModifierProperties.AssignProperties(modInstance);
var bundled = modInstance as IUseWhenBundled;
if (bundled != null)
{
bundled.UseWhenBundled = modifierElmnt.UseWhenBundled;
modInstance = (T) bundled;
}
instances.Add(modInstance);
}
return instances;
}
/// <summary>
/// Returns the <see cref="Type"/> specified in the <see cref="IAssemblyElement"/>.
/// </summary>
public static T ToInstance<T>(this IAssemblyElement element)
{
return (T) Activator.CreateInstance(element.Type);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Dulcet.Twitter;
using Inscribe.Common;
using Inscribe.Configuration;
using Inscribe.Util;
using Inscribe.Subsystems;
using Inscribe.ViewModels.PartBlocks.MainBlock.TimelineChild;
using Livet;
namespace Inscribe.Storage
{
/// <summary>
/// ツイートの存在状態
/// </summary>
public enum TweetExistState
{
Unreceived,
EmptyExists,
Exists,
ServerDeleted,
}
/// <summary>
/// ツイートデータ(ViewModel)保持ベースクラス
/// </summary>
public static class TweetStorage
{
/// <summary>
/// ディクショナリのロック
/// </summary>
static ReaderWriterLockWrap lockWrap = new ReaderWriterLockWrap(LockRecursionPolicy.NoRecursion);
/// <summary>
/// 登録済みステータスディクショナリ
/// </summary>
static SortedDictionary<long, TweetViewModel> dictionary = new SortedDictionary<long, TweetViewModel>();
static ReaderWriterLockWrap vmLockWrap = new ReaderWriterLockWrap(LockRecursionPolicy.NoRecursion);
/// <summary>
/// ViewModel一覧の参照の高速化のためのリスト
/// </summary>
static List<TweetViewModel> viewmodels = new List<TweetViewModel>();
/// <summary>
/// empties/deleteReserveds用ロックラップ
/// </summary>
static ReaderWriterLockWrap elockWrap = new ReaderWriterLockWrap(LockRecursionPolicy.NoRecursion);
/// <summary>
/// 仮登録ステータスディクショナリ
/// </summary>
static SortedDictionary<long, TweetViewModel> empties = new SortedDictionary<long, TweetViewModel>();
/// <summary>
/// 削除予約されたツイートIDリスト
/// </summary>
static LinkedList<long> deleteReserveds = new LinkedList<long>();
/// <summary>
/// ツイートストレージの作業用スレッドディスパッチャ
/// </summary>
static QueueTaskDispatcher operationDispatcher;
static TweetStorage()
{
operationDispatcher = new QueueTaskDispatcher(1);
ThreadHelper.Halt += () => operationDispatcher.Dispose();
}
/// <summary>
/// ツイートを受信したか、また明示的削除などが行われたかを確認します。
/// </summary>
public static TweetExistState Contains(long id)
{
using (lockWrap.GetReaderLock())
{
if (dictionary.ContainsKey(id))
return TweetExistState.Exists;
}
using (elockWrap.GetReaderLock())
{
if (deleteReserveds.Contains(id))
return TweetExistState.ServerDeleted;
else if (empties.ContainsKey(id))
return TweetExistState.EmptyExists;
else
return TweetExistState.Unreceived;
}
}
/// <summary>
/// ツイートデータを取得します。
/// </summary>
/// <param name="id">ツイートID</param>
/// <param name="createEmpty">存在しないとき、空のViewModelを作って登録して返す</param>
public static TweetViewModel Get(long id, bool createEmpty = false)
{
TweetViewModel ret;
using (lockWrap.GetReaderLock())
{
if (dictionary.TryGetValue(id, out ret))
return ret;
}
using (createEmpty ? elockWrap.GetUpgradableReaderLock() : elockWrap.GetReaderLock())
{
if (empties.TryGetValue(id, out ret))
return ret;
if (createEmpty)
{
using (elockWrap.GetWriterLock())
{
var nvm = new TweetViewModel(id);
empties.Add(id, nvm);
return nvm;
}
}
else
{
return null;
}
}
}
/// <summary>
/// 登録されているステータスを抽出します。
/// </summary>
/// <param name="predicate">抽出条件</param>
/// <returns>条件にマッチするステータス、または登録されているすべてのステータス</returns>
public static IEnumerable<TweetViewModel> GetAll(Func<TweetViewModel, bool> predicate = null)
{
IEnumerable<TweetViewModel> tvms;
using (vmLockWrap.GetReaderLock())
{
tvms = viewmodels.ToArray();
}
if (predicate == null)
return tvms;
else
return tvms.AsParallel().Where(predicate);
}
private static volatile int _count;
/// <summary>
/// 登録されているツイートの個数を取得します。
/// </summary>
public static int Count()
{
return _count;
}
/// <summary>
/// 受信したツイートを登録します。<para />
/// 諸々の処理を自動で行います。
/// </summary>
public static TweetViewModel Register(TwitterStatusBase statusBase)
{
TweetViewModel robj;
using (lockWrap.GetReaderLock())
{
if (dictionary.TryGetValue(statusBase.Id, out robj))
return robj;
}
var status = statusBase as TwitterStatus;
if (status != null)
{
return RegisterStatus(status);
}
else
{
var dmsg = statusBase as TwitterDirectMessage;
if (dmsg != null)
{
return RegisterDirectMessage(dmsg);
}
else
{
throw new InvalidOperationException("不明なステータスを受信しました: " + statusBase);
}
}
}
/// <summary>
/// ステータスの追加に際しての処理
/// </summary>
private static TweetViewModel RegisterStatus(TwitterStatus status)
{
if (status.RetweetedOriginal != null)
{
// リツイートのオリジナルステータスを登録
var vm = Register(status.RetweetedOriginal);
// リツイートユーザーに登録
var user = UserStorage.Get(status.User);
var tuser = UserStorage.Get(status.RetweetedOriginal.User);
if (vm.RegisterRetweeted(user))
{
if (!vm.IsStatusInfoContains)
vm.SetStatus(status.RetweetedOriginal);
// 自分が関係していれば
if (AccountStorage.Contains(status.RetweetedOriginal.User.ScreenName)
|| AccountStorage.Contains(user.TwitterUser.ScreenName))
EventStorage.OnRetweeted(vm, user);
}
}
UserStorage.Register(status.User);
var registered = RegisterCore(status);
// 返信先の登録
if (status.InReplyToStatusId != 0)
{
Get(status.InReplyToStatusId, true).RegisterInReplyToThis(status.Id);
}
if (TwitterHelper.IsMentionOfMe(status))
{
EventStorage.OnMention(registered);
}
return registered;
}
/// <summary>
/// ダイレクトメッセージの追加に際しての処理
/// </summary>
private static TweetViewModel RegisterDirectMessage(TwitterDirectMessage dmsg)
{
UserStorage.Register(dmsg.Sender);
UserStorage.Register(dmsg.Recipient);
var vm = RegisterCore(dmsg);
EventStorage.OnDirectMessage(vm);
return vm;
}
/// <summary>
/// ステータスベースの登録処理
/// </summary>
private static TweetViewModel RegisterCore(TwitterStatusBase statusBase)
{
TweetViewModel viewModel;
using (elockWrap.GetUpgradableReaderLock())
{
if (empties.TryGetValue(statusBase.Id, out viewModel))
{
// 既にViewModelが生成済み
if (!viewModel.IsStatusInfoContains)
viewModel.SetStatus(statusBase);
using (elockWrap.GetWriterLock())
{
empties.Remove(statusBase.Id);
}
}
else
{
// 全く初めて触れるステータス
viewModel = new TweetViewModel(statusBase);
}
}
if (ValidateTweet(viewModel))
{
// プリプロセッシング
PreProcess(statusBase);
bool delr = false;
using (elockWrap.GetReaderLock())
{
delr = deleteReserveds.Contains(statusBase.Id);
}
if (!delr)
{
using (lockWrap.GetUpgradableReaderLock())
{
if (dictionary.ContainsKey(statusBase.Id))
{
return viewModel; // すでにKrile内に存在する
}
else
{
using (lockWrap.GetWriterLock())
{
dictionary.Add(statusBase.Id, viewModel);
}
_count++;
}
}
Task.Factory.StartNew(() => RaiseStatusAdded(viewModel)).ContinueWith(_ =>
{
// delay add
using (vmLockWrap.GetWriterLock())
{
viewmodels.Add(viewModel);
}
});
}
}
return viewModel;
}
/// <summary>
/// 登録可能なツイートか判定
/// </summary>
/// <returns></returns>
public static bool ValidateTweet(TweetViewModel viewModel)
{
if (viewModel.Status == null || viewModel.Status.User == null || String.IsNullOrEmpty(viewModel.Status.User.ScreenName))
throw new ArgumentException("データが破損しています。");
return true;
}
/// <summary>
/// ステータスのプリプロセッシング
/// </summary>
private static void PreProcess(TwitterStatusBase status)
{
try
{
if (status.Entities != null)
{
// extracting t.co and official image
new[]
{
status.Entities.GetChildNode("urls"),
status.Entities.GetChildNode("media")
}
.Where(n => n != null)
.SelectMany(n => n.GetChildNodes("item"))
.Where(i => i.GetChildNode("indices") != null)
.Where(i => i.GetChildNode("indices").GetChildValues("item") != null)
.OrderByDescending(i => i.GetChildNode("indices").GetChildValues("item")
.Select(s => int.Parse(s.Value)).First())
.ForEach(i =>
{
String expand = null;
if (i.GetChildValue("media_url") != null)
expand = i.GetChildValue("media_url").Value;
if (String.IsNullOrWhiteSpace(expand) && i.GetChildValue("expanded_url") != null)
expand = i.GetChildValue("expanded_url").Value;
if (String.IsNullOrWhiteSpace(expand) && i.GetChildValue("url") != null)
expand = i.GetChildValue("url").Value;
if (!String.IsNullOrWhiteSpace(expand))
{
var indices = i.GetChildNode("indices").GetChildValues("item")
.Select(v => int.Parse(v.Value)).OrderBy(v => v).ToArray();
if (indices.Length == 2)
{
//一旦内容を元の状態に戻す(参照:XmlParser.ParseString)
string orgtext = status.Text.Replace("&", "&").Replace(">", ">").Replace("<", "<");
// Considering surrogate pairs and Combining Character.
string text =
SubstringForSurrogatePaire(orgtext, 0, indices[0])
+ expand
+ SubstringForSurrogatePaire(orgtext, indices[1]);
//再度処理を施す
status.Text = text.Replace("<", "<").Replace(">", ">").Replace("&", "&");
}
}
});
}
}
catch { }
}
private static string SubstringForSurrogatePaire(string str, int startIndex, int length = -1)
{
var s = GetLengthForSurrogatePaire(str, startIndex, 0);
if (length == -1)
{
return str.Substring(s);
}
var l = GetLengthForSurrogatePaire(str, length, s);
return str.Substring(s, l);
}
private static int GetLengthForSurrogatePaire(string str, int len, int s)
{
var l = 0;
for (int i = 0; i < len; i++)
{
if (char.IsHighSurrogate(str[l + s]))
{
l++;
}
l++;
}
return l;
}
/// <summary>
/// ツイートをツイートストレージから除去
/// </summary>
/// <param name="id">ツイートID</param>
public static void Trim(long id)
{
TweetViewModel remobj = null;
using (elockWrap.GetWriterLock())
{
empties.Remove(id);
}
using (lockWrap.GetWriterLock())
{
if (dictionary.TryGetValue(id, out remobj))
{
dictionary.Remove(id);
_count--;
}
}
if (remobj != null)
{
using (vmLockWrap.GetWriterLock())
{
viewmodels.Remove(remobj);
}
Task.Factory.StartNew(() => RaiseStatusRemoved(remobj));
}
}
/// <summary>
/// ツイートの削除
/// </summary>
/// <param name="id">削除するツイートID</param>
public static void Remove(long id)
{
TweetViewModel remobj = null;
using (elockWrap.GetWriterLock())
{
empties.Remove(id);
}
using (lockWrap.GetWriterLock())
{
// 削除する
deleteReserveds.AddLast(id);
if (dictionary.TryGetValue(id, out remobj))
{
if (remobj.IsRemoved)
{
dictionary.Remove(id);
_count--;
}
}
}
if (remobj != null)
{
using (vmLockWrap.GetWriterLock())
{
if (remobj.IsRemoved)
viewmodels.Remove(remobj);
}
Task.Factory.StartNew(() => RaiseStatusRemoved(remobj));
// リツイート判定
var status = remobj.Status as TwitterStatus;
if (status != null && status.RetweetedOriginal != null)
{
var ros = TweetStorage.Get(status.RetweetedOriginal.Id);
if (ros != null)
ros.RemoveRetweeted(UserStorage.Get(status.User));
}
}
}
/// <summary>
/// ツイートの内部状態が変化したことを通知します。<para />
/// (例えば、ふぁぼられたりRTされたり返信貰ったりなど。)
/// </summary>
public static void NotifyTweetStateChanged(TweetViewModel tweet)
{
Task.Factory.StartNew(() => RaiseStatusStateChanged(tweet));
}
#region TweetStorageChangedイベント
public static event EventHandler<TweetStorageChangedEventArgs> TweetStorageChanged;
private static Notificator<TweetStorageChangedEventArgs> _TweetStorageChangedEvent;
public static Notificator<TweetStorageChangedEventArgs> TweetStorageChangedEvent
{
get
{
if (_TweetStorageChangedEvent == null)
_TweetStorageChangedEvent = new Notificator<TweetStorageChangedEventArgs>();
return _TweetStorageChangedEvent;
}
set { _TweetStorageChangedEvent = value; }
}
private static void OnTweetStorageChanged(TweetStorageChangedEventArgs e)
{
var threadSafeHandler = Interlocked.CompareExchange(ref TweetStorageChanged, null, null);
if (threadSafeHandler != null) threadSafeHandler(null, e);
TweetStorageChangedEvent.Raise(e);
}
#endregion
static void RaiseStatusAdded(TweetViewModel added)
{
// Mention通知設定がないか、
// 自分へのMentionでない場合にのみRegisterする
// +
// Retweet通知設定がないか、
// 自分のTweetのRetweetでない場合にのみRegisterする
if ((!Setting.Instance.NotificationProperty.NotifyMention ||
!TwitterHelper.IsMentionOfMe(added.Status)) &&
(!Setting.Instance.NotificationProperty.NotifyRetweet ||
!(added.Status is TwitterStatus) || ((TwitterStatus)added.Status).RetweetedOriginal == null ||
!AccountStorage.Contains(((TwitterStatus)added.Status).RetweetedOriginal.User.ScreenName)))
NotificationCore.RegisterNotify(added);
OnTweetStorageChanged(new TweetStorageChangedEventArgs(TweetActionKind.Added, added));
NotificationCore.DispatchNotify(added);
}
static void RaiseStatusRemoved(TweetViewModel removed)
{
OnTweetStorageChanged(new TweetStorageChangedEventArgs(TweetActionKind.Removed, removed));
}
static void RaiseStatusStateChanged(TweetViewModel changed)
{
OnTweetStorageChanged(new TweetStorageChangedEventArgs(TweetActionKind.Changed, changed));
}
static void RaiseRefreshTweets()
{
OnTweetStorageChanged(new TweetStorageChangedEventArgs(TweetActionKind.Refresh));
}
internal static void UpdateMute()
{
if (Setting.Instance.TimelineFilteringProperty.MuteFilterCluster == null) return;
GetAll(t => Setting.Instance.TimelineFilteringProperty.MuteFilterCluster.Filter(t.Status))
.ForEach(t =>
{
if (!AccountStorage.Contains(t.Status.User.ScreenName))
Remove(t.bindingId);
});
}
}
public class TweetStorageChangedEventArgs : EventArgs
{
public TweetStorageChangedEventArgs(TweetActionKind act, TweetViewModel added = null)
{
this.ActionKind = act;
this.Tweet = added;
}
public TweetViewModel Tweet { get; set; }
public TweetActionKind ActionKind { get; set; }
}
public enum TweetActionKind
{
/// <summary>
/// ツイートが追加された
/// </summary>
Added,
/// <summary>
/// ツイートが削除された
/// </summary>
Removed,
/// <summary>
/// ツイートの固有情報が変更された
/// </summary>
Changed,
/// <summary>
/// ストレージ全体に変更が入った
/// </summary>
Refresh,
}
}
|
/*
* @(#)Function2Arg.cs 3.0.0 2016-05-07
*
* You may use this software under the condition of "Simplified BSD License"
*
* Copyright 2010-2016 MARIUSZ GROMADA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <MARIUSZ GROMADA> ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of MARIUSZ GROMADA.
*
* If you have any questions/bugs feel free to contact:
*
* Mariusz Gromada
* mariuszgromada.org@gmail.com
* http://mathparser.org
* http://mathspace.pl
* http://janetsudoku.mariuszgromada.org
* http://github.com/mariuszgromada/MathParser.org-mXparser
* http://mariuszgromada.github.io/MathParser.org-mXparser
* http://mxparser.sourceforge.net
* http://bitbucket.org/mariuszgromada/mxparser
* http://mxparser.codeplex.com
* http://github.com/mariuszgromada/Janet-Sudoku
* http://janetsudoku.codeplex.com
* http://sourceforge.net/projects/janetsudoku
* http://bitbucket.org/mariuszgromada/janet-sudoku
* http://github.com/mariuszgromada/MathParser.org-mXparser
*
* Asked if he believes in one God, a mathematician answered:
* "Yes, up to isomorphism."
*/
using System;
namespace org.mariuszgromada.math.mxparser.parsertokens {
/**
* Binary functions (2 arguments) - mXparser tokens definition.
*
* @author <b>Mariusz Gromada</b><br>
* <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br>
* <a href="http://mathspace.pl" target="_blank">MathSpace.pl</a><br>
* <a href="http://mathparser.org" target="_blank">MathParser.org - mXparser project page</a><br>
* <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br>
* <a href="http://mxparser.sourceforge.net" target="_blank">mXparser on SourceForge</a><br>
* <a href="http://bitbucket.org/mariuszgromada/mxparser" target="_blank">mXparser on Bitbucket</a><br>
* <a href="http://mxparser.codeplex.com" target="_blank">mXparser on CodePlex</a><br>
* <a href="http://janetsudoku.mariuszgromada.org" target="_blank">Janet Sudoku - project web page</a><br>
* <a href="http://github.com/mariuszgromada/Janet-Sudoku" target="_blank">Janet Sudoku on GitHub</a><br>
* <a href="http://janetsudoku.codeplex.com" target="_blank">Janet Sudoku on CodePlex</a><br>
* <a href="http://sourceforge.net/projects/janetsudoku" target="_blank">Janet Sudoku on SourceForge</a><br>
* <a href="http://bitbucket.org/mariuszgromada/janet-sudoku" target="_blank">Janet Sudoku on BitBucket</a><br>
*
* @version 3.0.0
*/
[CLSCompliant(true)]
public sealed class Function2Arg {
/*
* BinaryFunction - token type id.
*/
public const int TYPE_ID = 5;
public const String TYPE_DESC = "Binary Function";
/*
* BinaryFunction - tokens id.
*/
public const int LOG_ID = 1;
public const int MOD_ID = 2;
public const int BINOM_COEFF_ID = 3;
public const int BERNOULLI_NUMBER_ID = 4;
public const int STIRLING1_NUMBER_ID = 5;
public const int STIRLING2_NUMBER_ID = 6;
public const int WORPITZKY_NUMBER_ID = 7;
public const int EULER_NUMBER_ID = 8;
public const int KRONECKER_DELTA_ID = 9;
public const int EULER_POLYNOMIAL_ID = 10;
public const int HARMONIC_NUMBER_ID = 11;
public const int RND_UNIFORM_CONT_ID = 12;
public const int RND_UNIFORM_DISCR_ID = 13;
public const int ROUND_ID = 14;
public const int RND_NORMAL_ID = 15;
/*
* BinaryFunction - tokens key words.
*/
public const String LOG_STR = "log";
public const String MOD_STR = "mod";
public const String BINOM_COEFF_STR = "C";
public const String BERNOULLI_NUMBER_STR = "Bern";
public const String STIRLING1_NUMBER_STR = "Stirl1";
public const String STIRLING2_NUMBER_STR = "Stirl2";
public const String WORPITZKY_NUMBER_STR = "Worp";
public const String EULER_NUMBER_STR = "Euler";
public const String KRONECKER_DELTA_STR = "KDelta";
public const String EULER_POLYNOMIAL_STR = "EulerPol";
public const String HARMONIC_NUMBER_STR = "Harm";
public const String RND_UNIFORM_CONT_STR = "rUni";
public const String RND_UNIFORM_DISCR_STR = "rUnid";
public const String ROUND_STR = "round";
public const String RND_NORMAL_STR = "rNor";
/*
* BinaryFunction - tokens description.
*/
public const String LOG_DESC = "logarithm function";
public const String MOD_DESC = "modulo function";
public const String BINOM_COEFF_DESC = "binomial coefficient function";
public const String BERNOULLI_NUMBER_DESC = "Bernoulli numbers";
public const String STIRLING1_NUMBER_DESC = "Stirling numbers of the first kind";
public const String STIRLING2_NUMBER_DESC = "Stirling numbers of the second kind";
public const String WORPITZKY_NUMBER_DESC = "Worpitzky number";
public const String EULER_NUMBER_DESC = "Euler number";
public const String KRONECKER_DELTA_DESC = "Kronecker delta";
public const String EULER_POLYNOMIAL_DESC = "EulerPol";
public const String HARMONIC_NUMBER_DESC = "Harmonic number";
public const String RND_UNIFORM_CONT_DESC = "(3.0) Random variable - Uniform continuous distribution U(a,b), usage example: 2*rUni(2,10)";
public const String RND_UNIFORM_DISCR_DESC = "(3.0) Random variable - Uniform discrete distribution U{a,b}, usage example: 2*rUnid(2,100)";
public const String ROUND_DESC = "(3.0) Half-up rounding, usage examples: round(2.2, 0) = 2, round(2.6, 0) = 3, round(2.66,1) = 2.7";
public const String RND_NORMAL_DESC = "(3.0) Random variable - Normal distribution N(m,s) m - mean, s - stddev, usage example: 3*rNor(0,1)";
}
}
|
using Xunit;
using Shouldly;
using System.Linq;
using System;
using System.Text.RegularExpressions;
namespace AutoMapper.UnitTests
{
public class MapFromReverseResolveUsing : AutoMapperSpecBase
{
public class Source
{
public int Total { get; set; }
}
public class Destination
{
public int Total { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(c =>
{
c.CreateMap<Destination, Source>()
.ForMember(dest => dest.Total, opt => opt.MapFrom(x => x.Total))
.ReverseMap()
.ForMember(dest => dest.Total, opt => opt.ResolveUsing<CustomResolver>());
});
public class CustomResolver : IValueResolver<Source, Destination, int>
{
public int Resolve(Source source, Destination destination, int member, ResolutionContext context)
{
return Int32.MaxValue;
}
}
[Fact]
public void Should_use_the_resolver()
{
Mapper.Map<Destination>(new Source()).Total.ShouldBe(int.MaxValue);
}
}
public class MethodsWithReverse : AutoMapperSpecBase
{
class Order
{
public OrderItem[] OrderItems { get; set; }
}
class OrderItem
{
public string Product { get; set; }
}
class OrderDto
{
public int OrderItemsCount { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(c=>
{
c.CreateMap<Order, OrderDto>().ReverseMap();
});
[Fact]
public void ShouldMapOk()
{
Mapper.Map<Order>(new OrderDto());
}
}
public class ReverseForPath : AutoMapperSpecBase
{
public class Order
{
public CustomerHolder CustomerHolder { get; set; }
}
public class CustomerHolder
{
public Customer Customer { get; set; }
}
public class Customer
{
public string Name { get; set; }
public decimal Total { get; set; }
}
public class OrderDto
{
public string CustomerName { get; set; }
public decimal Total { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<OrderDto, Order>()
.ForPath(o => o.CustomerHolder.Customer.Name, o => o.MapFrom(s => s.CustomerName))
.ForPath(o => o.CustomerHolder.Customer.Total, o => o.MapFrom(s => s.Total))
.ReverseMap();
});
[Fact]
public void Should_flatten()
{
var model = new Order {
CustomerHolder = new CustomerHolder {
Customer = new Customer { Name = "George Costanza", Total = 74.85m }
}
};
var dto = Mapper.Map<OrderDto>(model);
dto.CustomerName.ShouldBe("George Costanza");
dto.Total.ShouldBe(74.85m);
}
}
public class ReverseMapFrom : AutoMapperSpecBase
{
public class Order
{
public CustomerHolder CustomerHolder { get; set; }
}
public class CustomerHolder
{
public Customer Customer { get; set; }
}
public class Customer
{
public string Name { get; set; }
public decimal Total { get; set; }
}
public class OrderDto
{
public string CustomerName { get; set; }
public decimal Total { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Order, OrderDto>()
.ForMember(d => d.CustomerName, o => o.MapFrom(s => s.CustomerHolder.Customer.Name))
.ForMember(d => d.Total, o => o.MapFrom(s => s.CustomerHolder.Customer.Total))
.ReverseMap();
});
[Fact]
public void Should_unflatten()
{
var dto = new OrderDto { CustomerName = "George Costanza", Total = 74.85m };
var model = Mapper.Map<Order>(dto);
model.CustomerHolder.Customer.Name.ShouldBe("George Costanza");
model.CustomerHolder.Customer.Total.ShouldBe(74.85m);
}
}
public class ReverseDefaultFlatteningWithIgnoreMember : AutoMapperSpecBase
{
public class Order
{
public CustomerHolder Customerholder { get; set; }
}
public class CustomerHolder
{
public Customer Customer { get; set; }
}
public class Customer
{
public string Name { get; set; }
public decimal Total { get; set; }
}
public class OrderDto
{
public string CustomerholderCustomerName { get; set; }
public decimal CustomerholderCustomerTotal { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Order, OrderDto>()
.ReverseMap()
.ForMember(d=>d.Customerholder, o=>o.Ignore())
.ForPath(d=>d.Customerholder.Customer.Total, o=>o.MapFrom(s=>s.CustomerholderCustomerTotal));
});
[Fact]
public void Should_unflatten()
{
var dto = new OrderDto { CustomerholderCustomerName = "George Costanza", CustomerholderCustomerTotal = 74.85m };
var model = Mapper.Map<Order>(dto);
model.Customerholder.Customer.Name.ShouldBeNull();
model.Customerholder.Customer.Total.ShouldBe(74.85m);
}
}
public class ReverseDefaultFlattening : AutoMapperSpecBase
{
public class Order
{
public CustomerHolder Customerholder { get; set; }
}
public class CustomerHolder
{
public Customer Customer { get; set; }
}
public class Customer
{
public string Name { get; set; }
public decimal Total { get; set; }
}
public class OrderDto
{
public string CustomerholderCustomerName { get; set; }
public decimal CustomerholderCustomerTotal { get; set; }
}
protected override MapperConfiguration Configuration => new MapperConfiguration(cfg =>
{
cfg.CreateMap<Order, OrderDto>()
.ReverseMap();
});
[Fact]
public void Should_unflatten()
{
var dto = new OrderDto { CustomerholderCustomerName = "George Costanza", CustomerholderCustomerTotal = 74.85m };
var model = Mapper.Map<Order>(dto);
model.Customerholder.Customer.Name.ShouldBe("George Costanza");
model.Customerholder.Customer.Total.ShouldBe(74.85m);
}
}
public class ReverseMapConventions : AutoMapperSpecBase
{
Rotator_Ad_Run _destination;
DateTime _startDate = DateTime.Now, _endDate = DateTime.Now.AddHours(2);
public class Rotator_Ad_Run
{
public DateTime Start_Date { get; set; }
public DateTime End_Date { get; set; }
public bool Enabled { get; set; }
}
public class RotatorAdRunViewModel
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public bool Enabled { get; set; }
}
public class UnderscoreNamingConvention : INamingConvention
{
public Regex SplittingExpression { get; } = new Regex(@"\p{Lu}[a-z0-9]*(?=_?)");
public string SeparatorCharacter => "_";
public string ReplaceValue(Match match)
{
return match.Value;
}
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateProfile("MyMapperProfile", prf =>
{
prf.SourceMemberNamingConvention = new UnderscoreNamingConvention();
prf.CreateMap<Rotator_Ad_Run, RotatorAdRunViewModel>();
});
cfg.CreateProfile("MyMapperProfile2", prf =>
{
prf.DestinationMemberNamingConvention = new UnderscoreNamingConvention();
prf.CreateMap<RotatorAdRunViewModel, Rotator_Ad_Run>();
});
});
protected override void Because_of()
{
_destination = Mapper.Map<RotatorAdRunViewModel, Rotator_Ad_Run>(new RotatorAdRunViewModel { Enabled = true, EndDate = _endDate, StartDate = _startDate });
}
[Fact]
public void Should_apply_the_convention_in_reverse()
{
_destination.Enabled.ShouldBeTrue();
_destination.End_Date.ShouldBe(_endDate);
_destination.Start_Date.ShouldBe(_startDate);
}
}
public class When_reverse_mapping_classes_with_simple_properties : AutoMapperSpecBase
{
private Source _source;
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>()
.ReverseMap();
});
protected override void Because_of()
{
var dest = new Destination
{
Value = 10
};
_source = Mapper.Map<Destination, Source>(dest);
}
[Fact]
public void Should_create_a_map_with_the_reverse_items()
{
_source.Value.ShouldBe(10);
}
}
public class When_validating_only_against_source_members_and_source_matches : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int Value { get; set; }
public int Value2 { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>(MemberList.Source);
});
[Fact]
public void Should_only_map_source_members()
{
var typeMap = ConfigProvider.FindTypeMapFor<Source, Destination>();
typeMap.GetPropertyMaps().Count().ShouldBe(1);
}
[Fact]
public void Should_not_throw_any_configuration_validation_errors()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_validating_only_against_source_members_and_source_does_not_match : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
public int Value2 { get; set; }
}
public class Destination
{
public int Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>(MemberList.Source);
});
[Fact]
public void Should_throw_a_configuration_validation_error()
{
typeof(AutoMapperConfigurationException).ShouldBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_validating_only_against_source_members_and_unmatching_source_members_are_manually_mapped : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
public int Value2 { get; set; }
}
public class Destination
{
public int Value { get; set; }
public int Value3 { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>(MemberList.Source)
.ForMember(dest => dest.Value3, opt => opt.MapFrom(src => src.Value2));
});
[Fact]
public void Should_not_throw_a_configuration_validation_error()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_validating_only_against_source_members_and_unmatching_source_members_are_manually_mapped_with_resolvers : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
public int Value2 { get; set; }
}
public class Destination
{
public int Value { get; set; }
public int Value3 { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>(MemberList.Source)
.ForMember(dest => dest.Value3, opt => opt.ResolveUsing(src => src.Value2))
.ForSourceMember(src => src.Value2, opt => opt.Ignore());
});
[Fact]
public void Should_not_throw_a_configuration_validation_error()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(Configuration.AssertConfigurationIsValid);
}
}
public class When_reverse_mapping_and_ignoring_via_method : NonValidatingSpecBase
{
public class Source
{
public int Value { get; set; }
}
public class Dest
{
public int Value { get; set; }
public int Ignored { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Dest>()
.ForMember(d => d.Ignored, opt => opt.Ignore())
.ReverseMap();
});
[Fact]
public void Should_show_valid()
{
typeof(AutoMapperConfigurationException).ShouldNotBeThrownBy(() => Configuration.AssertConfigurationIsValid());
}
}
public class When_reverse_mapping_and_ignoring : SpecBase
{
public class Foo
{
public string Bar { get; set; }
public string Baz { get; set; }
}
public class Foo2
{
public string Bar { get; set; }
public string Boo { get; set; }
}
[Fact]
public void GetUnmappedPropertyNames_ShouldReturnBoo()
{
//Arrange
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Foo, Foo2>();
});
var typeMap = config.GetAllTypeMaps()
.First(x => x.SourceType == typeof(Foo) && x.DestinationType == typeof(Foo2));
//Act
var unmappedPropertyNames = typeMap.GetUnmappedPropertyNames();
//Assert
unmappedPropertyNames[0].ShouldBe("Boo");
}
[Fact]
public void WhenSecondCallTo_GetUnmappedPropertyNames_ShouldReturnBoo()
{
//Arrange
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Foo, Foo2>().ReverseMap();
});
var typeMap = config.GetAllTypeMaps()
.First(x => x.SourceType == typeof(Foo2) && x.DestinationType == typeof(Foo));
//Act
var unmappedPropertyNames = typeMap.GetUnmappedPropertyNames();
//Assert
unmappedPropertyNames[0].ShouldBe("Boo");
}
}
public class When_reverse_mapping_open_generics : AutoMapperSpecBase
{
private Source<int> _source;
public class Source<T>
{
public T Value { get; set; }
}
public class Destination<T>
{
public T Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap(typeof(Source<>), typeof(Destination<>))
.ReverseMap();
});
protected override void Because_of()
{
var dest = new Destination<int>
{
Value = 10
};
_source = Mapper.Map<Destination<int>, Source<int>>(dest);
}
[Fact]
public void Should_create_a_map_with_the_reverse_items()
{
_source.Value.ShouldBe(10);
}
}
} |
namespace Tipshare
{
partial class Tipshare
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.gbAM = new System.Windows.Forms.GroupBox();
this.tbAMUnallocatedAdj = new System.Windows.Forms.TextBox();
this.lblAMCurrentUnallocated = new System.Windows.Forms.Label();
this.tbAMUnallocatedSugg = new System.Windows.Forms.TextBox();
this.lblAMUnallocated = new System.Windows.Forms.Label();
this.lAMAdj = new System.Windows.Forms.Label();
this.lAMSugg = new System.Windows.Forms.Label();
this.lAMID = new System.Windows.Forms.Label();
this.lAMName = new System.Windows.Forms.Label();
this.gbControls = new System.Windows.Forms.GroupBox();
this.btnDistributeUnallocated = new System.Windows.Forms.Button();
this.btnSettings = new System.Windows.Forms.Button();
this.btnReset = new System.Windows.Forms.Button();
this.btnSave = new System.Windows.Forms.Button();
this.lDate = new System.Windows.Forms.Label();
this.lDay = new System.Windows.Forms.Label();
this.bDayBack = new System.Windows.Forms.Button();
this.bDayForward = new System.Windows.Forms.Button();
this.gbPM = new System.Windows.Forms.GroupBox();
this.tbPMUnallocatedAdj = new System.Windows.Forms.TextBox();
this.lblPMCurrentUnallocated = new System.Windows.Forms.Label();
this.tbPMUnallocatedSugg = new System.Windows.Forms.TextBox();
this.lblPMUnallocated = new System.Windows.Forms.Label();
this.lPMAdj = new System.Windows.Forms.Label();
this.lPMSugg = new System.Windows.Forms.Label();
this.lPMID = new System.Windows.Forms.Label();
this.lPMName = new System.Windows.Forms.Label();
this.msMenu = new System.Windows.Forms.MenuStrip();
this.mFile = new System.Windows.Forms.ToolStripMenuItem();
this.miJump = new System.Windows.Forms.ToolStripMenuItem();
this.miPrint = new System.Windows.Forms.ToolStripMenuItem();
this.miExit = new System.Windows.Forms.ToolStripMenuItem();
this.mAbout = new System.Windows.Forms.ToolStripMenuItem();
this.miHelp = new System.Windows.Forms.ToolStripMenuItem();
this.miAbout = new System.Windows.Forms.ToolStripMenuItem();
this.tTimer = new System.Windows.Forms.Timer(this.components);
this.gbTotals = new System.Windows.Forms.GroupBox();
this.lTotalSugg = new System.Windows.Forms.Label();
this.lTotalAdj = new System.Windows.Forms.Label();
this.lLabTotSug = new System.Windows.Forms.Label();
this.lTotalAMSugg = new System.Windows.Forms.Label();
this.lTotalAMAdj = new System.Windows.Forms.Label();
this.lLabTotAMSugg = new System.Windows.Forms.Label();
this.lTotalPMSugg = new System.Windows.Forms.Label();
this.lTotalPMAdj = new System.Windows.Forms.Label();
this.lLabTotPMSugg = new System.Windows.Forms.Label();
this.gbAM.SuspendLayout();
this.gbControls.SuspendLayout();
this.gbPM.SuspendLayout();
this.msMenu.SuspendLayout();
this.gbTotals.SuspendLayout();
this.SuspendLayout();
//
// gbAM
//
this.gbAM.Controls.Add(this.tbAMUnallocatedAdj);
this.gbAM.Controls.Add(this.lblAMCurrentUnallocated);
this.gbAM.Controls.Add(this.tbAMUnallocatedSugg);
this.gbAM.Controls.Add(this.lblAMUnallocated);
this.gbAM.Controls.Add(this.lAMAdj);
this.gbAM.Controls.Add(this.lAMSugg);
this.gbAM.Controls.Add(this.lAMID);
this.gbAM.Controls.Add(this.lAMName);
this.gbAM.Location = new System.Drawing.Point(12, 27);
this.gbAM.Name = "gbAM";
this.gbAM.Size = new System.Drawing.Size(318, 430);
this.gbAM.TabIndex = 1;
this.gbAM.TabStop = false;
this.gbAM.Text = "AM Declarations";
//
// tbAMUnallocatedAdj
//
this.tbAMUnallocatedAdj.Location = new System.Drawing.Point(277, 404);
this.tbAMUnallocatedAdj.Name = "tbAMUnallocatedAdj";
this.tbAMUnallocatedAdj.ReadOnly = true;
this.tbAMUnallocatedAdj.Size = new System.Drawing.Size(35, 20);
this.tbAMUnallocatedAdj.TabIndex = 14;
//
// lblAMCurrentUnallocated
//
this.lblAMCurrentUnallocated.AutoSize = true;
this.lblAMCurrentUnallocated.Location = new System.Drawing.Point(167, 407);
this.lblAMCurrentUnallocated.Name = "lblAMCurrentUnallocated";
this.lblAMCurrentUnallocated.Size = new System.Drawing.Size(104, 13);
this.lblAMCurrentUnallocated.TabIndex = 13;
this.lblAMCurrentUnallocated.Text = "Current Unallocated:";
//
// tbAMUnallocatedSugg
//
this.tbAMUnallocatedSugg.Location = new System.Drawing.Point(118, 404);
this.tbAMUnallocatedSugg.Name = "tbAMUnallocatedSugg";
this.tbAMUnallocatedSugg.ReadOnly = true;
this.tbAMUnallocatedSugg.Size = new System.Drawing.Size(35, 20);
this.tbAMUnallocatedSugg.TabIndex = 12;
//
// lblAMUnallocated
//
this.lblAMUnallocated.AutoSize = true;
this.lblAMUnallocated.Location = new System.Drawing.Point(6, 407);
this.lblAMUnallocated.Name = "lblAMUnallocated";
this.lblAMUnallocated.Size = new System.Drawing.Size(106, 13);
this.lblAMUnallocated.TabIndex = 10;
this.lblAMUnallocated.Text = "Starting Unallocated:";
//
// lAMAdj
//
this.lAMAdj.AutoSize = true;
this.lAMAdj.Location = new System.Drawing.Point(276, 16);
this.lAMAdj.Name = "lAMAdj";
this.lAMAdj.Size = new System.Drawing.Size(22, 13);
this.lAMAdj.TabIndex = 9;
this.lAMAdj.Text = "Adj";
//
// lAMSugg
//
this.lAMSugg.AutoSize = true;
this.lAMSugg.Location = new System.Drawing.Point(216, 16);
this.lAMSugg.Name = "lAMSugg";
this.lAMSugg.Size = new System.Drawing.Size(32, 13);
this.lAMSugg.TabIndex = 8;
this.lAMSugg.Text = "Sugg";
//
// lAMID
//
this.lAMID.AutoSize = true;
this.lAMID.Location = new System.Drawing.Point(169, 16);
this.lAMID.Name = "lAMID";
this.lAMID.Size = new System.Drawing.Size(18, 13);
this.lAMID.TabIndex = 7;
this.lAMID.Text = "ID";
//
// lAMName
//
this.lAMName.AutoSize = true;
this.lAMName.Location = new System.Drawing.Point(69, 16);
this.lAMName.Name = "lAMName";
this.lAMName.Size = new System.Drawing.Size(35, 13);
this.lAMName.TabIndex = 6;
this.lAMName.Text = "Name";
//
// gbControls
//
this.gbControls.Controls.Add(this.btnDistributeUnallocated);
this.gbControls.Controls.Add(this.btnSettings);
this.gbControls.Controls.Add(this.btnReset);
this.gbControls.Controls.Add(this.btnSave);
this.gbControls.Controls.Add(this.lDate);
this.gbControls.Controls.Add(this.lDay);
this.gbControls.Controls.Add(this.bDayBack);
this.gbControls.Controls.Add(this.bDayForward);
this.gbControls.Location = new System.Drawing.Point(12, 518);
this.gbControls.Name = "gbControls";
this.gbControls.Size = new System.Drawing.Size(648, 62);
this.gbControls.TabIndex = 2;
this.gbControls.TabStop = false;
this.gbControls.Text = "Controls";
//
// btnDistributeUnallocated
//
this.btnDistributeUnallocated.Enabled = false;
this.btnDistributeUnallocated.Location = new System.Drawing.Point(123, 19);
this.btnDistributeUnallocated.Name = "btnDistributeUnallocated";
this.btnDistributeUnallocated.Size = new System.Drawing.Size(111, 35);
this.btnDistributeUnallocated.TabIndex = 13;
this.btnDistributeUnallocated.Text = "Distribute Unallocated";
this.btnDistributeUnallocated.UseVisualStyleBackColor = true;
this.btnDistributeUnallocated.Click += new System.EventHandler(this.btnDistributeUnallocated_Click);
//
// btnSettings
//
this.btnSettings.Location = new System.Drawing.Point(6, 19);
this.btnSettings.Name = "btnSettings";
this.btnSettings.Size = new System.Drawing.Size(111, 35);
this.btnSettings.TabIndex = 12;
this.btnSettings.Text = "Advanced Settings";
this.btnSettings.UseVisualStyleBackColor = true;
this.btnSettings.Click += new System.EventHandler(this.btnSettings_Click);
//
// btnReset
//
this.btnReset.Location = new System.Drawing.Point(414, 19);
this.btnReset.Name = "btnReset";
this.btnReset.Size = new System.Drawing.Size(111, 35);
this.btnReset.TabIndex = 11;
this.btnReset.Text = "Reset Day";
this.btnReset.UseVisualStyleBackColor = true;
this.btnReset.Click += new System.EventHandler(this.btnReset_Click);
//
// btnSave
//
this.btnSave.Location = new System.Drawing.Point(531, 19);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(111, 35);
this.btnSave.TabIndex = 10;
this.btnSave.Text = "SAVE";
this.btnSave.UseVisualStyleBackColor = true;
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// lDate
//
this.lDate.AutoSize = true;
this.lDate.Location = new System.Drawing.Point(297, 19);
this.lDate.Name = "lDate";
this.lDate.Size = new System.Drawing.Size(64, 13);
this.lDate.TabIndex = 9;
this.lDate.Text = "##DATE##";
//
// lDay
//
this.lDay.AutoSize = true;
this.lDay.Location = new System.Drawing.Point(308, 41);
this.lDay.Name = "lDay";
this.lDay.Size = new System.Drawing.Size(26, 13);
this.lDay.TabIndex = 8;
this.lDay.Text = "Day";
//
// bDayBack
//
this.bDayBack.Location = new System.Drawing.Point(263, 35);
this.bDayBack.Name = "bDayBack";
this.bDayBack.Size = new System.Drawing.Size(39, 23);
this.bDayBack.TabIndex = 1;
this.bDayBack.Text = "<<";
this.bDayBack.UseVisualStyleBackColor = true;
this.bDayBack.Click += new System.EventHandler(this.bDayBack_Click);
//
// bDayForward
//
this.bDayForward.Location = new System.Drawing.Point(340, 36);
this.bDayForward.Name = "bDayForward";
this.bDayForward.Size = new System.Drawing.Size(39, 23);
this.bDayForward.TabIndex = 0;
this.bDayForward.Text = ">>";
this.bDayForward.UseVisualStyleBackColor = true;
this.bDayForward.Click += new System.EventHandler(this.bDayForward_Click);
//
// gbPM
//
this.gbPM.Controls.Add(this.tbPMUnallocatedAdj);
this.gbPM.Controls.Add(this.lblPMCurrentUnallocated);
this.gbPM.Controls.Add(this.tbPMUnallocatedSugg);
this.gbPM.Controls.Add(this.lblPMUnallocated);
this.gbPM.Controls.Add(this.lPMAdj);
this.gbPM.Controls.Add(this.lPMSugg);
this.gbPM.Controls.Add(this.lPMID);
this.gbPM.Controls.Add(this.lPMName);
this.gbPM.Location = new System.Drawing.Point(342, 27);
this.gbPM.Name = "gbPM";
this.gbPM.Size = new System.Drawing.Size(318, 430);
this.gbPM.TabIndex = 4;
this.gbPM.TabStop = false;
this.gbPM.Text = "PM Declarations";
//
// tbPMUnallocatedAdj
//
this.tbPMUnallocatedAdj.Location = new System.Drawing.Point(277, 404);
this.tbPMUnallocatedAdj.Name = "tbPMUnallocatedAdj";
this.tbPMUnallocatedAdj.ReadOnly = true;
this.tbPMUnallocatedAdj.Size = new System.Drawing.Size(35, 20);
this.tbPMUnallocatedAdj.TabIndex = 18;
//
// lblPMCurrentUnallocated
//
this.lblPMCurrentUnallocated.AutoSize = true;
this.lblPMCurrentUnallocated.Location = new System.Drawing.Point(167, 407);
this.lblPMCurrentUnallocated.Name = "lblPMCurrentUnallocated";
this.lblPMCurrentUnallocated.Size = new System.Drawing.Size(104, 13);
this.lblPMCurrentUnallocated.TabIndex = 17;
this.lblPMCurrentUnallocated.Text = "Current Unallocated:";
//
// tbPMUnallocatedSugg
//
this.tbPMUnallocatedSugg.Location = new System.Drawing.Point(115, 404);
this.tbPMUnallocatedSugg.Name = "tbPMUnallocatedSugg";
this.tbPMUnallocatedSugg.ReadOnly = true;
this.tbPMUnallocatedSugg.Size = new System.Drawing.Size(35, 20);
this.tbPMUnallocatedSugg.TabIndex = 15;
//
// lblPMUnallocated
//
this.lblPMUnallocated.AutoSize = true;
this.lblPMUnallocated.Location = new System.Drawing.Point(6, 407);
this.lblPMUnallocated.Name = "lblPMUnallocated";
this.lblPMUnallocated.Size = new System.Drawing.Size(106, 13);
this.lblPMUnallocated.TabIndex = 14;
this.lblPMUnallocated.Text = "Starting Unallocated:";
//
// lPMAdj
//
this.lPMAdj.AutoSize = true;
this.lPMAdj.Location = new System.Drawing.Point(276, 16);
this.lPMAdj.Name = "lPMAdj";
this.lPMAdj.Size = new System.Drawing.Size(22, 13);
this.lPMAdj.TabIndex = 13;
this.lPMAdj.Text = "Adj";
//
// lPMSugg
//
this.lPMSugg.AutoSize = true;
this.lPMSugg.Location = new System.Drawing.Point(216, 16);
this.lPMSugg.Name = "lPMSugg";
this.lPMSugg.Size = new System.Drawing.Size(32, 13);
this.lPMSugg.TabIndex = 12;
this.lPMSugg.Text = "Sugg";
//
// lPMID
//
this.lPMID.AutoSize = true;
this.lPMID.Location = new System.Drawing.Point(169, 16);
this.lPMID.Name = "lPMID";
this.lPMID.Size = new System.Drawing.Size(18, 13);
this.lPMID.TabIndex = 11;
this.lPMID.Text = "ID";
//
// lPMName
//
this.lPMName.AutoSize = true;
this.lPMName.Location = new System.Drawing.Point(69, 16);
this.lPMName.Name = "lPMName";
this.lPMName.Size = new System.Drawing.Size(35, 13);
this.lPMName.TabIndex = 10;
this.lPMName.Text = "Name";
//
// msMenu
//
this.msMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mFile,
this.mAbout});
this.msMenu.Location = new System.Drawing.Point(0, 0);
this.msMenu.Name = "msMenu";
this.msMenu.Size = new System.Drawing.Size(672, 24);
this.msMenu.TabIndex = 5;
this.msMenu.Text = "MenuStrip";
//
// mFile
//
this.mFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miJump,
this.miPrint,
this.miExit});
this.mFile.Name = "mFile";
this.mFile.Size = new System.Drawing.Size(37, 20);
this.mFile.Text = "File";
//
// miJump
//
this.miJump.Name = "miJump";
this.miJump.Size = new System.Drawing.Size(148, 22);
this.miJump.Text = "Jump to day...";
//
// miPrint
//
this.miPrint.Name = "miPrint";
this.miPrint.Size = new System.Drawing.Size(148, 22);
this.miPrint.Text = "Print Today";
this.miPrint.Click += new System.EventHandler(this.miPrint_Click);
//
// miExit
//
this.miExit.Name = "miExit";
this.miExit.Size = new System.Drawing.Size(148, 22);
this.miExit.Text = "Exit";
this.miExit.Click += new System.EventHandler(this.miExit_Click);
//
// mAbout
//
this.mAbout.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miHelp,
this.miAbout});
this.mAbout.Name = "mAbout";
this.mAbout.Size = new System.Drawing.Size(52, 20);
this.mAbout.Text = "About";
//
// miHelp
//
this.miHelp.Name = "miHelp";
this.miHelp.Size = new System.Drawing.Size(107, 22);
this.miHelp.Text = "Help";
this.miHelp.Click += new System.EventHandler(this.miHelp_Click);
//
// miAbout
//
this.miAbout.Name = "miAbout";
this.miAbout.Size = new System.Drawing.Size(107, 22);
this.miAbout.Text = "About";
this.miAbout.Click += new System.EventHandler(this.miAbout_Click);
//
// tTimer
//
this.tTimer.Tick += new System.EventHandler(this.tTimer_Tick);
//
// gbTotals
//
this.gbTotals.Controls.Add(this.lTotalSugg);
this.gbTotals.Controls.Add(this.lTotalAdj);
this.gbTotals.Controls.Add(this.lLabTotSug);
this.gbTotals.Controls.Add(this.lTotalAMSugg);
this.gbTotals.Controls.Add(this.lTotalAMAdj);
this.gbTotals.Controls.Add(this.lLabTotAMSugg);
this.gbTotals.Controls.Add(this.lTotalPMSugg);
this.gbTotals.Controls.Add(this.lTotalPMAdj);
this.gbTotals.Controls.Add(this.lLabTotPMSugg);
this.gbTotals.Location = new System.Drawing.Point(12, 463);
this.gbTotals.Name = "gbTotals";
this.gbTotals.Size = new System.Drawing.Size(648, 49);
this.gbTotals.TabIndex = 6;
this.gbTotals.TabStop = false;
this.gbTotals.Text = "Totals";
//
// lTotalSugg
//
this.lTotalSugg.AutoSize = true;
this.lTotalSugg.Location = new System.Drawing.Point(285, 29);
this.lTotalSugg.Name = "lTotalSugg";
this.lTotalSugg.Size = new System.Drawing.Size(21, 13);
this.lTotalSugg.TabIndex = 8;
this.lTotalSugg.Text = "##";
//
// lTotalAdj
//
this.lTotalAdj.AutoSize = true;
this.lTotalAdj.Location = new System.Drawing.Point(348, 29);
this.lTotalAdj.Name = "lTotalAdj";
this.lTotalAdj.Size = new System.Drawing.Size(21, 13);
this.lTotalAdj.TabIndex = 7;
this.lTotalAdj.Text = "##";
//
// lLabTotSug
//
this.lLabTotSug.AutoSize = true;
this.lLabTotSug.Location = new System.Drawing.Point(285, 16);
this.lLabTotSug.Name = "lLabTotSug";
this.lLabTotSug.Size = new System.Drawing.Size(79, 13);
this.lLabTotSug.TabIndex = 6;
this.lLabTotSug.Text = "Total Sugg/Adj";
//
// lTotalAMSugg
//
this.lTotalAMSugg.AutoSize = true;
this.lTotalAMSugg.Location = new System.Drawing.Point(32, 29);
this.lTotalAMSugg.Name = "lTotalAMSugg";
this.lTotalAMSugg.Size = new System.Drawing.Size(21, 13);
this.lTotalAMSugg.TabIndex = 5;
this.lTotalAMSugg.Text = "##";
//
// lTotalAMAdj
//
this.lTotalAMAdj.AutoSize = true;
this.lTotalAMAdj.Location = new System.Drawing.Point(83, 29);
this.lTotalAMAdj.Name = "lTotalAMAdj";
this.lTotalAMAdj.Size = new System.Drawing.Size(21, 13);
this.lTotalAMAdj.TabIndex = 4;
this.lTotalAMAdj.Text = "##";
//
// lLabTotAMSugg
//
this.lLabTotAMSugg.AutoSize = true;
this.lLabTotAMSugg.Location = new System.Drawing.Point(19, 16);
this.lLabTotAMSugg.Name = "lLabTotAMSugg";
this.lLabTotAMSugg.Size = new System.Drawing.Size(98, 13);
this.lLabTotAMSugg.TabIndex = 3;
this.lLabTotAMSugg.Text = "Total AM Sugg/Adj";
//
// lTotalPMSugg
//
this.lTotalPMSugg.AutoSize = true;
this.lTotalPMSugg.Location = new System.Drawing.Point(545, 29);
this.lTotalPMSugg.Name = "lTotalPMSugg";
this.lTotalPMSugg.Size = new System.Drawing.Size(21, 13);
this.lTotalPMSugg.TabIndex = 2;
this.lTotalPMSugg.Text = "##";
//
// lTotalPMAdj
//
this.lTotalPMAdj.AutoSize = true;
this.lTotalPMAdj.Location = new System.Drawing.Point(596, 29);
this.lTotalPMAdj.Name = "lTotalPMAdj";
this.lTotalPMAdj.Size = new System.Drawing.Size(21, 13);
this.lTotalPMAdj.TabIndex = 1;
this.lTotalPMAdj.Text = "##";
//
// lLabTotPMSugg
//
this.lLabTotPMSugg.AutoSize = true;
this.lLabTotPMSugg.Location = new System.Drawing.Point(530, 16);
this.lLabTotPMSugg.Name = "lLabTotPMSugg";
this.lLabTotPMSugg.Size = new System.Drawing.Size(98, 13);
this.lLabTotPMSugg.TabIndex = 0;
this.lLabTotPMSugg.Text = "Total PM Sugg/Adj";
//
// Tipshare
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(672, 592);
this.Controls.Add(this.gbTotals);
this.Controls.Add(this.gbPM);
this.Controls.Add(this.gbControls);
this.Controls.Add(this.gbAM);
this.Controls.Add(this.msMenu);
this.MainMenuStrip = this.msMenu;
this.Name = "Tipshare";
this.Text = "Tipshare##VERSION## - ##STORENAME##";
this.Load += new System.EventHandler(this.Tipshare_Load);
this.gbAM.ResumeLayout(false);
this.gbAM.PerformLayout();
this.gbControls.ResumeLayout(false);
this.gbControls.PerformLayout();
this.gbPM.ResumeLayout(false);
this.gbPM.PerformLayout();
this.msMenu.ResumeLayout(false);
this.msMenu.PerformLayout();
this.gbTotals.ResumeLayout(false);
this.gbTotals.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox gbAM;
private System.Windows.Forms.GroupBox gbControls;
private System.Windows.Forms.GroupBox gbPM;
private System.Windows.Forms.Button bDayBack;
private System.Windows.Forms.Button bDayForward;
private System.Windows.Forms.Label lAMName;
private System.Windows.Forms.Label lAMAdj;
private System.Windows.Forms.Label lAMSugg;
private System.Windows.Forms.Label lAMID;
private System.Windows.Forms.Label lDate;
private System.Windows.Forms.Label lDay;
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.Button btnDistributeUnallocated;
private System.Windows.Forms.Button btnSettings;
private System.Windows.Forms.Button btnReset;
private System.Windows.Forms.Label lPMAdj;
private System.Windows.Forms.Label lPMSugg;
private System.Windows.Forms.Label lPMID;
private System.Windows.Forms.Label lPMName;
private System.Windows.Forms.MenuStrip msMenu;
private System.Windows.Forms.ToolStripMenuItem mFile;
private System.Windows.Forms.ToolStripMenuItem miJump;
private System.Windows.Forms.ToolStripMenuItem miPrint;
private System.Windows.Forms.ToolStripMenuItem miExit;
private System.Windows.Forms.ToolStripMenuItem mAbout;
private System.Windows.Forms.ToolStripMenuItem miHelp;
private System.Windows.Forms.ToolStripMenuItem miAbout;
private System.Windows.Forms.Timer tTimer;
private System.Windows.Forms.GroupBox gbTotals;
private System.Windows.Forms.Label lTotalPMAdj;
private System.Windows.Forms.Label lLabTotPMSugg;
private System.Windows.Forms.Label lTotalAMSugg;
private System.Windows.Forms.Label lTotalAMAdj;
private System.Windows.Forms.Label lLabTotAMSugg;
private System.Windows.Forms.Label lTotalPMSugg;
private System.Windows.Forms.Label lTotalSugg;
private System.Windows.Forms.Label lTotalAdj;
private System.Windows.Forms.Label lLabTotSug;
private System.Windows.Forms.TextBox tbAMUnallocatedSugg;
private System.Windows.Forms.Label lblAMUnallocated;
private System.Windows.Forms.TextBox tbPMUnallocatedSugg;
private System.Windows.Forms.Label lblPMUnallocated;
private System.Windows.Forms.TextBox tbAMUnallocatedAdj;
private System.Windows.Forms.Label lblAMCurrentUnallocated;
private System.Windows.Forms.TextBox tbPMUnallocatedAdj;
private System.Windows.Forms.Label lblPMCurrentUnallocated;
}
}
|
using System;
using Server;
using Server.Gumps;
using Server.Network;
namespace Server.Items
{
public class PowerScroll : Item
{
private SkillName m_Skill;
private double m_Value;
private static SkillName[] m_Skills = new SkillName[]
{
SkillName.Blacksmith,
SkillName.Tailoring,
SkillName.Swords,
SkillName.Fencing,
SkillName.Macing,
SkillName.Archery,
SkillName.Wrestling,
SkillName.Parry,
SkillName.Tactics,
SkillName.Anatomy,
SkillName.Healing,
SkillName.Magery,
SkillName.Meditation,
SkillName.EvalInt,
SkillName.MagicResist,
SkillName.AnimalTaming,
SkillName.AnimalLore,
SkillName.Veterinary,
SkillName.Musicianship,
SkillName.Provocation,
SkillName.Discordance,
SkillName.Peacemaking
};
private static SkillName[] m_AOSSkills = new SkillName[]
{
SkillName.Blacksmith,
SkillName.Tailoring,
SkillName.Swords,
SkillName.Fencing,
SkillName.Macing,
SkillName.Archery,
SkillName.Wrestling,
SkillName.Parry,
SkillName.Tactics,
SkillName.Anatomy,
SkillName.Healing,
SkillName.Magery,
SkillName.Meditation,
SkillName.EvalInt,
SkillName.MagicResist,
SkillName.AnimalTaming,
SkillName.AnimalLore,
SkillName.Veterinary,
SkillName.Musicianship,
SkillName.Provocation,
SkillName.Discordance,
SkillName.Peacemaking,
SkillName.Chivalry,
SkillName.Focus,
SkillName.Necromancy,
SkillName.Stealing,
SkillName.Stealth,
SkillName.SpiritSpeak
};
private static SkillName[] m_SESkills = new SkillName[]
{
SkillName.Blacksmith,
SkillName.Tailoring,
SkillName.Swords,
SkillName.Fencing,
SkillName.Macing,
SkillName.Archery,
SkillName.Wrestling,
SkillName.Parry,
SkillName.Tactics,
SkillName.Anatomy,
SkillName.Healing,
SkillName.Magery,
SkillName.Meditation,
SkillName.EvalInt,
SkillName.MagicResist,
SkillName.AnimalTaming,
SkillName.AnimalLore,
SkillName.Veterinary,
SkillName.Musicianship,
SkillName.Provocation,
SkillName.Discordance,
SkillName.Peacemaking,
SkillName.Chivalry,
SkillName.Focus,
SkillName.Necromancy,
SkillName.Stealing,
SkillName.Stealth,
SkillName.SpiritSpeak,
SkillName.Ninjitsu,
SkillName.Bushido
};
private static SkillName[] m_MLSkills = new SkillName[]
{
SkillName.Blacksmith,
SkillName.Tailoring,
SkillName.Swords,
SkillName.Fencing,
SkillName.Macing,
SkillName.Archery,
SkillName.Wrestling,
SkillName.Parry,
SkillName.Tactics,
SkillName.Anatomy,
SkillName.Healing,
SkillName.Magery,
SkillName.Meditation,
SkillName.EvalInt,
SkillName.MagicResist,
SkillName.AnimalTaming,
SkillName.AnimalLore,
SkillName.Veterinary,
SkillName.Musicianship,
SkillName.Provocation,
SkillName.Discordance,
SkillName.Peacemaking,
SkillName.Chivalry,
SkillName.Focus,
SkillName.Necromancy,
SkillName.Stealing,
SkillName.Stealth,
SkillName.SpiritSpeak,
SkillName.Ninjitsu,
SkillName.Bushido,
SkillName.Spellweaving
};
public static SkillName[] Skills{ get{ return ( Core.ML ? m_MLSkills : Core.SE ? m_SESkills : Core.AOS ? m_AOSSkills : m_Skills ); } }
public static PowerScroll CreateRandom( int min, int max )
{
min /= 5;
max /= 5;
SkillName[] skills = PowerScroll.Skills;
return new PowerScroll( skills[Utility.Random( skills.Length )], 100 + (Utility.RandomMinMax( min, max ) * 5));
}
public static PowerScroll CreateRandomNoCraft( int min, int max )
{
min /= 5;
max /= 5;
SkillName[] skills = PowerScroll.Skills;
SkillName skillName;
do
{
skillName = skills[Utility.Random( skills.Length )];
} while ( skillName == SkillName.Blacksmith || skillName == SkillName.Tailoring );
return new PowerScroll( skillName, 100 + (Utility.RandomMinMax( min, max ) * 5));
}
[Constructable]
public PowerScroll( SkillName skill, double value ) : base( 0x14F0 )
{
base.Hue = 0x481;
base.Weight = 1.0;
m_Skill = skill;
m_Value = value;
if ( m_Value > 105.0 )
LootType = LootType.Cursed;
}
public PowerScroll( Serial serial ) : base( serial )
{
}
[CommandProperty( AccessLevel.GameMaster )]
public SkillName Skill
{
get
{
return m_Skill;
}
set
{
m_Skill = value;
}
}
[CommandProperty( AccessLevel.GameMaster )]
public double Value
{
get
{
return m_Value;
}
set
{
m_Value = value;
}
}
private string GetNameLocalized()
{
return String.Concat( "#", (1044060 + (int)m_Skill).ToString() );
}
private string GetName()
{
int index = (int)m_Skill;
SkillInfo[] table = SkillInfo.Table;
if ( index >= 0 && index < table.Length )
return table[index].Name.ToLower();
else
return "???";
}
public override void AddNameProperty(ObjectPropertyList list)
{
if ( m_Value == 105.0 )
list.Add( 1049639, GetNameLocalized() ); // a wonderous scroll of ~1_type~ (105 Skill)
else if ( m_Value == 110.0 )
list.Add( 1049640, GetNameLocalized() ); // an exalted scroll of ~1_type~ (110 Skill)
else if ( m_Value == 115.0 )
list.Add( 1049641, GetNameLocalized() ); // a mythical scroll of ~1_type~ (115 Skill)
else if ( m_Value == 120.0 )
list.Add( 1049642, GetNameLocalized() ); // a legendary scroll of ~1_type~ (120 Skill)
else
list.Add( "a power scroll of {0} ({1} Skill)", GetName(), m_Value );
}
public override void OnSingleClick( Mobile from )
{
if ( m_Value == 105.0 )
base.LabelTo( from, 1049639, GetNameLocalized() ); // a wonderous scroll of ~1_type~ (105 Skill)
else if ( m_Value == 110.0 )
base.LabelTo( from, 1049640, GetNameLocalized() ); // an exalted scroll of ~1_type~ (110 Skill)
else if ( m_Value == 115.0 )
base.LabelTo( from, 1049641, GetNameLocalized() ); // a mythical scroll of ~1_type~ (115 Skill)
else if ( m_Value == 120.0 )
base.LabelTo( from, 1049642, GetNameLocalized() ); // a legendary scroll of ~1_type~ (120 Skill)
else
base.LabelTo( from, "a power scroll of {0} ({1} Skill)", GetName(), m_Value );
}
public void Use( Mobile from, bool firstStage )
{
if ( Deleted )
return;
if ( IsChildOf( from.Backpack ) )
{
Skill skill = from.Skills[m_Skill];
if ( skill != null )
{
if ( skill.Cap >= m_Value )
{
from.SendLocalizedMessage( 1049511, GetNameLocalized() ); // Your ~1_type~ is too high for this power scroll.
}
else
{
if ( firstStage )
{
from.CloseGump( typeof( StatCapScroll.InternalGump ) );
from.CloseGump( typeof( PowerScroll.InternalGump ) );
from.SendGump( new InternalGump( from, this ) );
}
else
{
from.SendLocalizedMessage( 1049513, GetNameLocalized() ); // You feel a surge of magic as the scroll enhances your ~1_type~!
skill.Cap = m_Value;
Effects.SendLocationParticles( EffectItem.Create( from.Location, from.Map, EffectItem.DefaultDuration ), 0, 0, 0, 0, 0, 5060, 0 );
Effects.PlaySound( from.Location, from.Map, 0x243 );
Effects.SendMovingParticles( new Entity( Serial.Zero, new Point3D( from.X - 6, from.Y - 6, from.Z + 15 ), from.Map ), from, 0x36D4, 7, 0, false, true, 0x497, 0, 9502, 1, 0, (EffectLayer)255, 0x100 );
Effects.SendMovingParticles( new Entity( Serial.Zero, new Point3D( from.X - 4, from.Y - 6, from.Z + 15 ), from.Map ), from, 0x36D4, 7, 0, false, true, 0x497, 0, 9502, 1, 0, (EffectLayer)255, 0x100 );
Effects.SendMovingParticles( new Entity( Serial.Zero, new Point3D( from.X - 6, from.Y - 4, from.Z + 15 ), from.Map ), from, 0x36D4, 7, 0, false, true, 0x497, 0, 9502, 1, 0, (EffectLayer)255, 0x100 );
Effects.SendTargetParticles( from, 0x375A, 35, 90, 0x00, 0x00, 9502, (EffectLayer)255, 0x100 );
Delete();
}
}
}
}
else
{
from.SendLocalizedMessage( 1042001 ); // That must be in your pack for you to use it.
}
}
public override void OnDoubleClick( Mobile from )
{
Use( from, true );
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
writer.Write( (int) m_Skill );
writer.Write( (double) m_Value );
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch ( version )
{
case 0:
{
m_Skill = (SkillName)reader.ReadInt();
m_Value = reader.ReadDouble();
break;
}
}
if ( m_Value == 105.0 )
{
LootType = LootType.Regular;
}
else
{
LootType = LootType.Cursed;
if ( Insured )
Insured = false;
}
}
public class InternalGump : Gump
{
private Mobile m_Mobile;
private PowerScroll m_Scroll;
public InternalGump( Mobile mobile, PowerScroll scroll ) : base( 25, 50 )
{
m_Mobile = mobile;
m_Scroll = scroll;
AddPage( 0 );
AddBackground( 25, 10, 420, 200, 5054 );
AddImageTiled( 33, 20, 401, 181, 2624 );
AddAlphaRegion( 33, 20, 401, 181 );
AddHtmlLocalized( 40, 48, 387, 100, 1049469, true, true ); /* Using a scroll increases the maximum amount of a specific skill or your maximum statistics.
* When used, the effect is not immediately seen without a gain of points with that skill or statistics.
* You can view your maximum skill values in your skills window.
* You can view your maximum statistic value in your statistics window.
*/
AddHtmlLocalized( 125, 148, 200, 20, 1049478, 0xFFFFFF, false, false ); // Do you wish to use this scroll?
AddButton( 100, 172, 4005, 4007, 1, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 135, 172, 120, 20, 1046362, 0xFFFFFF, false, false ); // Yes
AddButton( 275, 172, 4005, 4007, 0, GumpButtonType.Reply, 0 );
AddHtmlLocalized( 310, 172, 120, 20, 1046363, 0xFFFFFF, false, false ); // No
double value = scroll.m_Value;
if ( value == 105.0 )
AddHtmlLocalized( 40, 20, 260, 20, 1049635, 0xFFFFFF, false, false ); // Wonderous Scroll (105 Skill):
else if ( value == 110.0 )
AddHtmlLocalized( 40, 20, 260, 20, 1049636, 0xFFFFFF, false, false ); // Exalted Scroll (110 Skill):
else if ( value == 115.0 )
AddHtmlLocalized( 40, 20, 260, 20, 1049637, 0xFFFFFF, false, false ); // Mythical Scroll (115 Skill):
else if ( value == 120.0 )
AddHtmlLocalized( 40, 20, 260, 20, 1049638, 0xFFFFFF, false, false ); // Legendary Scroll (120 Skill):
else
AddHtml( 40, 20, 260, 20, String.Format( "<basefont color=#FFFFFF>Power Scroll ({0} Skill):</basefont>", value ), false, false );
AddHtmlLocalized( 310, 20, 120, 20, 1044060 + (int)scroll.m_Skill, 0xFFFFFF, false, false );
}
public override void OnResponse( NetState state, RelayInfo info )
{
if ( info.ButtonID == 1 )
m_Scroll.Use( m_Mobile, false );
}
}
}
} |
// <copyright file="Collision.cs" company="LeagueSharp">
// Copyright (c) 2015 LeagueSharp.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/
// </copyright>
namespace LeagueSharp.SDK
{
using System;
using System.Collections.Generic;
using System.Linq;
using LeagueSharp.Data.Enumerations;
using LeagueSharp.SDK.Polygons;
using LeagueSharp.SDK.Utils;
using SharpDX;
/// <summary>
/// Collision class, calculates collision for moving objects.
/// </summary>
public static class Collision
{
#region Static Fields
private static MissileClient yasuoWallLeft, yasuoWallRight;
private static RectanglePoly yasuoWallPoly;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes static members of the <see cref="Collision" /> class.
/// Static Constructor
/// </summary>
static Collision()
{
GameObject.OnCreate += (sender, args) =>
{
var missile = sender as MissileClient;
var spellCaster = missile?.SpellCaster as Obj_AI_Hero;
if (spellCaster == null || spellCaster.ChampionName != "Yasuo"
|| spellCaster.Team == GameObjects.Player.Team)
{
return;
}
switch (missile.SData.Name)
{
case "YasuoWMovingWallMisL":
yasuoWallLeft = missile;
break;
case "YasuoWMovingWallMisR":
yasuoWallRight = missile;
break;
case "YasuoWMovingWallMisVis":
yasuoWallRight = missile;
break;
}
};
GameObject.OnDelete += (sender, args) =>
{
var missile = sender as MissileClient;
if (missile == null)
{
return;
}
if (missile.Compare(yasuoWallLeft))
{
yasuoWallLeft = null;
}
else if (missile.Compare(yasuoWallRight))
{
yasuoWallRight = null;
}
};
}
#endregion
#region Public Methods and Operators
/// <summary>
/// Returns the list of the units that the skill-shot will hit before reaching the set positions.
/// </summary>
/// <param name="positions">
/// The positions.
/// </param>
/// <param name="input">
/// The input.
/// </param>
/// <returns>
/// A list of <c>Obj_AI_Base</c>s which the input collides with.
/// </returns>
public static List<Obj_AI_Base> GetCollision(List<Vector3> positions, PredictionInput input)
{
var result = new List<Obj_AI_Base>();
foreach (var position in positions)
{
if (input.CollisionObjects.HasFlag(CollisionableObjects.Minions))
{
result.AddRange(
GameObjects.EnemyMinions.Where(i => i.IsMinion() || i.IsPet())
.Concat(GameObjects.Jungle)
.Where(
minion =>
minion.IsValidTarget(
Math.Min(input.Range + input.Radius + 100, 2000),
true,
input.RangeCheckFrom) && IsHitCollision(minion, input, position, 20)));
}
if (input.CollisionObjects.HasFlag(CollisionableObjects.Heroes))
{
result.AddRange(
GameObjects.EnemyHeroes.Where(
hero =>
hero.IsValidTarget(
Math.Min(input.Range + input.Radius + 100, 2000),
true,
input.RangeCheckFrom) && IsHitCollision(hero, input, position, 50)));
}
if (input.CollisionObjects.HasFlag(CollisionableObjects.Walls))
{
var step = position.Distance(input.From) / 20;
for (var i = 0; i < 20; i++)
{
if (input.From.ToVector2().Extend(position, step * i).IsWall())
{
result.Add(GameObjects.Player);
}
}
}
if (input.CollisionObjects.HasFlag(CollisionableObjects.YasuoWall))
{
if (yasuoWallLeft == null || yasuoWallRight == null)
{
continue;
}
yasuoWallPoly = new RectanglePoly(yasuoWallLeft.Position, yasuoWallRight.Position, 75);
var intersections = new List<Vector2>();
for (var i = 0; i < yasuoWallPoly.Points.Count; i++)
{
var inter =
yasuoWallPoly.Points[i].Intersection(
yasuoWallPoly.Points[i != yasuoWallPoly.Points.Count - 1 ? i + 1 : 0],
input.From.ToVector2(),
position.ToVector2());
if (inter.Intersects)
{
intersections.Add(inter.Point);
}
}
if (intersections.Count > 0)
{
result.Add(GameObjects.Player);
}
}
}
return result.Distinct().ToList();
}
#endregion
#region Methods
private static bool IsHitCollision(Obj_AI_Base collision, PredictionInput input, Vector3 pos, float extraRadius)
{
var inputSub = input.Clone() as PredictionInput;
if (inputSub == null)
{
return false;
}
inputSub.Unit = collision;
var predPos = Movement.GetPrediction(inputSub, false, false).UnitPosition.ToVector2();
return predPos.Distance(input.From) < input.Radius + input.Unit.BoundingRadius / 2
|| predPos.Distance(pos) < input.Radius + input.Unit.BoundingRadius / 2
|| predPos.DistanceSquared(input.From.ToVector2(), pos.ToVector2(), true)
<= Math.Pow(input.Radius + input.Unit.BoundingRadius + extraRadius, 2);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Collections;
using System.Web;
using System.Xml;
using System.Reflection;
using Microsoft.Win32;
using System.Globalization;
using Microsoft.FlightSimulator.SimConnect;
using System.Runtime.InteropServices;
namespace FSX_Google_Earth_Tracker
{
public partial class Form1 : Form
{
#region Global Variables
bool bErrorOnLoad = false;
Form2 frmAdd = new Form2();
String szAppPath = "";
//String szCommonPath = "";
String szUserAppPath = "";
String szFilePathPub = "";
String szFilePathData = "";
String szServerPath = "";
IPAddress[] ipalLocal1 = null;
IPAddress[] ipalLocal2 = null;
System.Object lockIPAddressList = new System.Object();
string /* szPathGE , */ szPathFSX;
const string szRegKeyRun = "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
//const int iOnlineVersionCheckRawDataLength = 64;
//WebRequest wrOnlineVersionCheck;
//WebResponse wrespOnlineVersionCheck;
//private byte[] bOnlineVersionCheckRawData = new byte[iOnlineVersionCheckRawDataLength];
//String szOnlineVersionCheckData = "";
XmlTextReader xmlrSeetingsFile;
XmlTextWriter xmlwSeetingsFile;
XmlDocument xmldSettings;
GlobalFixConfiguration gconffixCurrent = new GlobalFixConfiguration();
GlobalChangingConfiguration gconfchCurrent;
System.Object lockChConf = new System.Object();
bool bClose = false;
bool bConnected = false;
//bool bServerUp = false;
bool bRestartRequired = false;
const int WM_USER_SIMCONNECT = 0x0402;
SimConnect simconnect = null;
Icon icActive, icDisabled, icReceive;
Image imgAtcLabel;
HttpListener listener;
System.Object lockListenerControl = new System.Object();
uint uiUserAircraftID = 0;
bool bUserAircraftIDSet = false;
System.Object lockUserAircraftID = new System.Object();
StructBasicMovingSceneryObject suadCurrent;
System.Object lockKmlUserAircraft = new System.Object();
String szKmlUserAircraftPath = "";
System.Object lockKmlUserPath = new System.Object();
PathPosition ppPos1, ppPos2;
String szKmlUserPrediction = "";
List<PathPositionStored> listKmlPredictionPoints;
System.Object lockKmlUserPrediction = new System.Object();
System.Object lockKmlPredictionPoints = new System.Object();
DataRequestReturn drrAIPlanes;
System.Object lockDrrAiPlanes = new System.Object();
DataRequestReturn drrAIHelicopters;
System.Object lockDrrAiHelicopters = new System.Object();
DataRequestReturn drrAIBoats;
System.Object lockDrrAiBoats = new System.Object();
DataRequestReturn drrAIGround;
System.Object lockDrrAiGround = new System.Object();
List<ObjectImage> listIconsGE;
List<ObjectImage> listImgUnitsAir, listImgUnitsWater, listImgUnitsGround;
//List<FlightPlan> listFlightPlans;
//System.Object lockFlightPlanList = new System.Object();
byte[] imgNoImage;
#endregion
#region Structs & Enums
enum DEFINITIONS
{
StructBasicMovingSceneryObject,
};
enum DATA_REQUESTS
{
REQUEST_USER_AIRCRAFT,
REQUEST_USER_PATH,
REQUEST_USER_PREDICTION,
REQUEST_AI_HELICOPTER,
REQUEST_AI_PLANE,
REQUEST_AI_BOAT,
REQUEST_AI_GROUND
};
enum KML_FILES
{
REQUEST_USER_AIRCRAFT,
REQUEST_USER_PATH,
REQUEST_USER_PREDICTION,
REQUEST_AI_HELICOPTER,
REQUEST_AI_PLANE,
REQUEST_AI_BOAT,
REQUEST_AI_GROUND,
REQUEST_FLIGHT_PLANS
};
enum KML_ACCESS_MODES
{
MODE_SERVER,
MODE_FILE_LOCAL,
MODE_FILE_USERDEFINED
};
enum KML_IMAGE_TYPES
{
AIRCRAFT,
WATER,
GROUND
};
enum KML_ICON_TYPES
{
USER_AIRCRAFT_POSITION,
USER_PREDICTION_POINT,
AI_AIRCRAFT_PREDICTION_POINT,
AI_HELICOPTER_PREDICTION_POINT,
AI_BOAT_PREDICTION_POINT,
AI_GROUND_PREDICTION_POINT,
AI_AIRCRAFT,
AI_HELICOPTER,
AI_BOAT,
AI_GROUND_UNIT,
PLAN_VOR,
PLAN_NDB,
PLAN_USER,
PLAN_PORT,
PLAN_INTER,
ATC_LABEL,
UNKNOWN
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
struct StructBasicMovingSceneryObject
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public String szTitle;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public String szATCType;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public String szATCModel;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public String szATCID;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
public String szATCAirline;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public String szATCFlightNumber;
public double dLatitude;
public double dLongitude;
public double dAltitude;
public double dSpeed;
public double dVSpeed;
//public double dSpeedX;
//public double dSpeedY;
//public double dSpeedZ;
public double dTime;
};
struct DataRequestReturn
{
public List<DataRequestReturnObject> listFirst;
public List<DataRequestReturnObject> listSecond;
public uint uiLastEntryNumber;
public uint uiCurrentDataSet;
public bool bClearOnNextRun;
};
struct DataRequestReturnObject
{
public uint uiObjectID;
public StructBasicMovingSceneryObject bmsoObject;
public String szCoursePrediction;
public PathPositionStored[] ppsPredictionPoints;
}
struct PathPosition
{
public bool bInitialized;
public double dLat;
public double dLong;
public double dAlt;
public double dTime;
}
struct PathPositionStored
{
public double dLat;
public double dLong;
public double dAlt;
public double dTime;
}
struct ObjectImage
{
public String szTitle;
public String szPath;
public byte[] bData;
};
class GlobalFixConfiguration
{
public bool bLoadKMLFile;
//public bool bCheckForUpdates;
public long iServerPort;
public uint uiServerAccessLevel;
public String szUserdefinedPath;
public bool bQueryUserAircraft;
public long iTimerUserAircraft;
public bool bQueryUserPath;
public long iTimerUserPath;
public bool bUserPathPrediction;
public long iTimerUserPathPrediction;
public double[] dPredictionTimes;
public bool bQueryAIObjects;
public bool bQueryAIAircrafts;
public long iTimerAIAircrafts;
public long iRangeAIAircrafts;
public bool bPredictAIAircrafts;
public bool bPredictPointsAIAircrafts;
public bool bQueryAIHelicopters;
public long iTimerAIHelicopters;
public long iRangeAIHelicopters;
public bool bPredictAIHelicopters;
public bool bPredictPointsAIHelicopters;
public bool bQueryAIBoats;
public long iTimerAIBoats;
public long iRangeAIBoats;
public bool bPredictAIBoats;
public bool bPredictPointsAIBoats;
public bool bQueryAIGroundUnits;
public long iTimerAIGroundUnits;
public long iRangeAIGroundUnits;
public bool bPredictAIGroundUnits;
public bool bPredictPointsAIGroundUnits;
public long iUpdateGEUserAircraft;
public long iUpdateGEUserPath;
public long iUpdateGEUserPrediction;
public long iUpdateGEAIAircrafts;
public long iUpdateGEAIHelicopters;
public long iUpdateGEAIBoats;
public long iUpdateGEAIGroundUnits;
public bool bFsxConnectionIsLocal;
public String szFsxConnectionProtocol;
public String szFsxConnectionHost;
public String szFsxConnectionPort;
public bool bExitOnFsxExit;
private Object lock_utUnits = new Object();
private UnitType priv_utUnits;
public UnitType utUnits
{
get
{
lock (lock_utUnits)
{
return priv_utUnits;
}
}
set
{
lock (lock_utUnits)
{
priv_utUnits = value;
}
}
}
//public bool bLoadFlightPlans;
};
struct GlobalChangingConfiguration
{
public bool bEnabled;
public bool bShowBalloons;
};
struct ListBoxPredictionTimesItem
{
public double dTime;
public override String ToString()
{
if (dTime < 60)
return "ETA " + dTime + " sec";
else if (dTime < 3600)
return "ETA " + Math.Round(dTime / 60.0, 1) + " min";
else
return "ETA " + Math.Round(dTime / 3600.0, 2) + " hrs";
}
}
enum UnitType
{
METERS,
FEET
};
//struct ListViewFlightPlansItem
//{
// public String szName;
// public int iID;
// public override String ToString()
// {
// return szName.ToString();
// }
//}
//struct FlightPlan
//{
// public int uiID;
// public String szName;
// public XmlDocument xmldPlan;
//}
#endregion
#region Form Functions
public Form1()
{
//As this method doesn't start any other threads we don't need to lock anything here (especially not the config file xml document)
InitializeComponent();
Text = AssemblyTitle;
thrConnect = new Thread(new ThreadStart(openConnectionThreadFunction));
text = Text;
// Set data for the about page
this.labelProductName.Text = AssemblyProduct;
this.labelVersion.Text = String.Format("Version {0}", AssemblyVersion);
this.labelCopyright.Text = AssemblyCopyright;
this.labelCompanyName.Text = AssemblyCompany;
// Set file path
#if DEBUG
szAppPath = Application.StartupPath + "\\..\\..";
szUserAppPath = szAppPath + "\\AppData\\" + AssemblyVersion;
#else
szAppPath = Application.StartupPath;
szUserAppPath = Application.UserAppDataPath;
#endif
szFilePathPub = szAppPath + "\\pub";
szFilePathData = szAppPath + "\\data";
// Check if config file for current user exists
if (!File.Exists(szUserAppPath + "\\settings.cfg"))
{
if (!Directory.Exists(szUserAppPath))
Directory.CreateDirectory(szUserAppPath);
File.Copy(szAppPath + "\\data\\settings.default", szUserAppPath + "\\settings.cfg");
File.SetAttributes(szUserAppPath + "\\settings.cfg", FileAttributes.Normal);
}
// Load config file into memory
xmlrSeetingsFile = new XmlTextReader(szUserAppPath + "\\settings.cfg");
xmldSettings = new XmlDocument();
xmldSettings.PreserveWhitespace = true;
xmldSettings.Load(xmlrSeetingsFile);
xmlrSeetingsFile.Close();
xmlrSeetingsFile = null;
// Make sure we have a config file for the right version
// (future version should contain better checks and update from old config files to new version)
String szConfigVersion = "";
bool bUpdate = false;
try
{
szConfigVersion = xmldSettings["fsxget"]["settings"].Attributes["version"].Value;
}
catch
{
bUpdate = true;
}
if (bUpdate || !szConfigVersion.Equals(ProductVersion.ToLower()))
{
try
{
File.SetAttributes(szUserAppPath + "\\settings.cfg", FileAttributes.Normal);
File.Delete(szUserAppPath + "\\settings.cfg");
File.Copy(szAppPath + "\\data\\settings.default", szUserAppPath + "\\settings.cfg");
File.SetAttributes(szUserAppPath + "\\settings.cfg", FileAttributes.Normal);
xmlrSeetingsFile = new XmlTextReader(szUserAppPath + "\\settings.cfg");
xmldSettings = new XmlDocument();
xmldSettings.PreserveWhitespace = true;
xmldSettings.Load(xmlrSeetingsFile);
xmlrSeetingsFile.Close();
xmlrSeetingsFile = null;
xmldSettings["fsxget"]["settings"].Attributes["version"].Value = ProductVersion;
}
catch
{
MessageBox.Show("The config file for this program cannot be updated. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
bErrorOnLoad = true;
return;
}
}
// Mirror values we need from config file in memory to variables
try
{
ConfigMirrorToVariables();
}
catch
{
MessageBox.Show("The config file for this program contains errors. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
bErrorOnLoad = true;
return;
}
// Write SimConnect configuration file
try { File.Delete(szAppPath + "\\SimConnect.cfg"); }
catch { }
if (!gconffixCurrent.bFsxConnectionIsLocal)
{
try
{
StreamWriter swSimConnectCfg = File.CreateText(szAppPath + "\\SimConnect.cfg");
swSimConnectCfg.WriteLine("; FSXGET SimConnect client configuration");
swSimConnectCfg.WriteLine();
swSimConnectCfg.WriteLine("[SimConnect]");
swSimConnectCfg.WriteLine("Protocol=" + gconffixCurrent.szFsxConnectionProtocol);
swSimConnectCfg.WriteLine("Address=" + gconffixCurrent.szFsxConnectionHost);
swSimConnectCfg.WriteLine("Port=" + gconffixCurrent.szFsxConnectionPort);
swSimConnectCfg.WriteLine();
swSimConnectCfg.Flush();
swSimConnectCfg.Close();
swSimConnectCfg.Dispose();
}
catch
{
MessageBox.Show("The SimConnect client configuration file could not be written. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
bErrorOnLoad = true;
return;
}
}
// Update the notification icon context menu
lock (lockChConf)
{
enableTrackerToolStripMenuItem.Checked = gconfchCurrent.bEnabled;
showBalloonTipsToolStripMenuItem.Checked = gconfchCurrent.bShowBalloons;
}
// Set timer intervals
timerFSXConnect.Interval = 1500;
timerQueryUserAircraft.Interval = (int)gconffixCurrent.iTimerUserAircraft;
timerQueryUserPath.Interval = (int)gconffixCurrent.iTimerUserPath;
timerUserPrediction.Interval = (int)gconffixCurrent.iTimerUserPathPrediction;
timerQueryAIAircrafts.Interval = (int)gconffixCurrent.iTimerAIAircrafts;
timerQueryAIHelicopters.Interval = (int)gconffixCurrent.iTimerAIHelicopters;
timerQueryAIBoats.Interval = (int)gconffixCurrent.iTimerAIBoats;
timerQueryAIGroundUnits.Interval = (int)gconffixCurrent.iTimerAIGroundUnits;
timerIPAddressRefresh.Interval = 10000;
// Set server settings
szServerPath = "http://+:" + gconffixCurrent.iServerPort.ToString();
listener = new HttpListener();
listener.Prefixes.Add(szServerPath + "/");
// Lookup (in the config file) and load program icons, google earth pins and object images
try
{
// notification icons
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["program"]["icons"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.NodeType == XmlNodeType.Whitespace)
continue;
if (xmlnTemp.Attributes["Name"].Value == "Taskbar - Enabled")
icActive = new Icon(szFilePathData + xmlnTemp.Attributes["Img"].Value);
else if (xmlnTemp.Attributes["Name"].Value == "Taskbar - Disabled")
icDisabled = new Icon(szFilePathData + xmlnTemp.Attributes["Img"].Value);
else if (xmlnTemp.Attributes["Name"].Value == "Taskbar - Connected")
icReceive = new Icon(szFilePathData + xmlnTemp.Attributes["Img"].Value);
}
notifyIconMain.Icon = icDisabled;
notifyIconMain.Text = this.Text;
notifyIconMain.Visible = true;
// google earth icons
listIconsGE = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["ge"]["icons"].ChildNodes.Count);
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["ge"]["icons"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.NodeType == XmlNodeType.Whitespace)
continue;
ObjectImage imgTemp = new ObjectImage();
imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value;
imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value);
listIconsGE.Add(imgTemp);
}
// no-image image
imgNoImage = File.ReadAllBytes(szFilePathPub + xmldSettings["fsxget"]["gfx"]["scenery"]["noimage"].Attributes["Img"].Value);
// ATC label base image
imgAtcLabel = Image.FromFile(szFilePathData + xmldSettings["fsxget"]["gfx"]["ge"]["atclabel"].Attributes["Img"].Value);
// object images
listImgUnitsAir = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["scenery"]["air"].ChildNodes.Count);
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["scenery"]["air"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.NodeType == XmlNodeType.Whitespace)
continue;
ObjectImage imgTemp = new ObjectImage();
imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value;
imgTemp.szPath = xmlnTemp.Attributes["Img"].Value;
imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value);
listImgUnitsAir.Add(imgTemp);
}
listImgUnitsWater = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["scenery"]["water"].ChildNodes.Count);
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["scenery"]["water"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.NodeType == XmlNodeType.Whitespace)
continue;
ObjectImage imgTemp = new ObjectImage();
imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value;
imgTemp.szPath = xmlnTemp.Attributes["Img"].Value;
imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value);
listImgUnitsWater.Add(imgTemp);
}
listImgUnitsGround = new List<ObjectImage>(xmldSettings["fsxget"]["gfx"]["scenery"]["ground"].ChildNodes.Count);
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["gfx"]["scenery"]["ground"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.NodeType == XmlNodeType.Whitespace)
continue;
ObjectImage imgTemp = new ObjectImage();
imgTemp.szTitle = xmlnTemp.Attributes["Name"].Value;
imgTemp.szPath = xmlnTemp.Attributes["Img"].Value;
imgTemp.bData = File.ReadAllBytes(szFilePathPub + xmlnTemp.Attributes["Img"].Value);
listImgUnitsWater.Add(imgTemp);
}
}
catch
{
MessageBox.Show("Could not load all graphics files probably due to errors in the config file. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
bErrorOnLoad = true;
return;
}
// Initialize some variables
clearDrrStructure(ref drrAIPlanes);
clearDrrStructure(ref drrAIHelicopters);
clearDrrStructure(ref drrAIBoats);
clearDrrStructure(ref drrAIGround);
clearPPStructure(ref ppPos1);
clearPPStructure(ref ppPos2);
//listFlightPlans = new List<FlightPlan>();
listKmlPredictionPoints = new List<PathPositionStored>(gconffixCurrent.dPredictionTimes.GetLength(0));
// Test drive the following function which loads data from the config file, as it will be used regularly later on
try
{
ConfigMirrorToForm();
}
catch
{
MessageBox.Show("The config file for this program contains errors. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
bErrorOnLoad = true;
return;
}
// Load FSX and Google Earth path from registry
const string szRegKeyFSX = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft Games\\flight simulator\\10.0";
//const string szRegKeyGE = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Google\\Google Earth Plus";
//const string szRegKeyGE2 = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Google\\Google Earth Pro";
//szPathGE = (string)Registry.GetValue(szRegKeyGE, "InstallDir", "");
//if (szPathGE == "")
// szPathGE = (string)Registry.GetValue(szRegKeyGE2, "InstallDir", "");
szPathFSX = (string)Registry.GetValue(szRegKeyFSX, "SetupPath", "");
//if (szPathGE != "")
//{
// szPathGE += "\\googleearth.exe";
// if (File.Exists(szPathGE))
// runGoogleEarthToolStripMenuItem.Enabled = true;
// else
// runGoogleEarthToolStripMenuItem.Enabled = false;
//}
//else
// runGoogleEarthToolStripMenuItem.Enabled = false;
runGoogleEarthToolStripMenuItem.Enabled = true;
if (szPathFSX != "")
{
szPathFSX += "fsx.exe";
if (File.Exists(szPathFSX))
runMicrosoftFlightSimulatorXToolStripMenuItem.Enabled = true;
else
runMicrosoftFlightSimulatorXToolStripMenuItem.Enabled = false;
}
else
runMicrosoftFlightSimulatorXToolStripMenuItem.Enabled = false;
// Write Google Earth startup KML file
String szTempKMLFile = "";
String szTempKMLFileStatic = "";
if (CompileKMLStartUpFileDynamic("localhost", ref szTempKMLFile) && CompileKMLStartUpFileStatic("localhost", ref szTempKMLFileStatic))
{
try
{
if (!Directory.Exists(szUserAppPath + "\\pub"))
Directory.CreateDirectory(szUserAppPath + "\\pub");
File.WriteAllText(szUserAppPath + "\\pub\\fsxgetd.kml", szTempKMLFile);
File.WriteAllText(szUserAppPath + "\\pub\\fsxgets.kml", szTempKMLFileStatic);
}
catch
{
MessageBox.Show("Could not write KML file for google earth. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
bErrorOnLoad = true;
return;
}
}
else
{
MessageBox.Show("Could not write KML file for google earth. Aborting!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
bErrorOnLoad = true;
return;
}
// Init some never-changing form fields
textBoxLocalPubPath.Text = szFilePathPub;
// Load flight plans
//if (gconffixCurrent.bLoadFlightPlans)
// LoadFlightPlans();
// Online Update Check
//if (gconffixCurrent.bCheckForUpdates)
// checkForProgramUpdate();
}
private void Form1_Load(object sender, EventArgs e)
{
if (bErrorOnLoad)
return;
}
private void Form1_Shown(object sender, EventArgs e)
{
if (bErrorOnLoad)
{
bClose = true;
Close();
}
else
{
Hide();
lock (lockListenerControl)
{
listener.Start();
listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
//bServerUp = true;
}
globalConnect();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (!bClose)
{
e.Cancel = true;
safeHideMainDialog();
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (bErrorOnLoad)
return;
notifyIconMain.ContextMenuStrip = null;
// Save xml document in memory to config file on disc
xmlwSeetingsFile = new XmlTextWriter(szUserAppPath + "\\settings.cfg", null);
xmldSettings.PreserveWhitespace = true;
xmldSettings.Save(xmlwSeetingsFile);
xmlwSeetingsFile.Flush();
xmlwSeetingsFile.Close();
xmldSettings = null;
// Disconnect with FSX
lock (lockChConf)
{
gconfchCurrent.bEnabled = false;
}
globalDisconnect();
// Stop server
lock (lockListenerControl)
{
//bServerUp = false;
listener.Stop();
listener.Abort();
timerIPAddressRefresh.Stop();
}
// Delete temporary KML file
if (File.Exists(szFilePathPub + "\\fsxget.kml"))
{
try
{
File.Delete(szFilePathPub + "\\fsxget.kml");
}
catch { }
}
if (File.Exists(szAppPath + "\\SimConnect.cfg"))
{
try
{
File.Delete(szAppPath + "\\SimConnect.cfg");
}
catch { }
}
}
protected override void DefWndProc(ref Message m)
{
if (m.Msg == WM_USER_SIMCONNECT)
{
if (simconnect != null)
{
try
{
simconnect.ReceiveMessage();
}
catch
{
#if DEBUG
safeShowBalloonTip(3, "Error", "Error receiving data from FSX!", ToolTipIcon.Error);
#endif
}
}
}
else
base.DefWndProc(ref m);
}
#endregion
#region FSX Connection
Object lock_ConnectThread = new Object();
String text;
public void openConnectionThreadFunction()
{
while (simconnect == null)
{
try
{
simconnect = new SimConnect(text, IntPtr.Zero, WM_USER_SIMCONNECT, null, 0);
}
catch { }
if (simconnect == null)
Thread.Sleep(2000);
}
}
private bool openConnection()
{
if (thrConnect.ThreadState == ThreadState.Unstarted)
{
thrConnect.Start();
return false;
}
else if (thrConnect.ThreadState == ThreadState.Stopped)
{
if (simconnect != null)
{
try
{
simconnect.Dispose();
simconnect = null;
simconnect = new SimConnect(Text, this.Handle, WM_USER_SIMCONNECT, null, 0);
}
catch
{
return false;
}
if (initDataRequest())
return true;
else
{
simconnect = null;
return false;
}
}
else
{
thrConnect = new Thread(new ThreadStart(openConnectionThreadFunction));
thrConnect.Start();
return false;
}
}
else
return false;
}
private void closeConnection()
{
if (simconnect != null)
{
simconnect.Dispose();
simconnect = null;
}
}
private bool initDataRequest()
{
try
{
// listen to connect and quit msgs
simconnect.OnRecvOpen += new SimConnect.RecvOpenEventHandler(simconnect_OnRecvOpen);
simconnect.OnRecvQuit += new SimConnect.RecvQuitEventHandler(simconnect_OnRecvQuit);
// listen to exceptions
simconnect.OnRecvException += new SimConnect.RecvExceptionEventHandler(simconnect_OnRecvException);
// define a data structure
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Title", null, SIMCONNECT_DATATYPE.STRING256, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC Type", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC Model", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC ID", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC Airline", null, SIMCONNECT_DATATYPE.STRING64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "ATC Flight Number", null, SIMCONNECT_DATATYPE.STRING32, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Plane Latitude", "degrees", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Plane Longitude", "degrees", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Plane Altitude", "meters", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Ground Velocity", "knots", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Velocity World Y", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
//simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Velocity World X", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
//simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Velocity World Y", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
//simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Velocity World Z", "meter per second", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
simconnect.AddToDataDefinition(DEFINITIONS.StructBasicMovingSceneryObject, "Absolute Time", "seconds", SIMCONNECT_DATATYPE.FLOAT64, 0.0f, SimConnect.SIMCONNECT_UNUSED);
// IMPORTANT: register it with the simconnect managed wrapper marshaller
// if you skip this step, you will only receive a uint in the .dwData field.
simconnect.RegisterDataDefineStruct<StructBasicMovingSceneryObject>(DEFINITIONS.StructBasicMovingSceneryObject);
// catch a simobject data request
simconnect.OnRecvSimobjectDataBytype += new SimConnect.RecvSimobjectDataBytypeEventHandler(simconnect_OnRecvSimobjectDataBytype);
return true;
}
catch (COMException ex)
{
safeShowBalloonTip(3000, Text, "FSX Exception!\n\n" + ex.Message, ToolTipIcon.Error);
return false;
}
}
void simconnect_OnRecvOpen(SimConnect sender, SIMCONNECT_RECV_OPEN data)
{
lock (lockUserAircraftID)
{
bUserAircraftIDSet = false;
}
if (gconffixCurrent.bQueryUserAircraft)
timerQueryUserAircraft.Start();
if (gconffixCurrent.bQueryUserPath)
timerQueryUserPath.Start();
if (gconffixCurrent.bUserPathPrediction)
timerUserPrediction.Start();
if (gconffixCurrent.bQueryAIObjects)
{
if (gconffixCurrent.bQueryAIAircrafts)
timerQueryAIAircrafts.Start();
if (gconffixCurrent.bQueryAIHelicopters)
timerQueryAIHelicopters.Start();
if (gconffixCurrent.bQueryAIBoats)
timerQueryAIBoats.Start();
if (gconffixCurrent.bQueryAIGroundUnits)
timerQueryAIGroundUnits.Start();
}
timerIPAddressRefresh_Tick(null, null);
timerIPAddressRefresh.Start();
}
void simconnect_OnRecvQuit(SimConnect sender, SIMCONNECT_RECV data)
{
globalDisconnect();
if (gconffixCurrent.bExitOnFsxExit && isFsxStartActivated())
{
bClose = true;
Close();
}
}
void simconnect_OnRecvException(SimConnect sender, SIMCONNECT_RECV_EXCEPTION data)
{
safeShowBalloonTip(3000, Text, "FSX Exception!", ToolTipIcon.Error);
}
void simconnect_OnRecvSimobjectDataBytype(SimConnect sender, SIMCONNECT_RECV_SIMOBJECT_DATA_BYTYPE data)
{
if (data.dwentrynumber == 0 && data.dwoutof == 0)
return;
DataRequestReturnObject drroTemp;
drroTemp.bmsoObject = (StructBasicMovingSceneryObject)data.dwData[0];
drroTemp.uiObjectID = data.dwObjectID;
drroTemp.szCoursePrediction = "";
drroTemp.ppsPredictionPoints = null;
switch ((DATA_REQUESTS)data.dwRequestID)
{
case DATA_REQUESTS.REQUEST_USER_AIRCRAFT:
case DATA_REQUESTS.REQUEST_USER_PATH:
case DATA_REQUESTS.REQUEST_USER_PREDICTION:
lock (lockUserAircraftID)
{
bUserAircraftIDSet = true;
uiUserAircraftID = drroTemp.uiObjectID;
}
switch ((DATA_REQUESTS)data.dwRequestID)
{
case DATA_REQUESTS.REQUEST_USER_AIRCRAFT:
lock (lockKmlUserAircraft)
{
suadCurrent = drroTemp.bmsoObject;
}
break;
case DATA_REQUESTS.REQUEST_USER_PATH:
lock (lockKmlUserPath)
{
szKmlUserAircraftPath += drroTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "\n";
}
break;
case DATA_REQUESTS.REQUEST_USER_PREDICTION:
lock (lockKmlPredictionPoints)
{
if (!ppPos1.bInitialized)
{
ppPos1.dLong = drroTemp.bmsoObject.dLongitude;
ppPos1.dLat = drroTemp.bmsoObject.dLatitude;
ppPos1.dAlt = drroTemp.bmsoObject.dAltitude;
ppPos1.dTime = drroTemp.bmsoObject.dTime;
ppPos1.bInitialized = true;
return;
}
else
{
if (!ppPos2.bInitialized)
{
ppPos2.dLong = drroTemp.bmsoObject.dLongitude;
ppPos2.dLat = drroTemp.bmsoObject.dLatitude;
ppPos2.dAlt = drroTemp.bmsoObject.dAltitude;
ppPos2.dTime = drroTemp.bmsoObject.dTime;
ppPos2.bInitialized = true;
}
else
{
ppPos1 = ppPos2;
ppPos2.dLong = drroTemp.bmsoObject.dLongitude;
ppPos2.dLat = drroTemp.bmsoObject.dLatitude;
ppPos2.dAlt = drroTemp.bmsoObject.dAltitude;
ppPos2.dTime = drroTemp.bmsoObject.dTime;
//ppPos2.bInitialized = true;
}
}
if (ppPos1.dTime != ppPos2.dTime && ppPos1.bInitialized && ppPos2.bInitialized)
{
lock (lockKmlUserPrediction)
{
szKmlUserPrediction = drroTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + drroTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "\n";
listKmlPredictionPoints.Clear();
for (uint n = 0; n < gconffixCurrent.dPredictionTimes.GetLength(0); n++)
{
double dLongNew = 0.0, dLatNew = 0.0, dAltNew = 0.0;
calcPositionByTime(ref ppPos1, ref ppPos2, gconffixCurrent.dPredictionTimes[n], ref dLatNew, ref dLongNew, ref dAltNew);
PathPositionStored ppsTemp;
ppsTemp.dLat = dLatNew;
ppsTemp.dLong = dLongNew;
ppsTemp.dAlt = dAltNew;
ppsTemp.dTime = gconffixCurrent.dPredictionTimes[n];
listKmlPredictionPoints.Add(ppsTemp);
szKmlUserPrediction += dLongNew.ToString().Replace(",", ".") + "," + dLatNew.ToString().Replace(",", ".") + "," + dAltNew.ToString().Replace(",", ".") + "\n";
}
}
}
}
break;
}
break;
case DATA_REQUESTS.REQUEST_AI_PLANE:
case DATA_REQUESTS.REQUEST_AI_HELICOPTER:
case DATA_REQUESTS.REQUEST_AI_BOAT:
case DATA_REQUESTS.REQUEST_AI_GROUND:
lock (lockUserAircraftID)
{
if (bUserAircraftIDSet && (drroTemp.uiObjectID == uiUserAircraftID))
return;
}
switch ((DATA_REQUESTS)data.dwRequestID)
{
case DATA_REQUESTS.REQUEST_AI_PLANE:
processDataRequestResultAlternatingly(data.dwentrynumber, data.dwoutof, ref drrAIPlanes, ref lockDrrAiPlanes, ref drroTemp, gconffixCurrent.bPredictAIAircrafts, gconffixCurrent.bPredictPointsAIAircrafts);
break;
case DATA_REQUESTS.REQUEST_AI_HELICOPTER:
processDataRequestResultAlternatingly(data.dwentrynumber, data.dwoutof, ref drrAIHelicopters, ref lockDrrAiHelicopters, ref drroTemp, gconffixCurrent.bPredictAIHelicopters, gconffixCurrent.bPredictPointsAIHelicopters);
break;
case DATA_REQUESTS.REQUEST_AI_BOAT:
processDataRequestResultAlternatingly(data.dwentrynumber, data.dwoutof, ref drrAIBoats, ref lockDrrAiBoats, ref drroTemp, gconffixCurrent.bPredictAIBoats, gconffixCurrent.bPredictPointsAIBoats);
break;
case DATA_REQUESTS.REQUEST_AI_GROUND:
processDataRequestResultAlternatingly(data.dwentrynumber, data.dwoutof, ref drrAIGround, ref lockDrrAiGround, ref drroTemp, gconffixCurrent.bPredictAIGroundUnits, gconffixCurrent.bPredictPointsAIGroundUnits);
break;
}
break;
default:
#if DEBUG
safeShowBalloonTip(3000, Text, "Received unknown data from FSX!", ToolTipIcon.Warning);
#endif
break;
}
}
Thread thrConnect;
private void globalConnect()
{
lock (lockChConf)
{
if (!gconfchCurrent.bEnabled)
return;
}
notifyIconMain.Icon = icActive;
notifyIconMain.Text = Text + "(Waiting for connection...)";
if (bConnected)
return;
lock (lockKmlUserAircraft)
{
szKmlUserAircraftPath = "";
uiUserAircraftID = 0;
}
if (!timerFSXConnect.Enabled)
timerFSXConnect.Start();
}
private void globalDisconnect()
{
if (bConnected)
{
bConnected = false;
// Stop all query timers
timerQueryUserAircraft.Stop();
timerQueryUserPath.Stop();
timerUserPrediction.Stop();
timerQueryAIAircrafts.Stop();
timerQueryAIHelicopters.Stop();
timerQueryAIBoats.Stop();
timerQueryAIGroundUnits.Stop();
closeConnection();
lock (lockChConf)
{
if (gconfchCurrent.bEnabled)
safeShowBalloonTip(1000, Text, "Disconnected from FSX!", ToolTipIcon.Info);
}
}
lock (lockChConf)
{
if (gconfchCurrent.bEnabled)
{
if (!timerFSXConnect.Enabled)
{
timerFSXConnect.Start();
notifyIconMain.Icon = icActive;
notifyIconMain.Text = Text + "(Waiting for connection...)";
}
}
else
{
if (timerFSXConnect.Enabled)
{
timerFSXConnect.Stop();
thrConnect.Abort();
if (thrConnect.ThreadState != ThreadState.Unstarted)
thrConnect.Join();
closeConnection();
}
notifyIconMain.Icon = icDisabled;
notifyIconMain.Text = Text + "(Disabled)";
}
}
}
#endregion
#region Helper Functions
#region Old Version
//void processDataRequestResultAlternatingly(uint entryNumber, uint entriesCount, ref DataRequestReturn currentRequestStructure, ref object relatedLock, ref StructBasicMovingSceneryObject receivedData, ref String processedData)
//{
// lock (relatedLock)
// {
// if (entryNumber <= currentRequestStructure.uiLastEntryNumber)
// {
// if (currentRequestStructure.uiCurrentDataSet == 1)
// {
// currentRequestStructure.szData2 = "";
// currentRequestStructure.uiCurrentDataSet = 2;
// }
// else
// {
// currentRequestStructure.szData1 = "";
// currentRequestStructure.uiCurrentDataSet = 1;
// }
// }
// currentRequestStructure.uiLastEntryNumber = entryNumber;
// if (currentRequestStructure.uiCurrentDataSet == 1)
// currentRequestStructure.szData1 += processedData;
// else
// currentRequestStructure.szData2 += processedData;
// if (entryNumber == entriesCount)
// {
// if (currentRequestStructure.uiCurrentDataSet == 1)
// {
// currentRequestStructure.szData2 = "";
// currentRequestStructure.uiCurrentDataSet = 2;
// }
// else
// {
// currentRequestStructure.szData1 = "";
// currentRequestStructure.uiCurrentDataSet = 1;
// }
// currentRequestStructure.uiLastEntryNumber = 0;
// }
// }
//}
#endregion
void processDataRequestResultAlternatingly(uint entryNumber, uint entriesCount, ref DataRequestReturn currentRequestStructure, ref object relatedLock, ref DataRequestReturnObject receivedData, bool bCoursePrediction, bool bPredictionPoints)
{
lock (relatedLock)
{
// In case last data request return aborted unnormally and we're dealing with a new result, switch lists
if (entryNumber <= currentRequestStructure.uiLastEntryNumber)
{
if (currentRequestStructure.uiCurrentDataSet == 1)
currentRequestStructure.uiCurrentDataSet = 2;
else
currentRequestStructure.uiCurrentDataSet = 1;
}
List<DataRequestReturnObject> listCurrent = currentRequestStructure.uiCurrentDataSet == 1 ? currentRequestStructure.listFirst : currentRequestStructure.listSecond;
List<DataRequestReturnObject> listOld = currentRequestStructure.uiCurrentDataSet == 1 ? currentRequestStructure.listSecond : currentRequestStructure.listFirst;
// In case we have switched lists, clear new list and resize if necessary
if (currentRequestStructure.bClearOnNextRun)
{
currentRequestStructure.bClearOnNextRun = false;
listCurrent.Clear();
if (listCurrent.Capacity < entriesCount)
listCurrent.Capacity = (int)((double)entriesCount * 1.1);
}
// Calculate course prediction
if (bCoursePrediction)
{
foreach (DataRequestReturnObject drroTemp in listOld)
{
if (drroTemp.uiObjectID == receivedData.uiObjectID)
{
if (drroTemp.bmsoObject.dTime != receivedData.bmsoObject.dTime)
{
if (bPredictionPoints)
receivedData.ppsPredictionPoints = new PathPositionStored[gconffixCurrent.dPredictionTimes.GetLength(0)];
receivedData.szCoursePrediction = receivedData.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + receivedData.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + receivedData.bmsoObject.dAltitude.ToString().Replace(",", ".") + "\n";
for (uint n = 0; n < gconffixCurrent.dPredictionTimes.GetLength(0); n++)
{
PathPosition ppOld, ppCurrent;
double dLongNew = 0.0, dLatNew = 0.0, dAltNew = 0.0;
ppOld.bInitialized = true;
ppOld.dLat = drroTemp.bmsoObject.dLatitude;
ppOld.dLong = drroTemp.bmsoObject.dLongitude;
ppOld.dAlt = drroTemp.bmsoObject.dAltitude;
ppOld.dTime = drroTemp.bmsoObject.dTime;
ppCurrent.bInitialized = true;
ppCurrent.dLat = receivedData.bmsoObject.dLatitude;
ppCurrent.dLong = receivedData.bmsoObject.dLongitude;
ppCurrent.dAlt = receivedData.bmsoObject.dAltitude;
ppCurrent.dTime = receivedData.bmsoObject.dTime;
calcPositionByTime(ref ppOld, ref ppCurrent, gconffixCurrent.dPredictionTimes[n], ref dLatNew, ref dLongNew, ref dAltNew);
receivedData.szCoursePrediction += dLongNew.ToString().Replace(",", ".") + "," + dLatNew.ToString().Replace(",", ".") + "," + dAltNew.ToString().Replace(",", ".") + "\n";
if (bPredictionPoints)
{
PathPositionStored ppsTemp;
ppsTemp.dLat = dLatNew;
ppsTemp.dLong = dLongNew;
ppsTemp.dAlt = dAltNew;
ppsTemp.dTime = gconffixCurrent.dPredictionTimes[n];
receivedData.ppsPredictionPoints[n] = ppsTemp;
}
}
}
else
{
receivedData.szCoursePrediction = drroTemp.szCoursePrediction;
receivedData.ppsPredictionPoints = drroTemp.ppsPredictionPoints;
}
break;
}
}
}
// Set current entry number
currentRequestStructure.uiLastEntryNumber = entryNumber;
// Insert new data into the list
if (currentRequestStructure.uiCurrentDataSet == 1)
currentRequestStructure.listFirst.Add(receivedData);
else
currentRequestStructure.listSecond.Add(receivedData);
// If this is the last entry from the current return, switch lists, so that http server can work with the just completed list
if (entryNumber == entriesCount)
{
if (currentRequestStructure.uiCurrentDataSet == 1)
currentRequestStructure.uiCurrentDataSet = 2;
else
currentRequestStructure.uiCurrentDataSet = 1;
currentRequestStructure.uiLastEntryNumber = 0;
currentRequestStructure.bClearOnNextRun = true;
}
}
}
private List<DataRequestReturnObject> GetCurrentList(ref DataRequestReturn drrnCurrent)
{
if (drrnCurrent.uiCurrentDataSet == 1)
return drrnCurrent.listSecond;
else
return drrnCurrent.listFirst;
}
private void safeShowBalloonTip(int timeout, String tipTitle, String tipText, ToolTipIcon tipIcon)
{
lock (lockChConf)
{
if (!gconfchCurrent.bShowBalloons)
return;
}
notifyIconMain.ShowBalloonTip(timeout, tipTitle, tipText, tipIcon);
}
private void safeShowMainDialog(int iTab)
{
notifyIconMain.ContextMenuStrip = null;
ConfigMirrorToForm();
// Check startup options
if (isAutoStartActivated())
radioButton8.Checked = true;
else if (isFsxStartActivated() && szPathFSX != "")
radioButton9.Checked = true;
else
radioButton10.Checked = true;
if (szPathFSX == "")
radioButton9.Enabled = false;
bRestartRequired = false;
tabControl1.SelectedIndex = iTab;
Show();
}
private void safeHideMainDialog()
{
notifyIconMain.ContextMenuStrip = contextMenuStripNotifyIcon;
Hide();
}
private void clearDrrStructure(ref DataRequestReturn drrToClear)
{
if (drrToClear.listFirst == null)
drrToClear.listFirst = new List<DataRequestReturnObject>();
if (drrToClear.listSecond == null)
drrToClear.listSecond = new List<DataRequestReturnObject>();
drrToClear.listFirst.Clear();
drrToClear.listSecond.Clear();
drrToClear.uiLastEntryNumber = 0;
drrToClear.uiCurrentDataSet = 1;
drrToClear.bClearOnNextRun = true;
}
private void clearPPStructure(ref PathPosition ppToClear)
{
ppToClear.bInitialized = false;
ppToClear.dAlt = ppToClear.dLong = ppToClear.dAlt = 0.0;
}
private bool IsLocalHostIP(IPAddress ipaRequest)
{
lock (lockIPAddressList)
{
if (ipalLocal1 != null)
{
foreach (IPAddress ipaTemp in ipalLocal1)
{
if (ipaTemp.Equals(ipaRequest))
return true;
}
}
if (ipalLocal2 != null)
{
foreach (IPAddress ipaTemp in ipalLocal2)
{
if (ipaTemp.Equals(ipaRequest))
return true;
}
}
}
return false;
}
private bool CompileKMLStartUpFileDynamic(String szIPAddress, ref String szResult)
{
try
{
string szTempKMLFile = File.ReadAllText(szFilePathData + "\\fsxget.template");
szTempKMLFile = szTempKMLFile.Replace("%FSXU%", gconffixCurrent.bQueryUserAircraft ? File.ReadAllText(szFilePathData + "\\fsxget-fsxu.part") : "");
szTempKMLFile = szTempKMLFile.Replace("%FSXP%", gconffixCurrent.bQueryUserPath ? File.ReadAllText(szFilePathData + "\\fsxget-fsxp.part") : "");
szTempKMLFile = szTempKMLFile.Replace("%FSXPRE%", gconffixCurrent.bUserPathPrediction ? File.ReadAllText(szFilePathData + "\\fsxget-fsxpre.part") : "");
szTempKMLFile = szTempKMLFile.Replace("%FSXAIP%", gconffixCurrent.bQueryAIAircrafts ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaip.part") : "");
szTempKMLFile = szTempKMLFile.Replace("%FSXAIH%", gconffixCurrent.bQueryAIHelicopters ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaih.part") : "");
szTempKMLFile = szTempKMLFile.Replace("%FSXAIB%", gconffixCurrent.bQueryAIBoats ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaib.part") : "");
szTempKMLFile = szTempKMLFile.Replace("%FSXAIG%", gconffixCurrent.bQueryAIGroundUnits ? File.ReadAllText(szFilePathData + "\\fsxget-fsxaig.part") : "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXFLIGHTPLAN%", gconffixCurrent.bLoadFlightPlans ? File.ReadAllText(szFilePathData + "\\fsxget-fsxflightplan.part") : "");
szTempKMLFile = szTempKMLFile.Replace("%PATH%", "http://" + szIPAddress + ":" + gconffixCurrent.iServerPort.ToString());
szResult = szTempKMLFile;
return true;
}
catch
{
return false;
}
}
private bool CompileKMLStartUpFileStatic(String szIPAddress, ref String szResult)
{
try
{
string szTempKMLFile = File.ReadAllText(szFilePathData + "\\fsxgets.template");
//szTempKMLFile = szTempKMLFile.Replace("%FSXU%", "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXP%", "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXPRE%", "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXAIP%", "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXAIH%", "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXAIB%", "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXAIG%", "");
//szTempKMLFile = szTempKMLFile.Replace("%FSXFLIGHTPLAN%", gconffixCurrent.bLoadFlightPlans ? File.ReadAllText(szFilePathData + "\\fsxget-fsxflightplan.part") : "");
//szTempKMLFile = szTempKMLFile.Replace("%PATH%", "http://" + szIPAddress + ":" + gconffixCurrent.iServerPort.ToString());
szResult = szTempKMLFile;
return true;
}
catch
{
return false;
}
}
private void UpdateCheckBoxStates()
{
checkBoxQueryAIObjects_CheckedChanged(null, null);
radioButton7_CheckedChanged(null, null);
radioButton6_CheckedChanged(null, null);
radioButton8_CheckedChanged(null, null);
radioButton9_CheckedChanged(null, null);
radioButton10_CheckedChanged(null, null);
}
private void UpdateButtonStates()
{
if (listBoxPathPrediction.SelectedItems.Count == 1)
button2.Enabled = true;
else
button2.Enabled = false;
}
private double ConvertDegToDouble(String szDeg)
{
String szTemp = szDeg;
szTemp = szTemp.Replace("N", "+");
szTemp = szTemp.Replace("S", "-");
szTemp = szTemp.Replace("E", "+");
szTemp = szTemp.Replace("W", "-");
szTemp = szTemp.Replace(" ", "");
szTemp = szTemp.Replace("\"", "");
szTemp = szTemp.Replace("'", "/");
szTemp = szTemp.Replace("°", "/");
char[] szSeperator = { '/' };
String[] szParts = szTemp.Split(szSeperator);
if (szParts.GetLength(0) != 3)
{
throw new System.Exception("Wrong coordinate format!");
}
double d1 = System.Double.Parse(szParts[0], System.Globalization.NumberFormatInfo.InvariantInfo);
int iSign = Math.Sign(d1);
d1 = Math.Abs(d1);
double d2 = System.Double.Parse(szParts[1], System.Globalization.NumberFormatInfo.InvariantInfo);
double d3 = System.Double.Parse(szParts[2], System.Globalization.NumberFormatInfo.InvariantInfo);
return iSign * (d1 + (d2 * 60.0 + d3) / 3600.0);
}
private bool isAutoStartActivated()
{
string szRun = (string)Registry.GetValue(szRegKeyRun, AssemblyTitle, "");
return (szRun.ToLower() == Application.ExecutablePath.ToLower());
}
private bool AutoStartActivate()
{
try
{
Registry.SetValue(szRegKeyRun, AssemblyTitle, Application.ExecutablePath);
}
catch
{
return false;
}
return true;
}
private bool AutoStartDeactivate()
{
try
{
RegistryKey regkTemp = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run", true);
regkTemp.DeleteValue(AssemblyTitle);
}
catch
{
return false;
}
return true;
}
private bool isFsxStartActivated()
{
String szAppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\FSX";
if (File.Exists(szAppDataFolder + "\\EXE.xml"))
{
XmlTextReader xmlrFsxFile = new XmlTextReader(szAppDataFolder + "\\EXE.xml");
XmlDocument xmldSettings = new XmlDocument();
try
{
xmldSettings.Load(xmlrFsxFile);
}
catch
{
xmlrFsxFile.Close();
xmlrFsxFile = null;
return false;
}
xmlrFsxFile.Close();
xmlrFsxFile = null;
try
{
for (XmlNode xmlnTemp = xmldSettings["SimBase.Document"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.Name.ToLower() == "launch.addon")
{
try
{
if (Path.GetFullPath(xmlnTemp["Path"].InnerText).ToLower() == (Path.GetFullPath(szAppPath) + "\\starter.exe").ToLower())
return true;
}
catch { }
}
}
return false;
}
catch
{
return false;
}
}
else
return false;
}
private bool FsxStartActivate()
{
String szAppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\FSX";
if (File.Exists(szAppDataFolder + "\\EXE.xml"))
{
bool bLoadError = false;
XmlTextReader xmlrFsxFile = new XmlTextReader(szAppDataFolder + "\\EXE.xml");
XmlDocument xmldSettings = new XmlDocument();
try
{
xmldSettings.Load(xmlrFsxFile);
}
catch
{
bLoadError = true;
}
xmlrFsxFile.Close();
xmlrFsxFile = null;
// TODO: One could improve this function not just replacing the document if ["SimBase.Document"] doesn't exist,
// but just find and use the document's root element whatever it may be called. This would increase compatibility
// with future FS version. (Same should be done for other functions dealing with this document)
if (bLoadError || xmldSettings["SimBase.Document"] == null)
{
try
{
File.Delete(szAppDataFolder + "\\EXE.xml");
return FsxStartActivate();
}
catch
{
return false;
}
}
else
{
if (xmldSettings["SimBase.Document"]["Disabled"] == null)
{
XmlNode nodeTemp = xmldSettings.CreateElement("Disabled");
nodeTemp.InnerText = "False";
xmldSettings["SimBase.Document"].AppendChild(nodeTemp);
}
else if (xmldSettings["SimBase.Document"]["Disabled"].InnerText.ToLower() == "true")
xmldSettings["SimBase.Document"]["Disabled"].InnerText = "False";
xmlrFsxFile = new XmlTextReader(szAppPath + "\\data\\EXE.xml");
XmlDocument xmldTemplate = new XmlDocument();
xmldTemplate.Load(xmlrFsxFile);
xmlrFsxFile.Close();
xmlrFsxFile = null;
XmlNode nodeFsxget = xmldTemplate["SimBase.Document"]["Launch.Addon"];
XmlNode nodeTemp2 = xmldSettings.CreateElement(nodeFsxget.Name);
nodeTemp2.InnerXml = nodeFsxget.InnerXml.Replace("%PATH%", Path.GetFullPath(szAppPath) + "\\starter.exe");
xmldSettings["SimBase.Document"].AppendChild(nodeTemp2);
try
{
File.Delete(szAppDataFolder + "\\EXE.xml");
xmldSettings.Save(szAppDataFolder + "\\EXE.xml");
return true;
}
catch
{
return false;
}
}
}
else
{
try
{
StreamWriter swFsxFile = File.CreateText(szAppDataFolder + "\\EXE.xml");
StreamReader srFsxFileTemplate = File.OpenText(szAppPath + "\\data\\EXE.xml");
swFsxFile.Write(srFsxFileTemplate.ReadToEnd().Replace("%PATH%", Path.GetFullPath(szAppPath) + "\\starter.exe"));
swFsxFile.Flush();
swFsxFile.Close();
swFsxFile.Dispose();
srFsxFileTemplate.Close();
srFsxFileTemplate.Dispose();
return true;
}
catch
{
return false;
}
}
}
private bool FsxStartDeactivate()
{
String szAppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\FSX";
if (File.Exists(szAppDataFolder + "\\EXE.xml"))
{
XmlTextReader xmlrFsxFile = new XmlTextReader(szAppDataFolder + "\\EXE.xml");
XmlDocument xmldSettings = new XmlDocument();
xmldSettings.Load(xmlrFsxFile);
xmlrFsxFile.Close();
xmlrFsxFile = null;
try
{
bool bChanges = false;
for (XmlNode xmlnTemp = xmldSettings["SimBase.Document"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.Name.ToLower() == "launch.addon")
{
if (xmlnTemp["Path"] != null)
{
if (Path.GetFullPath(xmlnTemp["Path"].InnerText).ToLower() == (Path.GetFullPath(szAppPath) + "\\starter.exe").ToLower())
{
xmldSettings["SimBase.Document"].RemoveChild(xmlnTemp);
bChanges = true;
}
}
}
}
if (bChanges)
{
try
{
File.Delete(szAppDataFolder + "\\EXE.xml");
xmldSettings.Save(szAppDataFolder + "\\EXE.xml");
}
catch
{
return false;
}
}
return true;
}
catch
{
return true;
}
}
else
return true;
}
private double getValueInUnit(double dValueInMeters, UnitType Unit)
{
switch (Unit)
{
case UnitType.METERS:
return dValueInMeters;
case UnitType.FEET:
return dValueInMeters * 3.2808399;
default:
throw new Exception("Unknown unit type");
}
}
private double getValueInCurrentUnit(double dValueInMeters)
{
return getValueInUnit(dValueInMeters, gconffixCurrent.utUnits);
}
private String getCurrentUnitNameShort()
{
switch (gconffixCurrent.utUnits)
{
case UnitType.METERS:
return "m";
case UnitType.FEET:
return "ft";
default:
return "--";
}
}
private String getCurrentUnitName()
{
switch (gconffixCurrent.utUnits)
{
case UnitType.METERS:
return "Meters";
case UnitType.FEET:
return "Feet";
default:
return "Unknown Unit";
}
}
private void RestartApp()
{
Program.bRestart = true;
bClose = true;
Close();
}
protected static byte[] BitmapToPngBytes(Bitmap bmp)
{
byte[] bufferPng = null;
if (bmp != null)
{
byte[] buffer = new byte[1024 + bmp.Height * bmp.Width * 4];
MemoryStream s = new MemoryStream(buffer);
bmp.Save(s, System.Drawing.Imaging.ImageFormat.Png);
int nSize = (int)s.Position;
s.Close();
bufferPng = new byte[nSize];
for (int i = 0; i < nSize; i++)
bufferPng[i] = buffer[i];
}
return bufferPng;
}
#endregion
#region Calucaltion
private void calcPositionByTime(ref PathPosition ppOld, ref PathPosition ppNew, double dSeconds, ref double dResultLat, ref double dResultLong, ref double dResultAlt)
{
double dTimeElapsed = ppNew.dTime - ppOld.dTime;
double dScale = dSeconds / dTimeElapsed;
dResultLat = ppNew.dLat + dScale * (ppNew.dLat - ppOld.dLat);
dResultLong = ppNew.dLong + dScale * (ppNew.dLong - ppOld.dLong);
dResultAlt = ppNew.dAlt + dScale * (ppNew.dAlt - ppOld.dAlt);
}
#region Old Calculation
//private void calcPositionByTime(double dLong, double dLat, double dAlt, double dSpeedX, double dSpeedY, double dSpeedZ, double dSeconds, ref double dResultLat, ref double dResultLong, ref double dResultAlt)
//{
// const double dRadEarth = 6371000.8;
// dResultLat = dLat + dSpeedZ * dSeconds / 1852.0;
// dResultAlt = dAlt + dSpeedY * dSeconds;
// double dLatMiddle = dLat + (dSpeedZ * dSeconds / 1852.0 / 2.0);
// dResultLong = dLong + (dSpeedX * dSeconds / (2.0 * Math.PI * dRadEarth / 360.0 * Math.Cos(dLatMiddle * Math.PI / 180.0)));
// //double dNewPosX = dSpeedX * dSeconds;
// //double dNewPosY = dSpeedY * dSeconds;
// //double dNewPosZ = dSpeedZ * dSeconds;
// //double dCosAngle = (dNewPosY * 1.0 + dNewPosZ * 0.0) / (Math.Sqrt(Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0)) * Math.Sqrt(Math.Pow(0.0, 2.0) + Math.Pow(1.0, 2.0)));
// //dResultLat = dLat + Math.Acos(dCosAngle / 180.0 * Math.PI);
// //// East-West-Position
// //dCosAngle = (dNewPosX * 1.0 + dNewPosY * 0.0) / (Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0)) * Math.Sqrt(Math.Pow(1.0, 2.0) + Math.Pow(0.0, 2.0)));
// //dResultLong = dLong + Math.Acos(dCosAngle / 180.0 * Math.PI);
// //// Altitude
// //dResultAlt = dAlt + Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0));
// //const double dRadEarth = 6371000.8;
// ////x' = cos(theta)*x - sin(theta)*y
// ////y' = sin(theta)*x + cos(theta)*y
// //// Calculate North-South-Position
// //double dTempX = dAlt + dRadEarth;
// //double dTempY = 0.0;
// //double dPosY = Math.Cos(dLat) * dTempX - Math.Sin(dLat) * dTempY;
// //double dPosZ = Math.Sin(dLat) * dTempX - Math.Cos(dLat) * dTempY;
// //// Calculate East-West-Position
// //dTempX = dAlt + dRadEarth;
// //dTempY = 0;
// //double dPosX = Math.Cos(dLong) * dTempX - Math.Sin(dLong) * dTempY;
// ////dPosZ = Math.Sin(dLat) * dTempX - Math.Cos(dLat) * dTempY;
// //// Normalize
// //double dLength = Math.Sqrt(Math.Pow(dPosX, 2.0) + Math.Pow(dPosY, 2.0) + Math.Pow(dPosZ, 2.0));
// //dPosX = dPosX / dLength * (dAlt + dRadEarth);
// //dPosY = dPosY / dLength * (dAlt + dRadEarth);
// //dPosZ = dPosZ / dLength * (dAlt + dRadEarth);
// //double dTest = Math.Sqrt(Math.Pow(dPosX, 2.0) + Math.Pow(dPosY, 2.0) + Math.Pow(dPosZ, 2.0)) - dRadEarth;
// //// Calculate position after given time
// //double dNewPosX = dPosX + dSpeedX * dSeconds;
// //double dNewPosY = dPosY + dSpeedY * dSeconds;
// //double dNewPosZ = dPosZ + dSpeedZ * dSeconds;
// //// Now again translate into lat-long-coordinates
// //// North-South-Position
// //double dCosAngle = (dNewPosY * dPosY + dNewPosZ * dPosZ) / (Math.Sqrt(Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0)) * Math.Sqrt(Math.Pow(dPosY, 2.0) + Math.Pow(dPosZ, 2.0)));
// //dResultLat = dLat + Math.Acos(dCosAngle / 180.0 * Math.PI);
// //// East-West-Position
// //dCosAngle = (dNewPosX * dPosX + dNewPosY * dPosY) / (Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0)) * Math.Sqrt(Math.Pow(dPosX, 2.0) + Math.Pow(dPosY, 2.0)));
// //dResultLong = dLong + Math.Acos(dCosAngle / 180.0 * Math.PI);
// //// Altitude
// //dResultAlt = Math.Sqrt(Math.Pow(dNewPosX, 2.0) + Math.Pow(dNewPosY, 2.0) + Math.Pow(dNewPosZ, 2.0)) - dRadEarth;
//}
#endregion
#endregion
#region Server
public void ListenerCallback(IAsyncResult result)
{
lock (lockListenerControl)
{
HttpListener listener = (HttpListener)result.AsyncState;
if (!listener.IsListening)
return;
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
// This code using the objects IsLocal property doesn't work for some reason ...
//if (gconffixCurrent.uiServerAccessLevel == 0 && !request.IsLocal)
//{
// response.Abort();
// return;
//}
// ... so I'm using my own code.
if (gconffixCurrent.uiServerAccessLevel == 0 && !IsLocalHostIP(request.RemoteEndPoint.Address))
{
response.Abort();
return;
}
byte[] buffer = System.Text.Encoding.UTF8.GetBytes("");
String szHeader = "";
bool bContentSet = false;
if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/scenery/air/"))
{
String szTemp = request.Url.PathAndQuery.Substring(17);
if (szTemp.Length >= 4)
{
// Cut the .png suffix from the url
szTemp = szTemp.Substring(0, szTemp.Length - 4);
foreach (ObjectImage aimgCurrent in listImgUnitsAir)
{
String szTemp2 = HttpUtility.UrlDecode(szTemp);
if (aimgCurrent.szTitle.ToLower() == HttpUtility.UrlDecode(szTemp).ToLower())
{
buffer = aimgCurrent.bData;
szHeader = "image/png";
bContentSet = true;
break;
}
}
if (!bContentSet)
{
buffer = imgNoImage;
szHeader = "image/png";
bContentSet = true;
}
}
}
else if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/scenery/water/"))
{
String szTemp = request.Url.PathAndQuery.Substring(19);
if (szTemp.Length >= 4)
{
// Cut the .png suffix from the url
szTemp = szTemp.Substring(0, szTemp.Length - 4);
foreach (ObjectImage aimgCurrent in listImgUnitsWater)
{
String szTemp2 = HttpUtility.UrlDecode(szTemp);
if (aimgCurrent.szTitle.ToLower() == HttpUtility.UrlDecode(szTemp).ToLower())
{
buffer = aimgCurrent.bData;
szHeader = "image/png";
bContentSet = true;
break;
}
}
if (!bContentSet)
{
buffer = imgNoImage;
szHeader = "image/png";
bContentSet = true;
}
}
}
else if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/scenery/ground/"))
{
String szTemp = request.Url.PathAndQuery.Substring(20);
if (szTemp.Length >= 4)
{
// Cut the .png suffix from the url
szTemp = szTemp.Substring(0, szTemp.Length - 4);
foreach (ObjectImage aimgCurrent in listImgUnitsGround)
{
String szTemp2 = HttpUtility.UrlDecode(szTemp);
if (aimgCurrent.szTitle.ToLower() == HttpUtility.UrlDecode(szTemp).ToLower())
{
buffer = aimgCurrent.bData;
szHeader = "image/png";
bContentSet = true;
break;
}
}
if (!bContentSet)
{
buffer = imgNoImage;
szHeader = "image/png";
bContentSet = true;
}
}
}
else if (request.Url.PathAndQuery.ToLower().StartsWith("/gfx/ge/icons/"))
{
String szTemp = request.Url.PathAndQuery.Substring(14);
if (szTemp.Length >= 4)
{
// Cut the .png suffix from the url
szTemp = szTemp.Substring(0, szTemp.Length - 4);
buffer = null;
foreach (ObjectImage oimgTemp in listIconsGE)
{
if (oimgTemp.szTitle.ToLower() == szTemp.ToLower())
{
szHeader = "image/png";
buffer = oimgTemp.bData;
bContentSet = true;
break;
}
}
if (!bContentSet)
{
buffer = imgNoImage;
szHeader = "image/png";
bContentSet = true;
}
}
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxu.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_USER_AIRCRAFT, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEUserAircraft, request.UserHostName));
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxp.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_USER_PATH, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEUserPath, request.UserHostName));
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxpre.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_USER_PREDICTION, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEUserPrediction, request.UserHostName));
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxaip.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_PLANE, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEAIAircrafts, request.UserHostName));
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxaih.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_HELICOPTER, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEAIHelicopters, request.UserHostName));
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxaib.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_BOAT, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEAIBoats, request.UserHostName));
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxaig.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_AI_GROUND, KML_ACCESS_MODES.MODE_SERVER, true, (uint)gconffixCurrent.iUpdateGEAIGroundUnits, request.UserHostName));
}
else if (request.Url.PathAndQuery.ToLower() == "/fsxflightplans.kml")
{
bContentSet = true;
szHeader = "application/vnd.google-earth.kml+xml";
buffer = System.Text.Encoding.UTF8.GetBytes(KmlGenFile(KML_FILES.REQUEST_FLIGHT_PLANS, KML_ACCESS_MODES.MODE_SERVER, false, 0, request.UserHostName));
}
else if (request.Url.AbsolutePath.ToLower() == "/gfx/ge/label.png")
{
bContentSet = true;
szHeader = "image/png";
buffer = KmlGenAtcLabel(request.QueryString["code"], request.QueryString["fl"], request.QueryString["aircraft"], request.QueryString["speed"], request.QueryString["vspeed"]);
}
else
bContentSet = false;
if (bContentSet)
{
response.AddHeader("Content-type", szHeader);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
}
else
{
response.StatusCode = 404;
response.Close();
}
listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
}
}
private String KmlGenFile(KML_FILES kmlfWanted, KML_ACCESS_MODES AccessMode, bool bExpires, uint uiSeconds, String szSever)
{
String szTemp = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><kml xmlns=\"http://earth.google.com/kml/2.1\">" +
KmlGetExpireString(bExpires, uiSeconds) +
"<Document>";
switch (kmlfWanted)
{
case KML_FILES.REQUEST_USER_AIRCRAFT:
szTemp += KmlGenUserPosition(AccessMode, szSever);
break;
case KML_FILES.REQUEST_USER_PATH:
szTemp += KmlGenUserPath(AccessMode, szSever);
break;
case KML_FILES.REQUEST_USER_PREDICTION:
szTemp += KmlGenUserPrediction(AccessMode, szSever);
break;
case KML_FILES.REQUEST_AI_PLANE:
szTemp += KmlGenAIAircraft(AccessMode, szSever);
break;
case KML_FILES.REQUEST_AI_HELICOPTER:
szTemp += KmlGenAIHelicopter(AccessMode, szSever);
break;
case KML_FILES.REQUEST_AI_BOAT:
szTemp += KmlGenAIBoat(AccessMode, szSever);
break;
case KML_FILES.REQUEST_AI_GROUND:
szTemp += KmlGenAIGroundUnit(AccessMode, szSever);
break;
//case KML_FILES.REQUEST_FLIGHT_PLANS:
// szTemp += KmlGenFlightPlans(AccessMode, szSever);
// break;
default:
break;
}
szTemp += "</Document></kml>";
return szTemp;
}
private String KmlGetExpireString(bool bExpires, uint uiSeconds)
{
if (!bExpires)
return "";
DateTime date = DateTime.Now;
date = date.AddSeconds(uiSeconds);
date = date.ToUniversalTime();
return "<NetworkLinkControl><expires>" + date.ToString("yyyy") + "-" + date.ToString("MM") + "-" + date.ToString("dd") + "T" + date.ToString("HH") + ":" + date.ToString("mm") + ":" + date.ToString("ss") + "Z" + "</expires></NetworkLinkControl>";
}
private String KmlGetImageLink(KML_ACCESS_MODES AccessMode, KML_IMAGE_TYPES ImageType, String szTitle, String szServer)
{
if (AccessMode == KML_ACCESS_MODES.MODE_SERVER)
{
String szPrefix = "";
switch (ImageType)
{
case KML_IMAGE_TYPES.AIRCRAFT:
szPrefix = "/gfx/scenery/air/";
break;
case KML_IMAGE_TYPES.WATER:
szPrefix = "/gfx/scenery/water/";
break;
case KML_IMAGE_TYPES.GROUND:
szPrefix = "/gfx/scenery/ground/";
break;
}
return "http://" + szServer + szPrefix + szTitle + ".png";
}
else
{
List<ObjectImage> listTemp;
switch (ImageType)
{
case KML_IMAGE_TYPES.AIRCRAFT:
listTemp = listImgUnitsAir;
break;
case KML_IMAGE_TYPES.WATER:
listTemp = listImgUnitsWater;
break;
case KML_IMAGE_TYPES.GROUND:
listTemp = listImgUnitsGround;
break;
default:
return "";
}
foreach (ObjectImage oimgTemp in listTemp)
{
if (oimgTemp.szTitle.ToLower() == szTitle.ToLower())
{
if (AccessMode == KML_ACCESS_MODES.MODE_FILE_LOCAL)
return szFilePathPub + oimgTemp.szPath;
else if (AccessMode == KML_ACCESS_MODES.MODE_FILE_USERDEFINED)
return gconffixCurrent.szUserdefinedPath + oimgTemp.szPath;
}
}
return "";
}
}
private String KmlGetIconLink(KML_ACCESS_MODES AccessMode, KML_ICON_TYPES IconType, String szServer)
{
String szIcon = "";
switch (IconType)
{
case KML_ICON_TYPES.USER_AIRCRAFT_POSITION:
szIcon = "fsxu";
break;
case KML_ICON_TYPES.USER_PREDICTION_POINT:
szIcon = "fsxpm";
break;
case KML_ICON_TYPES.AI_AIRCRAFT:
szIcon = "fsxaip";
break;
case KML_ICON_TYPES.AI_HELICOPTER:
szIcon = "fsxaih";
break;
case KML_ICON_TYPES.AI_BOAT:
szIcon = "fsxaib";
break;
case KML_ICON_TYPES.AI_GROUND_UNIT:
szIcon = "fsxaig";
break;
case KML_ICON_TYPES.AI_AIRCRAFT_PREDICTION_POINT:
szIcon = "fsxaippp";
break;
case KML_ICON_TYPES.AI_HELICOPTER_PREDICTION_POINT:
szIcon = "fsxaihpp";
break;
case KML_ICON_TYPES.AI_BOAT_PREDICTION_POINT:
szIcon = "fsxaibpp";
break;
case KML_ICON_TYPES.AI_GROUND_PREDICTION_POINT:
szIcon = "fsxaigpp";
break;
case KML_ICON_TYPES.PLAN_INTER:
szIcon = "plan-inter";
break;
case KML_ICON_TYPES.PLAN_NDB:
szIcon = "plan-ndb";
break;
case KML_ICON_TYPES.PLAN_PORT:
szIcon = "plan-port";
break;
case KML_ICON_TYPES.PLAN_USER:
szIcon = "plan-user";
break;
case KML_ICON_TYPES.PLAN_VOR:
szIcon = "plan-vor";
break;
case KML_ICON_TYPES.ATC_LABEL:
return "http://" + szServer + "/gfx/ge/label.png";
}
if (AccessMode == KML_ACCESS_MODES.MODE_SERVER)
{
return "http://" + szServer + "/gfx/ge/icons/" + szIcon + ".png";
}
else
{
foreach (ObjectImage oimgTemp in listIconsGE)
{
if (oimgTemp.szTitle.ToLower() == szIcon.ToLower())
{
if (AccessMode == KML_ACCESS_MODES.MODE_FILE_LOCAL)
return szFilePathPub + oimgTemp.szPath;
else if (AccessMode == KML_ACCESS_MODES.MODE_FILE_USERDEFINED)
return gconffixCurrent.szUserdefinedPath + oimgTemp.szPath;
}
}
return "";
}
}
private String KmlGenETAPoints(ref PathPositionStored[] ppsCurrent, bool bGenerate, KML_ACCESS_MODES AccessMode, KML_ICON_TYPES Icon, String szServer)
{
if (ppsCurrent == null)
return "";
if (bGenerate)
{
String szTemp = "<Folder><name>ETA Points</name>";
for (uint n = 0; n < ppsCurrent.GetLength(0); n++)
szTemp += "<Placemark>" +
"<name>ETA " + ((ppsCurrent[n].dTime < 60.0) ? (((int)ppsCurrent[n].dTime).ToString() + " sec") : (ppsCurrent[n].dTime / 60.0 + " min")) + "</name><visibility>1</visibility><open>0</open>" +
"<description><![CDATA[Esitmated Position]]></description>" +
"<Style>" +
"<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, Icon, szServer) + "</href></Icon><scale>0.2</scale></IconStyle>" +
"<LabelStyle><scale>0.4</scale></LabelStyle>" +
"</Style>" +
"<Point><altitudeMode>absolute</altitudeMode><coordinates>" + ppsCurrent[n].dLong.ToString().Replace(",", ".") + "," + ppsCurrent[n].dLat.ToString().Replace(",", ".") + "," + ppsCurrent[n].dAlt.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
return szTemp + "</Folder>";
}
else
return "";
}
private String KmlGenUserPosition(KML_ACCESS_MODES AccessMode, String szServer)
{
lock (lockKmlUserAircraft)
{
return "<Placemark>" +
"<name>User Aircraft Position</name><visibility>1</visibility><open>0</open>" +
"<description><![CDATA[Microsoft Flight Simulator X - User Aircraft<br> <br>" +
"<b>Title:</b> " + suadCurrent.szTitle + "<br> <br>" +
"<b>Type:</b> " + suadCurrent.szATCType + "<br>" +
"<b>Model:</b> " + suadCurrent.szATCModel + "<br> <br>" +
"<b>Identification:</b> " + suadCurrent.szATCID + "<br> <br>" +
"<b>Flight Number:</b> " + suadCurrent.szATCFlightNumber + "<br>" +
"<b>Airline:</b> " + suadCurrent.szATCAirline + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(suadCurrent.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <br>" +
"<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, suadCurrent.szTitle, szServer) + "\"></center>]]></description>" +
"<Snippet>" + suadCurrent.szATCType + " " + suadCurrent.szATCModel + " (" + suadCurrent.szTitle + "), " + suadCurrent.szATCID + "\nAltitude: " + ((int)getValueInCurrentUnit(suadCurrent.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" +
"<Style>" +
"<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.USER_AIRCRAFT_POSITION, szServer) + "</href></Icon><scale>0.8</scale></IconStyle>" +
"<LabelStyle><scale>1.0</scale></LabelStyle>" +
"</Style>" +
"<Point><altitudeMode>absolute</altitudeMode><coordinates>" + suadCurrent.dLongitude.ToString().Replace(",", ".") + "," + suadCurrent.dLatitude.ToString().Replace(",", ".") + "," + suadCurrent.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
}
}
private String KmlGenUserPath(KML_ACCESS_MODES AccessMode, String szServer)
{
lock (lockKmlUserPath)
{
return "<Placemark><name>User Aircraft Path</name><description>Path of the user aircraft since tracking started.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9fffffff</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + szKmlUserAircraftPath + "</coordinates></LineString></Placemark>";
}
}
private String KmlGenUserPrediction(KML_ACCESS_MODES AccessMode, String szServer)
{
String szTemp = "";
lock (lockKmlUserPrediction)
{
szTemp = "<Placemark><name>User Aircraft Path Prediction</name><description>Path prediction of the user aircraft.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9f00ffff</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + szKmlUserPrediction + "</coordinates></LineString></Placemark>" +
"<Folder><name>ETA Points</name>";
foreach (PathPositionStored ppsTemp in listKmlPredictionPoints)
{
szTemp += "<Placemark>" +
"<name>ETA " + ((ppsTemp.dTime < 60.0) ? (((int)ppsTemp.dTime).ToString() + " sec") : (ppsTemp.dTime / 60.0 + " min")) + "</name><visibility>1</visibility><open>0</open>" +
"<description><![CDATA[Esitmated Position]]></description>" +
"<Style>" +
"<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.USER_PREDICTION_POINT, szServer) + "</href></Icon><scale>0.2</scale></IconStyle>" +
"<LabelStyle><scale>0.4</scale></LabelStyle>" +
"</Style>" +
"<Point><altitudeMode>absolute</altitudeMode><coordinates>" + ppsTemp.dLong.ToString().Replace(",", ".") + "," + ppsTemp.dLat.ToString().Replace(",", ".") + "," + ppsTemp.dAlt.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
}
}
return szTemp + "</Folder>";
}
private String KmlGenAIAircraft(KML_ACCESS_MODES AccessMode, String szServer)
{
String szTemp = "<Folder><name>Aircraft Positions</name>";
lock (lockDrrAiPlanes)
{
List<DataRequestReturnObject> listTemp = GetCurrentList(ref drrAIPlanes);
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
//szTemp += "<Placemark>" +
// "<name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><visibility>1</visibility><open>0</open>" +
// "<description><![CDATA[Microsoft Flight Simulator X - AI Plane<br> <br>" +
// "<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
// "<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" +
// "<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br> <br>" +
// "<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br> <br>" +
// "<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" +
// "<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br> <br>" +
// "<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <br>" +
// "<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" +
// "<Snippet>" + bmsoTemp.bmsoObject.szTitle + "\nAltitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" +
// "<Style>" +
// "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_AIRCRAFT, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" +
// "<LabelStyle><scale>0.6</scale></LabelStyle>" +
// "</Style>" +
// "<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
int FL = (int)Math.Round(getValueInUnit(bmsoTemp.bmsoObject.dAltitude, UnitType.FEET) / 100.0, 0);
int FLRound = FL - (FL % 10);
szTemp += "<Placemark>" +
"<name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><visibility>1</visibility><open>0</open>" +
"<description><![CDATA[Microsoft Flight Simulator X - AI Plane<br> <br>" +
"<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
"<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" +
"<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br> <br>" +
"<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br> <br>" +
"<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" +
"<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <br>" +
"<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" +
"<Snippet>" + bmsoTemp.bmsoObject.szTitle + "\nAltitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" +
"<Style>" +
"<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.ATC_LABEL, szServer) + "?code=" + bmsoTemp.bmsoObject.szATCID + "&fl=FL" + FLRound.ToString() + "&speed=" + Math.Round(bmsoTemp.bmsoObject.dSpeed, 0).ToString() + " kn&vspeed=" + (bmsoTemp.bmsoObject.dVSpeed > 0.0 ? "%2F%5C" : (bmsoTemp.bmsoObject.dVSpeed == 0.0 ? "-" : "%5C%2F")) + "&aircraft=" + bmsoTemp.bmsoObject.szATCModel + "</href></Icon><scale>2.5</scale> <hotSpot x=\"30\" y=\"50\" xunits=\"pixels\" yunits=\"pixels\"/></IconStyle>" +
"<LabelStyle><scale>0.6</scale></LabelStyle>" +
"</Style>" +
"<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
}
szTemp += "</Folder>";
if (gconffixCurrent.bPredictAIAircrafts)
{
szTemp += "<Folder><name>Aircraft Courses</name>";
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
if (bmsoTemp.szCoursePrediction == "")
continue;
szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><description>Course prediction of the aircraft.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9fd20091</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>";
PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints;
szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.bPredictPointsAIAircrafts, AccessMode, KML_ICON_TYPES.AI_AIRCRAFT_PREDICTION_POINT, szServer);
}
szTemp += "</Folder>";
}
}
return szTemp;
}
private String KmlGenAIHelicopter(KML_ACCESS_MODES AccessMode, String szServer)
{
String szTemp = "<Folder><name>Helicopter Positions</name>";
lock (lockDrrAiHelicopters)
{
List<DataRequestReturnObject> listTemp = GetCurrentList(ref drrAIHelicopters);
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
szTemp += "<Placemark>" +
"<name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><visibility>1</visibility><open>0</open>" +
"<description><![CDATA[Microsoft Flight Simulator X - AI Helicopter<br> <br>" +
"<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
"<b>Type:</b> " + bmsoTemp.bmsoObject.szATCType + "<br>" +
"<b>Model:</b> " + bmsoTemp.bmsoObject.szATCModel + "<br> <br>" +
"<b>Identification:</b> " + bmsoTemp.bmsoObject.szATCID + "<br> <br>" +
"<b>Flight Number:</b> " + bmsoTemp.bmsoObject.szATCFlightNumber + "<br>" +
"<b>Airline:</b> " + bmsoTemp.bmsoObject.szATCAirline + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <br>" +
"<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.AIRCRAFT, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" +
"<Snippet>" + bmsoTemp.bmsoObject.szTitle + "\nAltitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" +
"<Style>" +
"<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_HELICOPTER, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" +
"<LabelStyle><scale>0.6</scale></LabelStyle>" +
"</Style>" +
"<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
}
szTemp += "</Folder>";
if (gconffixCurrent.bPredictAIHelicopters)
{
szTemp += "<Folder><name>Helicopter Courses</name>";
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
if (bmsoTemp.szCoursePrediction == "")
continue;
szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szATCType + " " + bmsoTemp.bmsoObject.szATCModel + " (" + bmsoTemp.bmsoObject.szATCID + ")</name><description>Course prediction of the helicopter.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9fd20091</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>";
PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints;
szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.bPredictPointsAIHelicopters, AccessMode, KML_ICON_TYPES.AI_HELICOPTER_PREDICTION_POINT, szServer);
}
szTemp += "</Folder>";
}
}
return szTemp;
}
private String KmlGenAIBoat(KML_ACCESS_MODES AccessMode, String szServer)
{
String szTemp = "<Folder><name>Boat Positions</name>";
lock (lockDrrAiBoats)
{
List<DataRequestReturnObject> listTemp = GetCurrentList(ref drrAIBoats);
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
szTemp += "<Placemark>" +
"<name>" + bmsoTemp.bmsoObject.szTitle + "</name><visibility>1</visibility><open>0</open>" +
"<description><![CDATA[Microsoft Flight Simulator X - AI Boat<br> <br>" +
"<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <br>" +
"<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.WATER, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" +
"<Snippet>Altitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" +
"<Style>" +
"<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_BOAT, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" +
"<LabelStyle><scale>0.6</scale></LabelStyle>" +
"</Style>" +
"<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
}
szTemp += "</Folder>";
if (gconffixCurrent.bPredictAIBoats)
{
szTemp += "<Folder><name>Boat Courses</name>";
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
if (bmsoTemp.szCoursePrediction == "")
continue;
szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szTitle + "</name><description>Course prediction of the boat.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9f00b545</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>";
PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints;
szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.bPredictPointsAIBoats, AccessMode, KML_ICON_TYPES.AI_BOAT_PREDICTION_POINT, szServer);
}
szTemp += "</Folder>";
}
}
return szTemp;
}
private String KmlGenAIGroundUnit(KML_ACCESS_MODES AccessMode, String szServer)
{
String szTemp = "<Folder><name>Ground Vehicle Positions</name>";
lock (lockDrrAiGround)
{
List<DataRequestReturnObject> listTemp = GetCurrentList(ref drrAIGround);
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
szTemp += "<Placemark>" +
"<name>" + bmsoTemp.bmsoObject.szTitle + "</name><visibility>1</visibility><open>0</open>" +
"<description><![CDATA[Microsoft Flight Simulator X - AI Vehicle<br> <br>" +
"<b>Title:</b> " + bmsoTemp.bmsoObject.szTitle + "<br> <br>" +
"<b>Altitude:</b> " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "<br> <br>" +
"<center><img src=\"" + KmlGetImageLink(AccessMode, KML_IMAGE_TYPES.GROUND, bmsoTemp.bmsoObject.szTitle, szServer) + "\"></center>]]></description>" +
"<Snippet>Altitude: " + ((int)getValueInCurrentUnit(bmsoTemp.bmsoObject.dAltitude)).ToString().Replace(",", ".") + " " + getCurrentUnitNameShort() + "</Snippet>" +
"<Style>" +
"<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, KML_ICON_TYPES.AI_GROUND_UNIT, szServer) + "</href></Icon><scale>0.6</scale></IconStyle>" +
"<LabelStyle><scale>0.6</scale></LabelStyle>" +
"</Style>" +
"<Point><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.bmsoObject.dLongitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dLatitude.ToString().Replace(",", ".") + "," + bmsoTemp.bmsoObject.dAltitude.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
}
szTemp += "</Folder>";
if (gconffixCurrent.bPredictAIGroundUnits)
{
szTemp += "<Folder><name>Ground Vehicle Courses</name>";
foreach (DataRequestReturnObject bmsoTemp in listTemp)
{
if (bmsoTemp.szCoursePrediction == "")
continue;
szTemp += "<Placemark><name>" + bmsoTemp.bmsoObject.szTitle + "</name><description>Course prediction of the ground vehicle.</description><visibility>1</visibility><open>0</open><Style><LineStyle><color>9f00b545</color><width>2</width></LineStyle></Style><LineString><altitudeMode>absolute</altitudeMode><coordinates>" + bmsoTemp.szCoursePrediction + "</coordinates></LineString></Placemark>";
PathPositionStored[] ppsTemp = bmsoTemp.ppsPredictionPoints;
szTemp += KmlGenETAPoints(ref ppsTemp, gconffixCurrent.bPredictPointsAIGroundUnits, AccessMode, KML_ICON_TYPES.AI_GROUND_PREDICTION_POINT, szServer);
}
szTemp += "</Folder>";
}
}
return szTemp;
}
private byte[] KmlGenAtcLabel(String CallSign, String FL, String Aircraft, String Speed, String VerticalSpeed)
{
Bitmap bmp = new Bitmap(imgAtcLabel);
Graphics g = Graphics.FromImage(bmp);
Pen pen = new Pen(Color.FromArgb(81, 255, 147));
Brush brush = new SolidBrush(Color.FromArgb(81, 255, 147));
Font font = new Font("Courier New", 10, FontStyle.Bold);
Font font_small = new Font("Courier New", 6, FontStyle.Bold);
float fX = 72;
float fY = 13;
g.DrawString(CallSign, font, brush, new PointF(fX, fY));
fY += g.MeasureString(CallSign, font).Height;
g.DrawString(FL + " " + VerticalSpeed, font, brush, new PointF(fX, fY));
fY += g.MeasureString(FL + " " + VerticalSpeed, font).Height;
g.DrawString(Aircraft, font, brush, new PointF(fX, fY));
return BitmapToPngBytes(bmp);
}
//private String KmlGenFlightPlans(KML_ACCESS_MODES AccessMode, String szServer)
//{
// String szTemp = "";
// lock (lockFlightPlanList)
// {
// foreach (FlightPlan fpTemp in listFlightPlans)
// {
// XmlDocument xmldTemp = fpTemp.xmldPlan;
// String szTempInner = "";
// String szTempWaypoints = "";
// String szPath = "";
// try
// {
// for (XmlNode xmlnTemp = xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
// {
// if (xmlnTemp.Name.ToLower() != "atcwaypoint")
// continue;
// KML_ICON_TYPES iconType;
// String szType = xmlnTemp["ATCWaypointType"].InnerText.ToLower();
// if (szType == "intersection")
// iconType = KML_ICON_TYPES.PLAN_INTER;
// else if (szType == "ndb")
// iconType = KML_ICON_TYPES.PLAN_NDB;
// else if (szType == "vor")
// iconType = KML_ICON_TYPES.PLAN_VOR;
// else if (szType == "user")
// iconType = KML_ICON_TYPES.PLAN_USER;
// else if (szType == "airport")
// iconType = KML_ICON_TYPES.PLAN_PORT;
// else
// iconType = KML_ICON_TYPES.UNKNOWN;
// char[] szSeperator = { ',' };
// String[] szCoordinates = xmlnTemp["WorldPosition"].InnerText.Split(szSeperator);
// if (szCoordinates.GetLength(0) != 3)
// throw new System.Exception("Invalid position value");
// String szAirway = "", szICAOIdent = "", szICAORegion = "";
// if (xmlnTemp["ATCAirway"] != null)
// szAirway = xmlnTemp["ATCAirway"].InnerText;
// if (xmlnTemp["ICAO"] != null)
// {
// if (xmlnTemp["ICAO"]["ICAOIdent"] != null)
// szICAOIdent = xmlnTemp["ICAO"]["ICAOIdent"].InnerText;
// if (xmlnTemp["ICAO"]["ICAORegion"] != null)
// szICAORegion = xmlnTemp["ICAO"]["ICAORegion"].InnerText;
// }
// double dCurrentLong = ConvertDegToDouble(szCoordinates[1]);
// double dCurrentLat = ConvertDegToDouble(szCoordinates[0]);
// double dCurrentAlt = System.Double.Parse(szCoordinates[2]);
// szTempWaypoints += "<Placemark>" +
// "<name>" + xmlnTemp["ATCWaypointType"].InnerText + " (" + xmlnTemp.Attributes["id"].Value + ")</name><visibility>1</visibility><open>0</open>" +
// "<description><![CDATA[Flight Plane Element<br> <br>" +
// "<b>Waypoint Type:</b> " + xmlnTemp["ATCWaypointType"].InnerText + "<br> <br>" +
// (szAirway != "" ? "<b>ATC Airway:</b> " + szAirway + "<br> <br>" : "") +
// (szICAOIdent != "" ? "<b>ICAO Identification:</b> " + szICAOIdent + "<br>" : "") +
// (szICAORegion != "" ? "<b>ICAO Region:</b> " + szICAORegion : "") +
// "]]></description>" +
// "<Snippet>Waypoint Type: " + xmlnTemp["ATCWaypointType"].InnerText + (szAirway != "" ? "\nAirway: " + szAirway : "") + "</Snippet>" +
// "<Style>" +
// "<IconStyle><Icon><href>" + KmlGetIconLink(AccessMode, iconType, szServer) + "</href></Icon><scale>1.0</scale></IconStyle>" +
// "<LabelStyle><scale>0.6</scale></LabelStyle>" +
// "</Style>" +
// "<Point><altitudeMode>clampToGround</altitudeMode><coordinates>" + dCurrentLong.ToString().Replace(",", ".") + "," + dCurrentLat.ToString().Replace(",", ".") + "," + dCurrentAlt.ToString().Replace(",", ".") + "</coordinates><extrude>1</extrude></Point></Placemark>";
// szPath += dCurrentLong.ToString().Replace(",", ".") + "," + dCurrentLat.ToString().Replace(",", ".") + "," + dCurrentAlt.ToString().Replace(",", ".") + "\n";
// }
// szTempInner = "<Folder><open>0</open>" +
// "<name>" + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["Title"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["Title"].InnerText : "n/a") + "</name>" +
// "<description><![CDATA[" +
// "Type: " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["FPType"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["FPType"].InnerText : "n/a") + " (" + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["RouteType"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["RouteType"].InnerText : "n/a") + ")<br>" +
// "Flight from " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DepartureName"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DepartureName"].InnerText : "n/a") + " to " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DestinationName"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["DestinationName"].InnerText : "n/a") + ".<br> <br>" +
// "Altitude: " + (xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["CruisingAlt"] != null ? xmldTemp["SimBase.Document"]["FlightPlan.FlightPlan"]["CruisingAlt"].InnerText : "n/a") +
// "]]></description>" +
// "<Placemark><name>Path</name><Style><LineStyle><color>9f1ab6ff</color><width>2</width></LineStyle></Style><LineString><tessellate>1</tessellate><altitudeMode>clampToGround</altitudeMode><coordinates>" + szPath + "</coordinates></LineString></Placemark>" +
// "<Folder><open>0</open><name>Waypoints</name>" + szTempWaypoints + "</Folder>" +
// "</Folder>";
// }
// catch
// {
// szTemp += "<Folder><name>Invalid Flight Plan</name><snippet>Error loading flight plan.</snippet></Folder>";
// continue;
// }
// szTemp += szTempInner;
// }
// }
// return szTemp;
//}
#endregion
#region Update Check
// private void checkForProgramUpdate()
// {
// try
// {
// szOnlineVersionCheckData = "";
// wrOnlineVersionCheck = WebRequest.Create("http://juergentreml.online.de/fsxget/provide/version.txt");
// wrOnlineVersionCheck.BeginGetResponse(new AsyncCallback(RespCallback), wrOnlineVersionCheck);
// }
// catch
// {
//#if DEBUG
// notifyIconMain.ShowBalloonTip(5, Text, "Couldn't check for program update online!", ToolTipIcon.Warning);
//#endif
// }
// }
// private void RespCallback(IAsyncResult asynchronousResult)
// {
// try
// {
// WebRequest myWebRequest = (WebRequest)asynchronousResult.AsyncState;
// wrespOnlineVersionCheck = myWebRequest.EndGetResponse(asynchronousResult);
// Stream responseStream = wrespOnlineVersionCheck.GetResponseStream();
// responseStream.BeginRead(bOnlineVersionCheckRawData, 0, iOnlineVersionCheckRawDataLength, new AsyncCallback(ReadCallBack), responseStream);
// }
// catch
// {
//#if DEBUG
// notifyIconMain.ShowBalloonTip(5, Text, "Couldn't check for program update online!", ToolTipIcon.Warning);
//#endif
// }
// }
// private void ReadCallBack(IAsyncResult asyncResult)
// {
// try
// {
// Stream responseStream = (Stream)asyncResult.AsyncState;
// int iRead = responseStream.EndRead(asyncResult);
// if (iRead > 0)
// {
// szOnlineVersionCheckData += Encoding.ASCII.GetString(bOnlineVersionCheckRawData, 0, iRead);
// responseStream.BeginRead(bOnlineVersionCheckRawData, 0, iOnlineVersionCheckRawDataLength, new AsyncCallback(ReadCallBack), responseStream);
// }
// else
// {
// responseStream.Close();
// wrespOnlineVersionCheck.Close();
// char[] szSeperator = { '.' };
// String[] szVersionLocal = Application.ProductVersion.Split(szSeperator);
// String[] szVersionOnline = szOnlineVersionCheckData.Split(szSeperator);
// for (int i = 0; i < Math.Min(szVersionLocal.GetLength(0), szVersionOnline.GetLength(0)); i++)
// {
// if (Int64.Parse(szVersionOnline[i]) > Int64.Parse(szVersionLocal[i]))
// {
// notifyIconMain.ShowBalloonTip(30, Text, "A new program version is available!\n\nLatest Version:\t" + szOnlineVersionCheckData + "\nYour Version:\t" + Application.ProductVersion, ToolTipIcon.Info);
// break;
// }
// else if (Int64.Parse(szVersionOnline[i]) < Int64.Parse(szVersionLocal[i]))
// break;
// }
// }
// }
// catch
// {
//#if DEBUG
// notifyIconMain.ShowBalloonTip(5, Text, "Couldn't check for program update online!", ToolTipIcon.Warning);
//#endif
// }
// }
#endregion
#region Timers
private void timerFSXConnect_Tick(object sender, EventArgs e)
{
if (openConnection())
{
timerFSXConnect.Stop();
bConnected = true;
notifyIconMain.Icon = icReceive;
notifyIconMain.Text = Text + "(Waiting for connection...)";
safeShowBalloonTip(1000, Text, "Connected to FSX!", ToolTipIcon.Info);
}
}
private void timerIPAddressRefresh_Tick(object sender, EventArgs e)
{
IPHostEntry ipheLocalhost1 = Dns.GetHostEntry(Dns.GetHostName());
IPHostEntry ipheLocalhost2 = Dns.GetHostEntry("localhost");
lock (lockIPAddressList)
{
ipalLocal1 = ipheLocalhost1.AddressList;
ipalLocal2 = ipheLocalhost2.AddressList;
}
}
private void timerQueryUserAircraft_Tick(object sender, EventArgs e)
{
simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_USER_AIRCRAFT, DEFINITIONS.StructBasicMovingSceneryObject, 0, SIMCONNECT_SIMOBJECT_TYPE.USER);
}
private void timerQueryUserPath_Tick(object sender, EventArgs e)
{
simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_USER_PATH, DEFINITIONS.StructBasicMovingSceneryObject, 0, SIMCONNECT_SIMOBJECT_TYPE.USER);
}
private void timerUserPrediction_Tick(object sender, EventArgs e)
{
simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_USER_PREDICTION, DEFINITIONS.StructBasicMovingSceneryObject, 0, SIMCONNECT_SIMOBJECT_TYPE.USER);
}
private void timerQueryAIAircrafts_Tick(object sender, EventArgs e)
{
simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_AI_PLANE, DEFINITIONS.StructBasicMovingSceneryObject, (uint)gconffixCurrent.iRangeAIAircrafts, SIMCONNECT_SIMOBJECT_TYPE.AIRCRAFT);
}
private void timerQueryAIHelicopters_Tick(object sender, EventArgs e)
{
simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_AI_HELICOPTER, DEFINITIONS.StructBasicMovingSceneryObject, (uint)gconffixCurrent.iRangeAIHelicopters, SIMCONNECT_SIMOBJECT_TYPE.HELICOPTER);
}
private void timerQueryAIBoats_Tick(object sender, EventArgs e)
{
simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_AI_BOAT, DEFINITIONS.StructBasicMovingSceneryObject, (uint)gconffixCurrent.iRangeAIBoats, SIMCONNECT_SIMOBJECT_TYPE.BOAT);
}
private void timerQueryAIGroundUnits_Tick(object sender, EventArgs e)
{
simconnect.RequestDataOnSimObjectType(DATA_REQUESTS.REQUEST_AI_GROUND, DEFINITIONS.StructBasicMovingSceneryObject, (uint)gconffixCurrent.iRangeAIGroundUnits, SIMCONNECT_SIMOBJECT_TYPE.GROUND);
}
#endregion
#region Config File Read & Write
private void ConfigMirrorToVariables()
{
gconffixCurrent.bExitOnFsxExit = (xmldSettings["fsxget"]["settings"]["options"]["general"]["application-startup"].Attributes["Exit"].Value.ToLower() == "true");
lock (lockChConf)
{
gconfchCurrent.bEnabled = (xmldSettings["fsxget"]["settings"]["options"]["general"]["enable-on-startup"].Attributes["Enabled"].Value == "1");
gconfchCurrent.bShowBalloons = (xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value == "1");
}
gconffixCurrent.bLoadKMLFile = (xmldSettings["fsxget"]["settings"]["options"]["general"]["load-kml-file"].Attributes["Enabled"].Value == "1");
//gconffixCurrent.bCheckForUpdates = (xmldSettings["fsxget"]["settings"]["options"]["general"]["update-check"].Attributes["Enabled"].Value == "1");
gconffixCurrent.iTimerUserAircraft = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Interval"].Value);
gconffixCurrent.bQueryUserAircraft = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Enabled"].Value == "1");
gconffixCurrent.iTimerUserPath = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Interval"].Value);
gconffixCurrent.bQueryUserPath = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Enabled"].Value == "1");
gconffixCurrent.iTimerUserPathPrediction = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Interval"].Value);
gconffixCurrent.bUserPathPrediction = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Enabled"].Value == "1");
int iCount = 0;
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.Name == "prediction-point")
iCount++;
}
gconffixCurrent.dPredictionTimes = new double[iCount];
iCount = 0;
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.Name == "prediction-point")
{
gconffixCurrent.dPredictionTimes[iCount] = System.Int64.Parse(xmlnTemp.Attributes["Time"].Value);
iCount++;
}
}
gconffixCurrent.iTimerAIAircrafts = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Interval"].Value);
gconffixCurrent.iRangeAIAircrafts = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Range"].Value);
gconffixCurrent.bQueryAIAircrafts = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Enabled"].Value == "1");
gconffixCurrent.bPredictAIAircrafts = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Prediction"].Value == "1");
gconffixCurrent.bPredictPointsAIAircrafts = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["PredictionPoints"].Value == "1");
gconffixCurrent.iTimerAIHelicopters = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Interval"].Value);
gconffixCurrent.iRangeAIHelicopters = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Range"].Value);
gconffixCurrent.bQueryAIHelicopters = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Enabled"].Value == "1");
gconffixCurrent.bPredictAIHelicopters = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Prediction"].Value == "1");
gconffixCurrent.bPredictPointsAIHelicopters = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["PredictionPoints"].Value == "1");
gconffixCurrent.iTimerAIBoats = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Interval"].Value);
gconffixCurrent.iRangeAIBoats = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Range"].Value);
gconffixCurrent.bQueryAIBoats = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Enabled"].Value == "1");
gconffixCurrent.bPredictAIBoats = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Prediction"].Value == "1");
gconffixCurrent.bPredictPointsAIBoats = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["PredictionPoints"].Value == "1");
gconffixCurrent.iTimerAIGroundUnits = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Interval"].Value);
gconffixCurrent.iRangeAIGroundUnits = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Range"].Value);
gconffixCurrent.bQueryAIGroundUnits = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Enabled"].Value == "1");
gconffixCurrent.bPredictAIGroundUnits = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Prediction"].Value == "1");
gconffixCurrent.bPredictPointsAIGroundUnits = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["PredictionPoints"].Value == "1");
gconffixCurrent.bQueryAIObjects = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"].Attributes["Enabled"].Value == "1");
gconffixCurrent.iUpdateGEUserAircraft = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-aircraft"].Attributes["Interval"].Value);
gconffixCurrent.iUpdateGEUserPath = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path"].Attributes["Interval"].Value);
gconffixCurrent.iUpdateGEUserPrediction = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path-prediction"].Attributes["Interval"].Value);
gconffixCurrent.iUpdateGEAIAircrafts = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-aircrafts"].Attributes["Interval"].Value);
gconffixCurrent.iUpdateGEAIHelicopters = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-helicopters"].Attributes["Interval"].Value);
gconffixCurrent.iUpdateGEAIBoats = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-boats"].Attributes["Interval"].Value);
gconffixCurrent.iUpdateGEAIGroundUnits = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-ground-units"].Attributes["Interval"].Value);
gconffixCurrent.iServerPort = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["port"].Attributes["Value"].Value);
gconffixCurrent.uiServerAccessLevel = (uint)System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value);
gconffixCurrent.bFsxConnectionIsLocal = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Local"].Value.ToLower() == "true");
gconffixCurrent.szFsxConnectionHost = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Host"].Value;
gconffixCurrent.szFsxConnectionPort = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Port"].Value;
gconffixCurrent.szFsxConnectionProtocol = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Protocol"].Value;
//gconffixCurrent.bLoadFlightPlans = (xmldSettings["fsxget"]["settings"]["options"]["flightplans"].Attributes["Enabled"].Value == "1");
gconffixCurrent.utUnits = (UnitType)System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["units"].InnerText);
gconffixCurrent.szUserdefinedPath = "";
}
private void ConfigMirrorToForm()
{
checkBox1.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["application-startup"].Attributes["Exit"].Value.ToLower() == "true");
checkEnableOnStartup.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["enable-on-startup"].Attributes["Enabled"].Value == "1");
checkShowInfoBalloons.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value == "1");
checkBoxLoadKMLFile.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["load-kml-file"].Attributes["Enabled"].Value == "1");
//checkBoxUpdateCheck.Checked = (xmldSettings["fsxget"]["settings"]["options"]["general"]["update-check"].Attributes["Enabled"].Value == "1");
numericUpDownQueryUserAircraft.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Interval"].Value);
checkQueryUserAircraft.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Enabled"].Value == "1");
numericUpDownQueryUserPath.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Interval"].Value);
checkQueryUserPath.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Enabled"].Value == "1");
numericUpDownUserPathPrediction.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Interval"].Value);
checkBoxUserPathPrediction.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Enabled"].Value == "1");
listBoxPathPrediction.Items.Clear();
for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
{
if (xmlnTemp.Name == "prediction-point")
{
ListBoxPredictionTimesItem lbptiTemp = new ListBoxPredictionTimesItem();
lbptiTemp.dTime = System.Int64.Parse(xmlnTemp.Attributes["Time"].Value);
bool bInserted = false;
for (int n = 0; n < listBoxPathPrediction.Items.Count; n++)
{
if (((ListBoxPredictionTimesItem)listBoxPathPrediction.Items[n]).dTime > lbptiTemp.dTime)
{
listBoxPathPrediction.Items.Insert(n, lbptiTemp);
bInserted = true;
break;
}
}
if (!bInserted)
listBoxPathPrediction.Items.Add(lbptiTemp);
}
}
numericUpDownQueryAIAircraftsInterval.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Interval"].Value);
numericUpDownQueryAIAircraftsRadius.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Range"].Value);
checkBoxAIAircraftsPredictPoints.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["PredictionPoints"].Value == "1");
checkBoxAIAircraftsPredict.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Prediction"].Value == "1");
checkBoxAIAircraftsPredict_CheckedChanged(null, null);
checkBoxQueryAIAircrafts.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Enabled"].Value == "1");
checkBoxQueryAIAircrafts_CheckedChanged(null, null);
numericUpDownQueryAIHelicoptersInterval.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Interval"].Value);
numericUpDownQueryAIHelicoptersRadius.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Range"].Value);
checkBoxAIHelicoptersPredictPoints.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["PredictionPoints"].Value == "1");
checkBoxAIHelicoptersPredict.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Prediction"].Value == "1");
checkBoxAIHelicoptersPredict_CheckedChanged(null, null);
checkBoxQueryAIHelicopters.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Enabled"].Value == "1");
checkBoxQueryAIHelicopters_CheckedChanged(null, null);
numericUpDownQueryAIBoatsInterval.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Interval"].Value);
numericUpDownQueryAIBoatsRadius.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Range"].Value);
checkBoxAIBoatsPredictPoints.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["PredictionPoints"].Value == "1");
checkBoxAIBoatsPredict.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Prediction"].Value == "1");
checkBoxAIBoatsPredict_CheckedChanged(null, null);
checkBoxQueryAIBoats.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Enabled"].Value == "1");
checkBoxQueryAIBoats_CheckedChanged(null, null);
numericUpDownQueryAIGroudUnitsInterval.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Interval"].Value);
numericUpDownQueryAIGroudUnitsRadius.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Range"].Value);
checkBoxAIGroundPredictPoints.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["PredictionPoints"].Value == "1");
checkBoxAIGroundPredict.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Prediction"].Value == "1");
checkBoxAIGroundPredict_CheckedChanged(null, null);
checkBoxQueryAIGroudUnits.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Enabled"].Value == "1");
checkBoxQueryAIGroudUnits_CheckedChanged(null, null);
checkBoxQueryAIObjects.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"].Attributes["Enabled"].Value == "1");
numericUpDownRefreshUserAircraft.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-aircraft"].Attributes["Interval"].Value);
numericUpDownRefreshUserPath.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path"].Attributes["Interval"].Value);
numericUpDownRefreshUserPrediction.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path-prediction"].Attributes["Interval"].Value);
numericUpDownRefreshAIAircrafts.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-aircrafts"].Attributes["Interval"].Value);
numericUpDownRefreshAIHelicopter.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-helicopters"].Attributes["Interval"].Value);
numericUpDownRefreshAIBoats.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-boats"].Attributes["Interval"].Value);
numericUpDownRefreshAIGroundUnits.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-ground-units"].Attributes["Interval"].Value);
numericUpDownServerPort.Value = System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["port"].Attributes["Value"].Value);
if (System.Int64.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value) == 1)
radioButtonAccessRemote.Checked = true;
else
radioButtonAccessLocalOnly.Checked = true;
//checkBoxLoadFlightPlans.Checked = (xmldSettings["fsxget"]["settings"]["options"]["flightplans"].Attributes["Enabled"].Value == "1");
//listViewFlightPlans.Items.Clear();
//int iCount = 0;
//for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["flightplans"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
//{
// ListViewItem lviTemp = listViewFlightPlans.Items.Insert(iCount, xmlnTemp.Attributes["Name"].Value);
// lviTemp.Checked = (xmlnTemp.Attributes["Show"].Value == "1" ? true : false);
// lviTemp.SubItems.Add(xmlnTemp.Attributes["File"].Value);
// iCount++;
//}
radioButton7.Checked = (xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Local"].Value.ToLower() == "true");
radioButton6.Checked = !radioButton7.Checked;
textBox1.Text = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Host"].Value;
textBox3.Text = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Port"].Value;
comboBox1.SelectedIndex = comboBox1.FindString(xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Protocol"].Value);
comboBox2.SelectedIndex = int.Parse(xmldSettings["fsxget"]["settings"]["options"]["ge"]["units"].InnerText);
UpdateCheckBoxStates();
UpdateButtonStates();
}
private void ConfigRetrieveFromForm()
{
xmldSettings["fsxget"]["settings"]["options"]["general"]["application-startup"].Attributes["Exit"].Value = checkBox1.Checked ? "True" : "False";
xmldSettings["fsxget"]["settings"]["options"]["general"]["enable-on-startup"].Attributes["Enabled"].Value = checkEnableOnStartup.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value = checkShowInfoBalloons.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["general"]["load-kml-file"].Attributes["Enabled"].Value = checkBoxLoadKMLFile.Checked ? "1" : "0";
//xmldSettings["fsxget"]["settings"]["options"]["general"]["update-check"].Attributes["Enabled"].Value = checkBoxUpdateCheck.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Interval"].Value = numericUpDownQueryUserAircraft.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-aircraft"].Attributes["Enabled"].Value = checkQueryUserAircraft.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Interval"].Value = numericUpDownQueryUserPath.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-user-path"].Attributes["Enabled"].Value = checkQueryUserPath.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Interval"].Value = numericUpDownUserPathPrediction.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].Attributes["Enabled"].Value = checkBoxUserPathPrediction.Checked ? "1" : "0";
XmlNode xmlnTempLoop = xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].FirstChild;
while (xmlnTempLoop != null)
{
XmlNode xmlnDelete = xmlnTempLoop;
xmlnTempLoop = xmlnTempLoop.NextSibling;
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].RemoveChild(xmlnDelete);
}
for (int n = 0; n < listBoxPathPrediction.Items.Count; n++)
{
XmlNode xmlnTemp = xmldSettings.CreateElement("prediction-point");
XmlAttribute xmlaTemp = xmldSettings.CreateAttribute("Time");
xmlaTemp.Value = ((ListBoxPredictionTimesItem)listBoxPathPrediction.Items[n]).dTime.ToString();
xmlnTemp.Attributes.Append(xmlaTemp);
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["user-path-prediction"].AppendChild(xmlnTemp);
}
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Interval"].Value = numericUpDownQueryAIAircraftsInterval.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Range"].Value = numericUpDownQueryAIAircraftsRadius.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Enabled"].Value = checkBoxQueryAIAircrafts.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["Prediction"].Value = checkBoxAIAircraftsPredict.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-aircrafts"].Attributes["PredictionPoints"].Value = checkBoxAIAircraftsPredictPoints.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Interval"].Value = numericUpDownQueryAIHelicoptersInterval.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Range"].Value = numericUpDownQueryAIHelicoptersRadius.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Enabled"].Value = checkBoxQueryAIHelicopters.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["Prediction"].Value = checkBoxAIHelicoptersPredict.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-helicopters"].Attributes["PredictionPoints"].Value = checkBoxAIHelicoptersPredictPoints.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Interval"].Value = numericUpDownQueryAIBoatsInterval.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Range"].Value = numericUpDownQueryAIBoatsRadius.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Enabled"].Value = checkBoxQueryAIBoats.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["Prediction"].Value = checkBoxAIBoatsPredict.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-boats"].Attributes["PredictionPoints"].Value = checkBoxAIBoatsPredictPoints.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Interval"].Value = numericUpDownQueryAIGroudUnitsInterval.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Range"].Value = numericUpDownQueryAIGroudUnitsRadius.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Enabled"].Value = checkBoxQueryAIGroudUnits.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["Prediction"].Value = checkBoxAIGroundPredict.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"]["query-ai-ground-units"].Attributes["PredictionPoints"].Value = checkBoxAIGroundPredictPoints.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["query-ai-objects"].Attributes["Enabled"].Value = checkBoxQueryAIObjects.Checked ? "1" : "0";
xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-aircraft"].Attributes["Interval"].Value = numericUpDownRefreshUserAircraft.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path"].Attributes["Interval"].Value = numericUpDownRefreshUserPath.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["user-path-prediction"].Attributes["Interval"].Value = numericUpDownRefreshUserPrediction.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-aircrafts"].Attributes["Interval"].Value = numericUpDownRefreshAIAircrafts.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-helicopters"].Attributes["Interval"].Value = numericUpDownRefreshAIHelicopter.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-boats"].Attributes["Interval"].Value = numericUpDownRefreshAIBoats.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["ge"]["refresh-rates"]["ai-ground-units"].Attributes["Interval"].Value = numericUpDownRefreshAIGroundUnits.Value.ToString();
xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["port"].Attributes["Value"].Value = numericUpDownServerPort.Value.ToString();
if (radioButtonAccessRemote.Checked)
xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value = "1";
else
xmldSettings["fsxget"]["settings"]["options"]["ge"]["server-settings"]["access-level"].Attributes["Value"].Value = "0";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Local"].Value = radioButton7.Checked ? "True" : "False";
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Protocol"].Value = comboBox1.SelectedItem.ToString();
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Host"].Value = textBox1.Text;
xmldSettings["fsxget"]["settings"]["options"]["fsx"]["connection"].Attributes["Port"].Value = textBox3.Text;
xmldSettings["fsxget"]["settings"]["options"]["ge"]["units"].InnerXml = comboBox2.SelectedIndex.ToString();
//xmldSettings["fsxget"]["settings"]["options"]["flightplans"].Attributes["Enabled"].Value = checkBoxLoadFlightPlans.Checked ? "1" : "0";
}
//private void LoadFlightPlans()
//{
// bool bError = false;
// FlightPlan fpTemp;
// XmlDocument xmldTemp = new XmlDocument();
// try
// {
// int iCount = 0;
// fpTemp.szName = "";
// fpTemp.uiID = 0;
// fpTemp.xmldPlan = null;
// for (XmlNode xmlnTemp = xmldSettings["fsxget"]["settings"]["options"]["flightplans"].FirstChild; xmlnTemp != null; xmlnTemp = xmlnTemp.NextSibling)
// {
// try
// {
// if (xmlnTemp.Attributes["Show"].Value == "0")
// continue;
// XmlReader xmlrTemp = new XmlTextReader(xmlnTemp.Attributes["File"].Value);
// fpTemp.uiID = iCount;
// fpTemp.xmldPlan = new XmlDocument();
// fpTemp.xmldPlan.Load(xmlrTemp);
// xmlrTemp.Close();
// xmlrTemp = null;
// }
// catch
// {
// bError = true;
// continue;
// }
// lock (lockFlightPlanList)
// {
// listFlightPlans.Add(fpTemp);
// }
// iCount++;
// }
// }
// catch
// {
// MessageBox.Show("Could not read flight plan list from settings file! No flight plans will be loaded.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
// }
// if (bError)
// MessageBox.Show("There were errors loading some of the flight plans! These flight plans will not be shown.\n\nThis problem might be due to incorrect or no longer existing flight plan files.\nPlease remove them from the flight plan list in the options dialog.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
//}
#endregion
#region Assembly Attribute Accessors
public string AssemblyTitle
{
get
{
// Get all Title attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
// If there is at least one Title attribute
if (attributes.Length > 0)
{
// Select the first one
AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
// If it is not an empty string, return it
if (titleAttribute.Title != "")
return titleAttribute.Title;
}
// If there was no Title attribute, or if the Title attribute was the empty string, return the .exe name
return System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
}
}
public string AssemblyVersion
{
get
{
return Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}
public string AssemblyDescription
{
get
{
// Get all Description attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false);
// If there aren't any Description attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Description attribute, return its value
return ((AssemblyDescriptionAttribute)attributes[0]).Description;
}
}
public string AssemblyProduct
{
get
{
// Get all Product attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute), false);
// If there aren't any Product attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Product attribute, return its value
return ((AssemblyProductAttribute)attributes[0]).Product;
}
}
public string AssemblyCopyright
{
get
{
// Get all Copyright attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false);
// If there aren't any Copyright attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Copyright attribute, return its value
return ((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
}
public string AssemblyCompany
{
get
{
// Get all Company attributes on this assembly
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
// If there aren't any Company attributes, return an empty string
if (attributes.Length == 0)
return "";
// If there is a Company attribute, return its value
return ((AssemblyCompanyAttribute)attributes[0]).Company;
}
}
#endregion
#region User Interface Handlers
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
bClose = true;
Close();
}
private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
{
safeShowMainDialog(0);
}
private void enableTrackerToolStripMenuItem_Click(object sender, EventArgs e)
{
bool bTemp = enableTrackerToolStripMenuItem.Checked;
lock (lockChConf)
{
if (bTemp != gconfchCurrent.bEnabled)
{
gconfchCurrent.bEnabled = bTemp;
if (gconfchCurrent.bEnabled)
globalConnect();
else
globalDisconnect();
}
}
}
private void showBalloonTipsToolStripMenuItem_Click(object sender, EventArgs e)
{
lock (lockChConf)
{
gconfchCurrent.bShowBalloons = showBalloonTipsToolStripMenuItem.Checked;
}
// This call is safe as the existence of this key has been checked by calling configMirrorToForm at startup.
xmldSettings["fsxget"]["settings"]["options"]["general"]["show-balloon-tips"].Attributes["Enabled"].Value = showBalloonTipsToolStripMenuItem.Checked ? "1" : "0";
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
safeShowMainDialog(5);
}
private void clearUserAircraftPathToolStripMenuItem_Click(object sender, EventArgs e)
{
lock (lockKmlUserPath)
{
szKmlUserAircraftPath = "";
}
lock (lockKmlUserPrediction)
{
szKmlUserPrediction = "";
listKmlPredictionPoints.Clear();
}
lock (lockKmlPredictionPoints)
{
clearPPStructure(ref ppPos1);
clearPPStructure(ref ppPos2);
}
}
private void runMicrosoftFlightSimulatorXToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
System.Diagnostics.Process.Start(szPathFSX);
}
catch
{
MessageBox.Show("An error occured while trying to start Microsoft Flight Simulator X.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void runGoogleEarthToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
lock (lockListenerControl)
{
if (gconffixCurrent.bLoadKMLFile && bConnected)
System.Diagnostics.Process.Start(szUserAppPath + "\\pub\\fsxgetd.kml");
else
System.Diagnostics.Process.Start(szUserAppPath + "\\pub\\fsxgets.kml");
}
}
catch
{
MessageBox.Show("An error occured while trying to start Google Earth.", Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
if (notifyIconMain.ContextMenuStrip == null)
this.Activate();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
linkLabel1.LinkVisited = true;
System.Diagnostics.Process.Start("http://www.juergentreml.de/fsxget/");
}
catch
{
MessageBox.Show("Unable to open http://www.juergentreml.de/fsxget/!");
}
}
private void checkBoxQueryAIObjects_CheckedChanged(object sender, EventArgs e)
{
checkBoxQueryAIAircrafts.Enabled = checkBoxQueryAIBoats.Enabled = checkBoxQueryAIGroudUnits.Enabled = checkBoxQueryAIHelicopters.Enabled = checkBoxQueryAIObjects.Checked;
bRestartRequired = true;
}
private void checkBoxQueryAIAircrafts_CheckedChanged(object sender, EventArgs e)
{
checkBoxQueryAIAircrafts_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxQueryAIAircrafts_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIAircraftsPredict.Enabled = numericUpDownQueryAIAircraftsInterval.Enabled = numericUpDownQueryAIAircraftsRadius.Enabled = (checkBoxQueryAIAircrafts.Enabled & checkBoxQueryAIAircrafts.Checked);
}
private void checkBoxQueryAIHelicopters_CheckedChanged(object sender, EventArgs e)
{
checkBoxQueryAIHelicopters_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxQueryAIHelicopters_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIHelicoptersPredict.Enabled = numericUpDownQueryAIHelicoptersInterval.Enabled = numericUpDownQueryAIHelicoptersRadius.Enabled = (checkBoxQueryAIHelicopters.Enabled & checkBoxQueryAIHelicopters.Checked);
}
private void checkBoxQueryAIBoats_CheckedChanged(object sender, EventArgs e)
{
checkBoxQueryAIBoats_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxQueryAIBoats_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIBoatsPredict.Enabled = numericUpDownQueryAIBoatsInterval.Enabled = numericUpDownQueryAIBoatsRadius.Enabled = (checkBoxQueryAIBoats.Enabled & checkBoxQueryAIBoats.Checked);
}
private void checkBoxQueryAIGroudUnits_CheckedChanged(object sender, EventArgs e)
{
checkBoxQueryAIGroudUnits_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxQueryAIGroudUnits_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIGroundPredict.Enabled = numericUpDownQueryAIGroudUnitsInterval.Enabled = numericUpDownQueryAIGroudUnitsRadius.Enabled = (checkBoxQueryAIGroudUnits.Enabled & checkBoxQueryAIGroudUnits.Checked);
}
private void checkQueryUserAircraft_CheckedChanged(object sender, EventArgs e)
{
numericUpDownQueryUserAircraft.Enabled = checkQueryUserAircraft.Checked;
bRestartRequired = true;
}
private void checkQueryUserPath_CheckedChanged(object sender, EventArgs e)
{
numericUpDownQueryUserPath.Enabled = checkQueryUserPath.Checked;
bRestartRequired = true;
}
private void buttonOK_Click(object sender, EventArgs e)
{
// Set startup options if necessary
if (radioButton8.Checked)
{
if (!isAutoStartActivated())
if (!AutoStartActivate())
MessageBox.Show("Couldn't change autorun value in registry!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
if (isFsxStartActivated())
if (!FsxStartDeactivate())
MessageBox.Show("Couldn't change FSX startup options!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else if (radioButton9.Checked)
{
if (!isFsxStartActivated())
if (!FsxStartActivate())
MessageBox.Show("Couldn't change FSX startup options!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
if (isAutoStartActivated())
if (!AutoStartDeactivate())
MessageBox.Show("Couldn't change autorun value in registry!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
if (isFsxStartActivated())
if (!FsxStartDeactivate())
MessageBox.Show("Couldn't change FSX startup options!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
if (isAutoStartActivated())
if (!AutoStartDeactivate())
MessageBox.Show("Couldn't change autorun value in registry!", AssemblyTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
//string szRun = (string)Registry.GetValue(szRegKeyRun, AssemblyTitle, "");
ConfigRetrieveFromForm();
showBalloonTipsToolStripMenuItem.Checked = checkShowInfoBalloons.Checked;
notifyIconMain.ContextMenuStrip = contextMenuStripNotifyIcon;
gconffixCurrent.utUnits = (UnitType)comboBox2.SelectedIndex;
if (bRestartRequired)
if (MessageBox.Show("Some of the changes you made require a restart. Do you want to restart " + Text + " now for those changes to take effect.", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
RestartApp();
Hide();
}
private void buttonCancel_Click(object sender, EventArgs e)
{
safeHideMainDialog();
}
private void numericUpDownQueryUserAircraft_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryUserPath_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIAircraftsInterval_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIHelicoptersInterval_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIBoatsInterval_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIGroudUnitsInterval_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIAircraftsRadius_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIHelicoptersRadius_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIBoatsRadius_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownQueryAIGroudUnitsRadius_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownRefreshUserAircraft_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownRefreshUserPath_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownRefreshAIAircrafts_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownRefreshAIHelicopter_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownRefreshAIBoats_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownRefreshAIGroundUnits_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownServerPort_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void checkBoxLoadKMLFile_CheckedChanged(object sender, EventArgs e)
{
gconffixCurrent.bLoadKMLFile = checkBoxLoadKMLFile.Checked;
}
private void checkBoxUserPathPrediction_CheckedChanged(object sender, EventArgs e)
{
numericUpDownUserPathPrediction.Enabled = checkBoxUserPathPrediction.Checked;
bRestartRequired = true;
}
private void numericUpDownUserPathPrediction_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void numericUpDownRefreshUserPrediction_ValueChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void checkBoxSaveLog_CheckedChanged(object sender, EventArgs e)
{
checkBoxSubFoldersForLog.Enabled = (checkBoxSaveLog.Checked);
}
private void radioButtonAccessLocalOnly_CheckedChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void radioButtonAccessRemote_CheckedChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void checkBoxAIAircraftsPredict_CheckedChanged(object sender, EventArgs e)
{
checkBoxAIAircraftsPredict_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxAIAircraftsPredict_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIAircraftsPredictPoints.Enabled = (checkBoxAIAircraftsPredict.Enabled & checkBoxAIAircraftsPredict.Checked);
}
private void checkBoxAIHelicoptersPredict_CheckedChanged(object sender, EventArgs e)
{
checkBoxAIHelicoptersPredict_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxAIHelicoptersPredict_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIHelicoptersPredictPoints.Enabled = (checkBoxAIHelicoptersPredict.Enabled & checkBoxAIHelicoptersPredict.Checked);
}
private void checkBoxAIBoatsPredict_CheckedChanged(object sender, EventArgs e)
{
checkBoxAIBoatsPredict_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxAIBoatsPredict_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIBoatsPredictPoints.Enabled = (checkBoxAIBoatsPredict.Enabled & checkBoxAIBoatsPredict.Checked);
}
private void checkBoxAIGroundPredict_CheckedChanged(object sender, EventArgs e)
{
checkBoxAIGroundPredict_EnabledChanged(null, null);
bRestartRequired = true;
}
private void checkBoxAIGroundPredict_EnabledChanged(object sender, EventArgs e)
{
checkBoxAIGroundPredictPoints.Enabled = (checkBoxAIGroundPredict.Enabled & checkBoxAIGroundPredict.Checked);
}
private void checkBoxAIAircraftsPredictPoints_CheckedChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void checkBoxAIHelicoptersPredictPoints_CheckedChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void checkBoxAIBoatsPredictPoints_CheckedChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void checkBoxAIGroundPredictPoints_CheckedChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void createGoogleEarthKMLFileToolStripMenuItem_DropDownIPClick(object sender, EventArgs e)
{
String szTemp = sender.ToString();
if (szTemp.Length < 7)
return;
szTemp = szTemp.Substring(7);
String szKMLFile = "";
if (CompileKMLStartUpFileDynamic(szTemp, ref szKMLFile))
{
safeShowMainDialog(0);
if (saveFileDialogKMLFile.ShowDialog() == DialogResult.OK)
{
try
{
File.WriteAllText(saveFileDialogKMLFile.FileName, szKMLFile);
}
catch
{
MessageBox.Show("Could not save KML file!", Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
safeHideMainDialog();
}
}
private void contextMenuStripNotifyIcon_Opening(object sender, CancelEventArgs e)
{
createGoogleEarthKMLFileToolStripMenuItem.DropDown.Items.Clear();
lock (lockIPAddressList)
{
bool bAddressFound = false;
if (ipalLocal1 != null)
{
foreach (IPAddress ipaTemp in ipalLocal1)
{
bAddressFound = true;
createGoogleEarthKMLFileToolStripMenuItem.DropDown.Items.Add("For IP " + ipaTemp.ToString(), null, createGoogleEarthKMLFileToolStripMenuItem_DropDownIPClick);
}
}
if (ipalLocal2 != null)
{
foreach (IPAddress ipaTemp in ipalLocal2)
{
bAddressFound = true;
createGoogleEarthKMLFileToolStripMenuItem.DropDown.Items.Add("For IP " + ipaTemp.ToString(), null, createGoogleEarthKMLFileToolStripMenuItem_DropDownIPClick);
}
}
if (!bAddressFound)
createGoogleEarthKMLFileToolStripMenuItem.Enabled = false;
else
createGoogleEarthKMLFileToolStripMenuItem.Enabled = true;
}
}
private void button3_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Are you sure you want to remove the selected items?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
//foreach (ListViewItem lviTemp in listViewFlightPlans.SelectedItems)
//{
// listViewFlightPlans.Items.Remove(lviTemp);
//}
}
}
private void radioButton7_CheckedChanged(object sender, EventArgs e)
{
comboBox1.Enabled = textBox1.Enabled = textBox3.Enabled = !radioButton7.Checked;
bRestartRequired = true;
}
private void radioButton6_CheckedChanged(object sender, EventArgs e)
{
comboBox1.Enabled = textBox1.Enabled = textBox3.Enabled = radioButton6.Checked;
bRestartRequired = true;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void textBox3_TextChanged(object sender, EventArgs e)
{
bRestartRequired = true;
}
private void radioButton10_CheckedChanged(object sender, EventArgs e)
{
if (radioButton10.Checked)
radioButton8.Checked = radioButton9.Checked = checkBox1.Enabled = false;
}
private void radioButton9_CheckedChanged(object sender, EventArgs e)
{
checkBox1.Enabled = radioButton9.Checked;
}
private void radioButton8_CheckedChanged(object sender, EventArgs e)
{
if (radioButton10.Checked)
radioButton8.Checked = radioButton9.Checked = checkBox1.Enabled = false;
}
private void checkEnableOnStartup_CheckedChanged(object sender, EventArgs e)
{
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
gconffixCurrent.bExitOnFsxExit = checkBox1.Checked;
}
private void checkShowInfoBalloons_CheckedChanged(object sender, EventArgs e)
{
}
private void listBoxPathPrediction_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateButtonStates();
}
private void button2_Click(object sender, EventArgs e)
{
if (listBoxPathPrediction.SelectedItems.Count == 1)
{
int iIndex = listBoxPathPrediction.SelectedIndex;
listBoxPathPrediction.Items.RemoveAt(iIndex);
if (listBoxPathPrediction.SelectedItems.Count == 0)
{
if (listBoxPathPrediction.Items.Count > iIndex)
listBoxPathPrediction.SelectedIndex = iIndex;
else if (listBoxPathPrediction.Items.Count > 0)
listBoxPathPrediction.SelectedIndex = listBoxPathPrediction.Items.Count - 1;
}
bRestartRequired = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
int iSeconds;
if (frmAdd.ShowDialog(out iSeconds) == DialogResult.Cancel)
return;
ListBoxPredictionTimesItem lbptiTemp = new ListBoxPredictionTimesItem();
lbptiTemp.dTime = iSeconds;
bool bInserted = false;
for (int n = 0; n < listBoxPathPrediction.Items.Count; n++)
{
if (((ListBoxPredictionTimesItem)listBoxPathPrediction.Items[n]).dTime > lbptiTemp.dTime)
{
listBoxPathPrediction.Items.Insert(n, lbptiTemp);
bInserted = true;
break;
}
}
if (!bInserted)
listBoxPathPrediction.Items.Add(lbptiTemp);
bRestartRequired = true;
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace VariablesManager
{
public partial class Form1 : Form
{
private string _selectedTm;
private string _selectedLrt;
public string SelectedTm
{
get => _selectedTm.Trim();
set => _selectedTm = value;
}
public string SelectedLrt
{
get => _selectedLrt.Trim();
set => _selectedLrt = value;
}
public Form1()
{
InitializeComponent();
}
private void btnBrowseTM_Click(object sender, EventArgs e)
{
openFileDialog.Filter = @"Translation memory (*.sdltm)|*.sdltm";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
SelectedTm = openFileDialog.FileName;
txtTM.Text = Path.GetFileName(openFileDialog.FileName);
}
}
private void btnBrowseLRT_Click(object sender, EventArgs e)
{
openFileDialog.Filter = @"Language Resource Template (*.resource)|*.resource";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
SelectedLrt = openFileDialog.FileName;
txtLRT.Text = Path.GetFileName(openFileDialog.FileName);
}
}
private void btnImportFromFile_Click(object sender, EventArgs e)
{
openFileDialog.Filter = @"Text files (*.txt)|*.txt|All files (*.*)|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
using (var sr = new StreamReader(openFileDialog.FileName))
{
txtVariables.Text = sr.ReadToEnd();
}
}
catch
{
}
}
}
private void btnExportToFile_Click(object sender, EventArgs e)
{
saveFileDialog.Filter = @"Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog.DefaultExt = "txt";
saveFileDialog.AddExtension = true;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
using (var sw = new StreamWriter(saveFileDialog.FileName, false))
{
sw.Write(txtVariables.Text);
}
}
catch
{
}
}
MessageBox.Show(@"The variables list was exported to the selected file.");
}
private void btnFetchList_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtTM.Text))
{
FetchFromTm();
}
if (!string.IsNullOrEmpty(txtLRT.Text))
{
FetchFromLrt();
}
}
private void FetchFromLrt()
{
if (string.IsNullOrEmpty(SelectedLrt))
return;
var vars = GetVariablesAsTextFromLrt();
if (string.IsNullOrEmpty(vars))
return;
if (!string.IsNullOrEmpty(txtVariables.Text) &&
txtVariables.Text[txtVariables.Text.Length - 1] != '\n')
txtVariables.Text += "\r\n";
txtVariables.Text += vars;
}
private string GetVariablesAsTextFromLrt()
{
try
{
var xFinalDoc = new XmlDocument();
xFinalDoc.Load(SelectedLrt);
XmlNodeList languageResources = xFinalDoc.DocumentElement.GetElementsByTagName("LanguageResource");
if (languageResources.Count > 0)
{
foreach (XmlElement languageResource in languageResources)
{
if (languageResource.HasAttribute("Type") &&
languageResource.Attributes["Type"].Value == "Variables")
{
IEnumerable<XmlText> textElements = languageResource.ChildNodes.OfType<XmlText>();
if (textElements.Any())
{
var textElement = textElements.FirstOrDefault();
var base64Vars = textElement.Value;
return Encoding.UTF8.GetString(Convert.FromBase64String(base64Vars));
}
}
}
}
}
catch
{
}
return string.Empty;
}
private void FetchFromTm()
{
if (string.IsNullOrEmpty(txtTM.Text) || string.IsNullOrEmpty(SelectedTm))
return;
int count = 0;
var vars = GetVariablesAsTextFromTm(out count);
if (string.IsNullOrEmpty(vars))
return;
if (!string.IsNullOrEmpty(txtVariables.Text) && txtVariables.Text[txtVariables.Text.Length - 1] != '\n')
txtVariables.Text += "\r\n";
txtVariables.Text += vars;
}
private string GetVariablesAsTextFromTm(out int count)
{
count = 0;
try
{
SQLiteConnectionStringBuilder sb = new SQLiteConnectionStringBuilder();
sb.DataSource = SelectedTm;
sb.Version = 3;
sb.JournalMode = SQLiteJournalModeEnum.Off;
using (var connection = new SQLiteConnection(sb.ConnectionString, true))
using (var command = new SQLiteCommand(connection))
{
connection.Open();
command.CommandText = "SELECT data FROM resources where type = 1";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
count++;
var buffer = GetBytes(reader);
return Encoding.UTF8.GetString(buffer);
}
}
}
}
catch
{
}
return string.Empty;
}
static byte[] GetBytes(SQLiteDataReader reader)
{
const int CHUNK_SIZE = 2 * 1024;
var buffer = new byte[CHUNK_SIZE];
long bytesRead;
long fieldOffset = 0;
using (MemoryStream stream = new MemoryStream())
{
while ((bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, (int)bytesRead);
fieldOffset += bytesRead;
}
return stream.ToArray();
}
}
private void btnAddToTMorLRT_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtTM.Text))
AddToTm();
if (!string.IsNullOrEmpty(txtLRT.Text))
AddToLrt();
}
private void AddToLrt()
{
if (string.IsNullOrEmpty(SelectedLrt) || string.IsNullOrEmpty(txtVariables.Text))
return;
var vars = GetVariablesAsTextFromLrt() + txtVariables.Text;
if (!string.IsNullOrEmpty(vars) && vars[vars.Length - 1] != '\n')
vars += "\r\n";
var base64Vars = Convert.ToBase64String(Encoding.UTF8.GetBytes(vars));
SetVariablesInLrt(base64Vars);
MessageBox.Show(@"The variables list was add to the selected Language Resource Template.");
}
private void SetVariablesInLrt(string base64Vars)
{
try
{
var xFinalDoc = new XmlDocument();
xFinalDoc.Load(SelectedLrt);
XmlNodeList languageResources = xFinalDoc.DocumentElement.GetElementsByTagName("LanguageResource");
if (languageResources.Count > 0)
{
foreach (XmlElement languageResource in languageResources)
{
if (languageResource.HasAttribute("Type") &&
languageResource.Attributes["Type"].Value == "Variables")
{
languageResource.InnerText = base64Vars;
}
}
}
using (var writer = new XmlTextWriter(SelectedLrt, null))
{
writer.Formatting = Formatting.None;
xFinalDoc.Save(writer);
}
}
catch
{
}
}
private void AddToTm()
{
if (string.IsNullOrEmpty(SelectedTm) || string.IsNullOrEmpty(txtVariables.Text))
return;
int count = 0;
var vars = GetVariablesAsTextFromTm(out count) + txtVariables.Text;
if (!string.IsNullOrEmpty(vars) && vars[vars.Length - 1] != '\n')
vars += "\r\n";
SetVariablesInTm(Encoding.UTF8.GetBytes(vars), count);
MessageBox.Show(@"The variables list was add to the selected Translation Memory.");
}
private void SetVariablesInTm(byte[] variablesAsBytes, int count)
{
try
{
var sb = new SQLiteConnectionStringBuilder
{
DataSource = SelectedTm,
Version = 3,
JournalMode = SQLiteJournalModeEnum.Off
};
int maxID = 0;
if (count == 0)
{
using (var connection = new SQLiteConnection(sb.ConnectionString, true))
{
using (var command = new SQLiteCommand(connection))
{
connection.Open();
command.CommandText = "Select max(id) from resources";
object oId = command.ExecuteScalar();
maxID = oId == DBNull.Value ? 1 : Convert.ToInt32(oId) + 1;
}
}
}
using (var connection = new SQLiteConnection(sb.ConnectionString, true))
{
using (var command = new SQLiteCommand(connection))
{
connection.Open();
if (count == 0)
{
command.CommandText =
string.Format(
"insert into resources (rowid, id, guid, type, language, data) values ({2}, {2}, '{0}', 1, '{1}', @data)",
Guid.NewGuid(), GetTmLanguage(), maxID);
}
else
{
command.CommandText = "update resources set data = @data where type = 1";
}
command.Parameters.Add("@data", DbType.Binary).Value = variablesAsBytes;
command.ExecuteNonQuery();
}
}
}
catch (Exception e)
{
}
}
private object GetTmLanguage()
{
try
{
var sb = new SQLiteConnectionStringBuilder
{
DataSource = SelectedTm,
Version = 3,
JournalMode = SQLiteJournalModeEnum.Off
};
using (var connection = new SQLiteConnection(sb.ConnectionString, true))
using (var command = new SQLiteCommand(connection))
{
connection.Open();
command.CommandText = "SELECT source_language FROM translation_memories";
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
return reader.GetString(0);
}
}
}
}
catch
{
}
return string.Empty;
}
private void btnReplateToTMorLRT_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtTM.Text))
{
ReplaceToTm();
}
if (!string.IsNullOrEmpty(txtLRT.Text))
{
ReplaceToLrt();
}
}
private void ReplaceToLrt()
{
if (string.IsNullOrEmpty(SelectedLrt))
{
return;
}
var vars = txtVariables.Text;
if (!string.IsNullOrEmpty(vars) && vars[vars.Length - 1] != '\n')
{
vars += "\r\n";
}
var base64Vars = Convert.ToBase64String(Encoding.UTF8.GetBytes(vars));
SetVariablesInLrt(base64Vars);
MessageBox.Show(@"The variables list from the selected Language Resource Template was replaced with the new one.");
}
private void ReplaceToTm()
{
if (string.IsNullOrEmpty(SelectedTm))
return;
var vars = txtVariables.Text;
if (!string.IsNullOrEmpty(vars) && vars[vars.Length - 1] != '\n')
vars += "\r\n";
var count = 0;
GetVariablesAsTextFromTm(out count);
SetVariablesInTm(Encoding.UTF8.GetBytes(vars), count);
MessageBox.Show(@"The variables list from the selected Translation Memory was replaced with the new one.");
}
private void btnClear_Click(object sender, EventArgs e)
{
txtVariables.Clear();
}
}
}
|
using Halsign.DWM.Framework;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading;
namespace Halsign.DWM.Domain
{
public class DwmHost : DwmBase
{
private int _numCpus = 1;
private int _numVCpus;
private int _cpuSpeed;
private int _numNics = 1;
private bool _isPoolMaster;
private bool _enabled = true;
private string _ipAddress;
private bool _isEnterpriseOrHigher;
private PowerStatus _powerState;
private bool _participatesInPowerManagement;
private bool _excludeFromPlacementRecommendations;
private bool _excludeFromEvacuationRecommendations;
private bool _excludeFromPoolOptimizationAcceptVMs;
private long _memOverhead;
private DateTime _metricsLastRetrieved = DateTime.MinValue;
private DwmVirtualMachineCollection _listVMs;
private DwmPifCollection _listPIFs;
private DwmPbdCollection _listPBDs;
private DwmStorageRepositoryCollection _availableStorage;
private DwmHostAverageMetric _metrics;
private static Dictionary<string, int> _uuidCache = new Dictionary<string, int>();
private static Dictionary<string, int> _nameCache = new Dictionary<string, int>();
private static Dictionary<string, string> _uuidNameCache = new Dictionary<string, string>();
private static object _uuidCacheLock = new object();
private static object _nameCacheLock = new object();
private static object _uuidNameCacheLock = new object();
private double _cpuScore;
public int NumCpus
{
get
{
return this._numCpus;
}
set
{
this._numCpus = value;
}
}
public int NumVCpus
{
get
{
return this._numVCpus;
}
set
{
this._numVCpus = value;
}
}
public int CpuSpeed
{
get
{
return this._cpuSpeed;
}
set
{
this._cpuSpeed = value;
}
}
public int NumNics
{
get
{
return this._numNics;
}
set
{
this._numNics = value;
}
}
public string IPAddress
{
get
{
return this._ipAddress;
}
set
{
this._ipAddress = value;
}
}
public bool IsPoolMaster
{
get
{
return this._isPoolMaster;
}
set
{
this._isPoolMaster = value;
}
}
public bool Enabled
{
get
{
return this._enabled;
}
set
{
this._enabled = value;
}
}
public bool IsEnterpriseOrHigher
{
get
{
return this._isEnterpriseOrHigher;
}
set
{
this._isEnterpriseOrHigher = value;
}
}
public PowerStatus PowerState
{
get
{
return this._powerState;
}
set
{
this._powerState = value;
}
}
public long MemoryOverhead
{
get
{
return this._memOverhead;
}
set
{
this._memOverhead = value;
}
}
internal bool ParticipatesInPowerManagement
{
get
{
return this._participatesInPowerManagement;
}
set
{
this._participatesInPowerManagement = value;
}
}
internal bool ExcludeFromPlacementRecommendations
{
get
{
return this._excludeFromPlacementRecommendations;
}
set
{
this._excludeFromPlacementRecommendations = value;
}
}
internal bool ExcludeFromEvacuationRecommendations
{
get
{
return this._excludeFromEvacuationRecommendations;
}
set
{
this._excludeFromEvacuationRecommendations = value;
}
}
internal bool ExcludeFromPoolOptimizationAcceptVMs
{
get
{
return this._excludeFromPoolOptimizationAcceptVMs;
}
set
{
this._excludeFromPoolOptimizationAcceptVMs = value;
}
}
public DwmVirtualMachineCollection VirtualMachines
{
get
{
return DwmBase.SafeGetItem<DwmVirtualMachineCollection>(ref this._listVMs);
}
internal set
{
this._listVMs = value;
}
}
public DwmPifCollection PIFs
{
get
{
return DwmBase.SafeGetItem<DwmPifCollection>(ref this._listPIFs);
}
}
public DwmPbdCollection PBDs
{
get
{
return DwmBase.SafeGetItem<DwmPbdCollection>(ref this._listPBDs);
}
}
public DwmStorageRepositoryCollection AvailableStorage
{
get
{
return DwmBase.SafeGetItem<DwmStorageRepositoryCollection>(ref this._availableStorage);
}
internal set
{
this._availableStorage = value;
}
}
public DwmHostAverageMetric Metrics
{
get
{
return DwmBase.SafeGetItem<DwmHostAverageMetric>(ref this._metrics);
}
internal set
{
this._metrics = value;
}
}
internal double CpuScore
{
get
{
this._cpuScore = (double)(this.NumCpus * this.CpuSpeed);
if (this.Metrics.MetricsNow != null)
{
this._cpuScore *= 1.0 - this.Metrics.MetricsNow.AverageCpuUtilization;
}
return this._cpuScore;
}
}
public DateTime MetricsLastRetrieved
{
get
{
if (this._metricsLastRetrieved == DateTime.MinValue)
{
string sqlStatement = "get_host_last_metric_time";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_id", base.Id));
using (DBAccess dBAccess = new DBAccess())
{
this._metricsLastRetrieved = dBAccess.ExecuteScalarDateTime(sqlStatement, storedProcParamCollection);
}
if (this._metricsLastRetrieved == DateTime.MinValue)
{
this._metricsLastRetrieved = DateTime.UtcNow.AddMinutes(-1.0);
}
}
return this._metricsLastRetrieved;
}
set
{
this._metricsLastRetrieved = value;
}
}
public DwmHost(string uuid, string name, string poolUuid) : base(uuid, name)
{
base.PoolId = DwmBase.PoolUuidToId(poolUuid);
if (!string.IsNullOrEmpty(uuid))
{
base.Id = DwmHost.UuidToId(uuid, base.PoolId);
}
else
{
if (string.IsNullOrEmpty(name))
{
throw new DwmException("The uuid or name of the Physical Host must be specified.", DwmErrorCode.InvalidParameter, null);
}
base.Id = DwmHost.NameToId(name, base.PoolId);
}
}
public DwmHost(string uuid, string name, int poolId) : base(uuid, name)
{
base.PoolId = poolId;
if (!string.IsNullOrEmpty(uuid))
{
base.Id = DwmHost.UuidToId(uuid, base.PoolId);
}
else
{
if (string.IsNullOrEmpty(name))
{
throw new DwmException("The uuid or name of the Physical Host must be specified.", DwmErrorCode.InvalidParameter, null);
}
base.Id = DwmHost.NameToId(name, base.PoolId);
}
}
public DwmHost(int hostID) : base(hostID)
{
}
internal static void RefreshCache()
{
object uuidCacheLock = DwmHost._uuidCacheLock;
Monitor.Enter(uuidCacheLock);
try
{
DwmHost._uuidCache.Clear();
}
finally
{
Monitor.Exit(uuidCacheLock);
}
object nameCacheLock = DwmHost._nameCacheLock;
Monitor.Enter(nameCacheLock);
try
{
DwmHost._nameCache.Clear();
}
finally
{
Monitor.Exit(nameCacheLock);
}
object uuidNameCacheLock = DwmHost._uuidNameCacheLock;
Monitor.Enter(uuidNameCacheLock);
try
{
DwmHost._uuidNameCache.Clear();
}
finally
{
Monitor.Exit(uuidNameCacheLock);
}
}
internal static int UuidToId(string uuid, int poolId)
{
int num = 0;
if (!string.IsNullOrEmpty(uuid))
{
string key = Localization.Format("{0}|{1}", uuid, poolId);
if (!DwmHost._uuidCache.TryGetValue(key, out num))
{
using (DBAccess dBAccess = new DBAccess())
{
num = dBAccess.ExecuteScalarInt(Localization.Format("select id from hv_host where uuid='{0}' and poolid={1}", uuid.Replace("'", "''"), poolId));
if (num != 0)
{
object uuidCacheLock = DwmHost._uuidCacheLock;
Monitor.Enter(uuidCacheLock);
try
{
if (!DwmHost._uuidCache.ContainsKey(key))
{
DwmHost._uuidCache.Add(key, num);
}
}
finally
{
Monitor.Exit(uuidCacheLock);
}
}
}
}
}
return num;
}
public static int NameToId(string name, int poolId)
{
int num = 0;
if (!string.IsNullOrEmpty(name))
{
string key = Localization.Format("{0}|{1}", name, poolId);
if (!DwmHost._nameCache.TryGetValue(key, out num))
{
using (DBAccess dBAccess = new DBAccess())
{
num = dBAccess.ExecuteScalarInt(Localization.Format("select id from hv_host where name='{0}' and poolid={1}", name.Replace("'", "''"), poolId));
if (num != 0)
{
object nameCacheLock = DwmHost._nameCacheLock;
Monitor.Enter(nameCacheLock);
try
{
if (!DwmHost._nameCache.ContainsKey(key))
{
DwmHost._nameCache.Add(key, num);
}
}
finally
{
Monitor.Exit(nameCacheLock);
}
}
}
}
}
return num;
}
public static string UuidToName(string uuid, int poolId)
{
string text = string.Empty;
if (!string.IsNullOrEmpty(uuid))
{
string key = Localization.Format("{0}|{1}", uuid, poolId);
if (!DwmHost._uuidNameCache.TryGetValue(key, out text))
{
using (DBAccess dBAccess = new DBAccess())
{
text = dBAccess.ExecuteScalarString(Localization.Format("select name from hv_host where uuid='{0}' and poolid={1}", uuid, poolId));
if (string.IsNullOrEmpty(text))
{
object uuidNameCacheLock = DwmHost._uuidNameCacheLock;
Monitor.Enter(uuidNameCacheLock);
try
{
if (!DwmHost._uuidNameCache.ContainsKey(key))
{
DwmHost._uuidNameCache.Add(key, text);
}
}
finally
{
Monitor.Exit(uuidNameCacheLock);
}
}
}
}
}
return text;
}
public DwmHost Copy()
{
return new DwmHost(base.Uuid, base.Name, base.PoolId)
{
Id = base.Id,
CpuSpeed = this.CpuSpeed,
Description = base.Description,
IsPoolMaster = this.IsPoolMaster,
Name = base.Name,
NumCpus = this.NumCpus,
NumVCpus = this.NumVCpus,
NumNics = this.NumNics,
ParticipatesInPowerManagement = this.ParticipatesInPowerManagement,
ExcludeFromPlacementRecommendations = this.ExcludeFromPlacementRecommendations,
ExcludeFromEvacuationRecommendations = this.ExcludeFromEvacuationRecommendations,
ExcludeFromPoolOptimizationAcceptVMs = this.ExcludeFromPoolOptimizationAcceptVMs,
PowerState = this.PowerState,
MemoryOverhead = this.MemoryOverhead,
Metrics = this.Metrics.Copy(),
AvailableStorage = this.AvailableStorage.Copy(),
VirtualMachines = this.VirtualMachines.Copy()
};
}
internal static void SetOtherConfig(int hostId, string name, string value)
{
DwmHost dwmHost = new DwmHost(hostId);
dwmHost.SetOtherConfig(name, value);
}
public void SetOtherConfig(string name, string value)
{
base.SetOtherConfig("hv_host_config_update", "@host_id", name, value);
if (Localization.Compare(name, "ParticipatesInPowerManagement", true) == 0)
{
DwmPool.GenerateFillOrder(base.PoolId);
}
}
public void SetOtherConfig(Dictionary<string, string> config)
{
base.SetOtherConfig("hv_host_config_update", "@host_id", config);
if (config.ContainsKey("ParticipatesInPowerManagement"))
{
DwmPool.GenerateFillOrder(base.PoolId);
}
}
public string GetOtherConfigItem(string itemName)
{
return base.GetOtherConfigItem("hv_host_config_get_item", "@host_id", itemName);
}
public Dictionary<string, string> GetOtherConfig()
{
return base.GetOtherConfig("hv_host_config_get", "@host_id");
}
public static void SetEnabled(string hostUuid, string poolUuid, bool enabled)
{
string sqlStatement = "hv_host_set_enabled";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_uuid", hostUuid));
storedProcParamCollection.Add(new StoredProcParam("@pool_uuid", poolUuid));
storedProcParamCollection.Add(new StoredProcParam("@enabled", enabled));
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
internal static void SetStatus(int hostId, DwmStatus status)
{
string sqlStatement = "set_host_status";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_id", hostId));
storedProcParamCollection.Add(new StoredProcParam("@status", (int)status));
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
internal static void SetLastResult(int hostId, DwmStatus result)
{
string sqlStatement = "set_host_last_result";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_id", hostId));
storedProcParamCollection.Add(new StoredProcParam("@last_result", (int)result));
storedProcParamCollection.Add(new StoredProcParam("@last_result_time", DateTime.UtcNow));
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
public static void SetPoweredOffByWlb(int hostId, bool poweredOffByWlb)
{
string sqlStatement = "set_host_powered_off_by_wlb";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_id", hostId));
if (poweredOffByWlb)
{
storedProcParamCollection.Add(new StoredProcParam("@powered_off_by_wlb", 1));
}
else
{
storedProcParamCollection.Add(new StoredProcParam("@powered_off_by_wlb", 0));
}
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
internal bool HasRequiredStorage(DwmStorageRepositoryCollection requiredSRs)
{
bool result = true;
int num = 0;
while (requiredSRs != null && num < requiredSRs.Count)
{
if (!this.AvailableStorage.ContainsKey(requiredSRs[num].Id))
{
result = false;
break;
}
num++;
}
return result;
}
public static void DeleteHost(string hostUuid, string poolUuid)
{
if (!string.IsNullOrEmpty(hostUuid) && !string.IsNullOrEmpty(poolUuid))
{
Logger.Trace("Deleting host {0} by setting active to false", new object[]
{
hostUuid
});
int num = DwmPoolBase.UuidToId(poolUuid);
int num2 = DwmHost.UuidToId(hostUuid, num);
string sqlStatement = "delete_hv_host";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@pool_id", num));
storedProcParamCollection.Add(new StoredProcParam("@host_id", num2));
storedProcParamCollection.Add(new StoredProcParam("@tstamp", DateTime.UtcNow));
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
}
internal static DwmHost LoadWithMetrics(IDataReader reader)
{
string @string = DBAccess.GetString(reader, "uuid");
string string2 = DBAccess.GetString(reader, "name");
int @int = DBAccess.GetInt(reader, "poolid");
return new DwmHost(@string, string2, @int)
{
Id = DBAccess.GetInt(reader, "id"),
NumCpus = DBAccess.GetInt(reader, "num_cpus"),
NumVCpus = DBAccess.GetInt(reader, "num_vcpus"),
CpuSpeed = DBAccess.GetInt(reader, "cpu_speed"),
NumNics = DBAccess.GetInt(reader, "num_pifs"),
IsPoolMaster = DBAccess.GetBool(reader, "is_pool_master"),
PowerState = (PowerStatus)DBAccess.GetInt(reader, "power_state"),
ParticipatesInPowerManagement = DBAccess.GetBool(reader, "can_power"),
ExcludeFromPlacementRecommendations = DBAccess.GetBool(reader, "exclude_placements"),
ExcludeFromEvacuationRecommendations = DBAccess.GetBool(reader, "exclude_evacuations"),
Metrics =
{
FreeCPUs = DBAccess.GetInt(reader, "free_cpus"),
PotentialFreeMemory = DBAccess.GetInt64(reader, "potential_free_memory"),
FillOrder = DBAccess.GetInt(reader, "fill_order"),
TotalMemory = DBAccess.GetInt64(reader, "total_mem"),
FreeMemory = DBAccess.GetInt64(reader, "free_mem"),
NumHighFullContentionVCpus = DBAccess.GetInt(reader, "full_contention_count"),
NumHighConcurrencyHazardVCpus = DBAccess.GetInt(reader, "concurrency_hazard_count"),
NumHighPartialContentionVCpus = DBAccess.GetInt(reader, "partial_contention_count"),
NumHighFullrunVCpus = DBAccess.GetInt(reader, "fullrun_count"),
NumHighPartialRunVCpus = DBAccess.GetInt(reader, "partial_run_count"),
NumHighBlockedVCpus = DBAccess.GetInt(reader, "blocked_count"),
MetricsNow =
{
AverageFreeMemory = DBAccess.GetInt64(reader, "avg_free_mem_now", 0L),
AverageCpuUtilization = DBAccess.GetDouble(reader, "avg_cpu_now", 0.0),
AveragePifReadsPerSecond = DBAccess.GetDouble(reader, "avg_pif_read_now", 0.0),
AveragePifWritesPerSecond = DBAccess.GetDouble(reader, "avg_pif_write_now", 0.0),
AveragePbdReadsPerSecond = DBAccess.GetDouble(reader, "avg_pbd_read_now", 0.0),
AveragePbdWritesPerSecond = DBAccess.GetDouble(reader, "avg_pbd_write_now", 0.0),
AverageLoadAverage = DBAccess.GetDouble(reader, "avg_load_average_now", 0.0)
},
MetricsLast30Minutes =
{
AverageFreeMemory = DBAccess.GetInt64(reader, "avg_free_mem_30", 0L),
AverageCpuUtilization = DBAccess.GetDouble(reader, "avg_cpu_30", 0.0),
AveragePifReadsPerSecond = DBAccess.GetDouble(reader, "avg_pif_read_30", 0.0),
AveragePifWritesPerSecond = DBAccess.GetDouble(reader, "avg_pif_write_30", 0.0),
AveragePbdReadsPerSecond = DBAccess.GetDouble(reader, "avg_pbd_read_30", 0.0),
AveragePbdWritesPerSecond = DBAccess.GetDouble(reader, "avg_pbd_write_30", 0.0),
AverageLoadAverage = DBAccess.GetDouble(reader, "avg_load_average_30", 0.0)
},
MetricsYesterday =
{
AverageFreeMemory = DBAccess.GetInt64(reader, "avg_free_mem_yesterday", 0L),
AverageCpuUtilization = DBAccess.GetDouble(reader, "avg_cpu_yesterday", 0.0),
AveragePifReadsPerSecond = DBAccess.GetDouble(reader, "avg_pif_read_yesterday", 0.0),
AveragePifWritesPerSecond = DBAccess.GetDouble(reader, "avg_pif_write_yesterday", 0.0),
AveragePbdReadsPerSecond = DBAccess.GetDouble(reader, "avg_pbd_read_yesterday", 0.0),
AveragePbdWritesPerSecond = DBAccess.GetDouble(reader, "avg_pbd_write_yesterday", 0.0),
AverageLoadAverage = DBAccess.GetDouble(reader, "avg_load_average_yesterday", 0.0)
}
}
};
}
internal void LoadPif(IDataReader reader)
{
int @int = DBAccess.GetInt(reader, "pif_id");
string @string = DBAccess.GetString(reader, "pif_uuid");
string string2 = DBAccess.GetString(reader, "pif_name");
int int2 = DBAccess.GetInt(reader, "networkid");
int int3 = DBAccess.GetInt(reader, "poolid");
bool @bool = DBAccess.GetBool(reader, "is_management_interface");
DwmPif dwmPif = new DwmPif(@string, string2, int2, int3);
dwmPif.Id = @int;
dwmPif.IsManagementInterface = @bool;
this.PIFs.Add(dwmPif);
}
public void Save()
{
using (DBAccess dBAccess = new DBAccess())
{
this.Save(dBAccess);
}
}
public void Save(DBAccess db)
{
if (db != null)
{
try
{
string sqlStatement = "add_update_hv_host";
base.Id = db.ExecuteScalarInt(sqlStatement, new StoredProcParamCollection
{
new StoredProcParam("@uuid", base.Uuid),
new StoredProcParam("@name", (base.Name == null) ? string.Empty : base.Name),
new StoredProcParam("@pool_id", base.PoolId),
new StoredProcParam("@description", (base.Description == null) ? string.Empty : base.Description),
new StoredProcParam("@num_cpus", this._numCpus),
new StoredProcParam("@cpu_speed", this._cpuSpeed),
new StoredProcParam("@num_nics", this._numNics),
new StoredProcParam("@is_pool_master", this._isPoolMaster),
new StoredProcParam("@ip_address", this._ipAddress),
new StoredProcParam("@memory_overhead", this._memOverhead),
new StoredProcParam("@enabled", this._enabled),
new StoredProcParam("@power_state", (int)this._powerState)
});
StringBuilder stringBuilder = new StringBuilder();
string value = "BEGIN;\n";
string value2 = "COMMIT;\n";
stringBuilder.Append(value);
stringBuilder.Append(this.SaveHostStorageRelationships());
stringBuilder.Append(this.SaveHostVmRelationships());
stringBuilder.Append(this.SaveHostPifRelationships());
stringBuilder.Append(this.SaveHostPbdRelationships());
stringBuilder.Append(value2);
DwmBase.WriteData(db, stringBuilder);
}
catch (Exception ex)
{
Logger.Trace("Caught exception saving host {0} uuid={1}", new object[]
{
base.Name,
base.Uuid
});
Logger.LogException(ex);
}
return;
}
throw new DwmException("Cannot pass null DBAccess instance to Save", DwmErrorCode.NullReference, null);
}
private StringBuilder SaveHostStorageRelationships()
{
StringBuilder stringBuilder = new StringBuilder();
if (this._availableStorage != null && this._availableStorage.Count > 0)
{
StringBuilder stringBuilder2 = new StringBuilder();
for (int i = 0; i < this._availableStorage.Count; i++)
{
stringBuilder.AppendFormat("insert into hv_host_storage_repository (host_id, sr_id) select {0}, {1}\nwhere not exists (select id from hv_host_storage_repository where host_id={0} and sr_id={1});\n", base.Id, this._availableStorage[i].Id);
stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._availableStorage[i].Id);
}
stringBuilder.AppendFormat("delete from hv_host_storage_repository where host_id={0} and sr_id not in ({1});\n", base.Id, stringBuilder2.ToString());
}
else
{
stringBuilder.AppendFormat("delete from hv_host_storage_repository where host_id={0};\n", base.Id);
}
return stringBuilder;
}
private StringBuilder SaveHostVmRelationships()
{
StringBuilder stringBuilder = new StringBuilder();
if (this._listVMs != null && this._listVMs.Count > 0)
{
StringBuilder stringBuilder2 = new StringBuilder();
for (int i = 0; i < this._listVMs.Count; i++)
{
stringBuilder.AppendFormat("select * from add_update_host_vm( {0}, {1}, '{2}');\n", base.Id, this._listVMs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow));
stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listVMs[i].Id);
}
stringBuilder.AppendFormat("delete from host_vm where hostid={0} and vmid not in ({1});\nupdate host_vm_history set end_time='{2}' \nwhere host_id={0}\n and end_time is null\n and vm_id not in ({1});\n", base.Id, stringBuilder2.ToString(), Localization.DateTimeToSqlString(DateTime.UtcNow));
}
else
{
stringBuilder.AppendFormat("delete from host_vm where hostid={0};\nupdate host_vm_history set end_time='{1}' \nwhere host_id={0} and end_time is null;\n", base.Id, Localization.DateTimeToSqlString(DateTime.UtcNow));
}
return stringBuilder;
}
private StringBuilder SaveHostPifRelationships()
{
StringBuilder stringBuilder = new StringBuilder();
if (this._listPIFs != null && this._listPIFs.Count > 0)
{
StringBuilder stringBuilder2 = new StringBuilder();
for (int i = 0; i < this._listPIFs.Count; i++)
{
stringBuilder.AppendFormat("insert into hv_host_pif (hostid, pif_id, tstamp) select {0}, {1},'{2}'\nwhere not exists (select id from hv_host_pif where hostid={0} and pif_id={1});\n", base.Id, this._listPIFs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow));
stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listPIFs[i].Id);
}
stringBuilder.AppendFormat("delete from hv_host_pif where hostid={0} and pif_id not in ({1});\n", base.Id, stringBuilder2.ToString());
}
else
{
stringBuilder.AppendFormat("delete from hv_host_pif where hostid={0};\n", base.Id);
}
return stringBuilder;
}
private StringBuilder SaveHostPbdRelationships()
{
StringBuilder stringBuilder = new StringBuilder();
if (this._listPBDs != null && this._listPBDs.Count > 0)
{
StringBuilder stringBuilder2 = new StringBuilder();
for (int i = 0; i < this._listPBDs.Count; i++)
{
stringBuilder.AppendFormat("insert into hv_host_pbd (hostid, pbd_id, tstamp) select {0}, {1}, '{2}'\nwhere not exists (select id from hv_host_pbd where hostid={0} and pbd_id={1});\n", base.Id, this._listPBDs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow));
stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listPBDs[i].Id);
}
stringBuilder.AppendFormat("delete from hv_host_pbd where hostid={0} and pbd_id not in ({1});\n", base.Id, stringBuilder2.ToString());
}
else
{
stringBuilder.AppendFormat("delete from hv_host_pbd where hostid={0};\n", base.Id);
}
return stringBuilder;
}
public void Load()
{
string sql = "load_host_by_id";
this.InternalLoad(sql, new StoredProcParamCollection
{
new StoredProcParam("@host_id", base.Id)
});
}
internal void SimpleLoad()
{
string sql = "load_host_simple_by_id";
this.InternalLoad(sql, new StoredProcParamCollection
{
new StoredProcParam("@host_id", base.Id)
});
}
private void InternalLoad(string sql, StoredProcParamCollection parms)
{
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.UseTransaction = true;
using (IDataReader dataReader = dBAccess.ExecuteReader(sql, parms))
{
if (dataReader.Read())
{
if (string.IsNullOrEmpty(base.Uuid))
{
base.Uuid = DBAccess.GetString(dataReader, "uuid");
}
if (base.PoolId <= 0)
{
base.PoolId = DBAccess.GetInt(dataReader, "poolid");
}
base.Name = DBAccess.GetString(dataReader, "name");
base.Description = DBAccess.GetString(dataReader, "description");
this.NumCpus = DBAccess.GetInt(dataReader, "num_cpus");
this.CpuSpeed = DBAccess.GetInt(dataReader, "cpu_speed");
this.NumNics = DBAccess.GetInt(dataReader, "num_pifs");
this.IsPoolMaster = DBAccess.GetBool(dataReader, "is_pool_master");
this.Enabled = DBAccess.GetBool(dataReader, "enabled");
this.Metrics.FillOrder = DBAccess.GetInt(dataReader, "fill_order");
this.IPAddress = DBAccess.GetString(dataReader, "ip_address");
this.MemoryOverhead = DBAccess.GetInt64(dataReader, "memory_overhead");
base.Status = (DwmStatus)DBAccess.GetInt(dataReader, "status");
base.LastResult = (DwmStatus)DBAccess.GetInt(dataReader, "last_result");
base.LastResultTime = DBAccess.GetDateTime(dataReader, "last_result_time");
this.Metrics.TotalMemory = DBAccess.GetInt64(dataReader, "total_mem");
if (dataReader.NextResult())
{
while (dataReader.Read())
{
int @int = DBAccess.GetInt(dataReader, "hostid");
int int2 = DBAccess.GetInt(dataReader, "vmid");
string @string = DBAccess.GetString(dataReader, "name");
string string2 = DBAccess.GetString(dataReader, "uuid");
int int3 = DBAccess.GetInt(dataReader, "poolid");
DwmVirtualMachine dwmVirtualMachine = new DwmVirtualMachine(string2, @string, int3);
dwmVirtualMachine.Id = int2;
dwmVirtualMachine.Description = DBAccess.GetString(dataReader, "description");
dwmVirtualMachine.MinimumDynamicMemory = DBAccess.GetInt64(dataReader, "min_dynamic_memory");
dwmVirtualMachine.MaximumDynamicMemory = DBAccess.GetInt64(dataReader, "max_dynamic_memory");
dwmVirtualMachine.MinimumStaticMemory = DBAccess.GetInt64(dataReader, "min_static_memory");
dwmVirtualMachine.MaximumStaticMemory = DBAccess.GetInt64(dataReader, "max_static_memory");
dwmVirtualMachine.TargetMemory = DBAccess.GetInt64(dataReader, "target_memory");
dwmVirtualMachine.MemoryOverhead = DBAccess.GetInt64(dataReader, "memory_overhead");
dwmVirtualMachine.MinimumCpus = DBAccess.GetInt(dataReader, "min_cpus");
dwmVirtualMachine.HvMemoryMultiplier = DBAccess.GetDouble(dataReader, "hv_memory_multiplier");
dwmVirtualMachine.RequiredMemory = DBAccess.GetInt64(dataReader, "required_memory");
dwmVirtualMachine.IsControlDomain = DBAccess.GetBool(dataReader, "is_control_domain");
dwmVirtualMachine.IsAgile = DBAccess.GetBool(dataReader, "is_agile");
dwmVirtualMachine.DriversUpToDate = DBAccess.GetBool(dataReader, "drivers_up_to_date");
dwmVirtualMachine.Status = (DwmStatus)DBAccess.GetInt(dataReader, "status");
dwmVirtualMachine.LastResult = (DwmStatus)DBAccess.GetInt(dataReader, "last_result");
dwmVirtualMachine.LastResultTime = DBAccess.GetDateTime(dataReader, "last_result_time");
this.VirtualMachines.Add(dwmVirtualMachine);
}
}
}
}
}
}
public static DwmHost Load(string hostUuid, string poolUuid)
{
int poolId = DwmPoolBase.UuidToId(poolUuid);
int num = DwmHost.UuidToId(hostUuid, poolId);
if (num <= 0)
{
throw new DwmException("Invalid Host uuid", DwmErrorCode.InvalidParameter, null);
}
return DwmHost.Load(num);
}
public static DwmHost Load(int hostId)
{
if (hostId > 0)
{
DwmHost dwmHost = new DwmHost(hostId);
dwmHost.Load();
return dwmHost;
}
throw new DwmException("Invalid host ID", DwmErrorCode.InvalidParameter, null);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Data;
using System.Windows.Controls.Primitives;
using System.Reflection;
using System.Windows.Threading;
using System.ComponentModel;
using System.Windows.Shapes;
namespace MusicCollectionWPF.Infra
{
public class CustoSlider : Slider
{
private Canvas _Matrix;
private Image _Cursor;
private Popup _autoToolTip;
private TextBlock _TB;
private Line _B;
private DispatcherTimer _Time;
private int _ImobileCount=0;
public event EventHandler<EventArgs> DragStarted;
public event EventHandler<EventArgs> DragCompleted;
public CustoSlider()
: base()
{
NeedTP = false;
_Time = new DispatcherTimer();
_Time.Interval = TimeSpan.FromMilliseconds(200);
_Time.Tick += Tick;
_Time.IsEnabled = false;
}
private void UpdateToolTip(double xp)
{
_TB.Text = AutoToolTipContent.Convert(ConvertToValue(xp), this.Minimum, this.Maximum);
FrameworkElement ch = (this._autoToolTip.Child as FrameworkElement);
bool force = false;
if (ch.ActualWidth==0)
{
_TB.Visibility=Visibility.Hidden;
_autoToolTip.IsOpen = true;
force = true;
}
this._autoToolTip.HorizontalOffset = xp - ch.ActualWidth / 2;
if (force)
{
_autoToolTip.IsOpen = false;
_TB.Visibility = Visibility.Visible;
}
}
private void UpdateToolTip(Point p)
{
UpdateToolTip(p.X);
}
private Point _Current;
private void Tick(object s, EventArgs ea)
{
Point nCurrent = Mouse.GetPosition(_Matrix);
if (nCurrent == _Current)
{
_ImobileCount++;
if (_ImobileCount==3)
OnImmobile(nCurrent);
}
else
{
_ImobileCount = 0;
if (_autoToolTip.IsOpen)
{
UpdateToolTip(nCurrent);
}
}
_Current = nCurrent;
}
private void OnImmobile(Point p)
{
if (!this.NeedTP)
return;
if (this._Trig)
return;
UpdateToolTip(p);
_autoToolTip.IsOpen = true;
}
private void ME(object s, EventArgs ea)
{
_Time.IsEnabled = true;
}
private void ML(object s, MouseEventArgs ea)
{
_Time.IsEnabled = false;
_autoToolTip.IsOpen = false;
}
private double ConvertToValue(double delta)
{
return Math.Min(this.Maximum, Math.Max(this.Minimum, this.Minimum + (delta * (this.Maximum - this.Minimum)) / _Matrix.ActualWidth));
}
private double ConvertToRealValue(double delta)
{
return Math.Min(_Matrix.ActualWidth, Math.Max(0, delta));
}
public double LineThickness
{
get { return (double)GetValue(LineTicknessProperty); }
set { SetValue(LineTicknessProperty, value); }
}
public static readonly DependencyProperty LineTicknessProperty = DependencyProperty.Register(
"LineThickness",
typeof(double),
typeof(CustoSlider),
new FrameworkPropertyMetadata(2D));
public bool FillLineVisible
{
get { return (bool)GetValue(FillLineVisibleProperty); }
set { SetValue(FillLineVisibleProperty, value); }
}
public static readonly DependencyProperty TickLineBrushProperty = DependencyProperty.Register(
"TickLineBrush", typeof(Brush), typeof(CustoSlider));
public Brush TickLineBrush
{
get { return (Brush)GetValue(TickLineBrushProperty); }
set { SetValue(TickLineBrushProperty, value); }
}
public static readonly DependencyProperty FillLineVisibleProperty = DependencyProperty.Register(
"FillLineVisible",
typeof(bool),
typeof(CustoSlider),
new FrameworkPropertyMetadata(false));
public ISliderMultiConverter AutoToolTipContent
{
get { return (ISliderMultiConverter)GetValue(AutoToolTipContentProperty); }
set { SetValue(AutoToolTipContentProperty, value); }
}
public static readonly DependencyProperty AutoToolTipContentProperty = DependencyProperty.Register(
"AutoToolTipContent",
typeof(ISliderMultiConverter),
typeof(CustoSlider),
new FrameworkPropertyMetadata(null, AutoToolTipPropertyChangedCallback));
private static void AutoToolTipPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CustoSlider cs = d as CustoSlider;
cs.NeedTP = true;
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
try
{
_Matrix = (Canvas)GetTemplateChild("Matrix");
this.MouseDown += Canvas_MouseDown;
_Cursor = (Image)GetTemplateChild("Cursor");
_Cursor.PreviewMouseLeftButtonDown += Image_PreviewMouseDown;
_Cursor.MouseLeftButtonUp += Image_MouseUp;
_Cursor.MouseMove += Image_MouseMove;
_B = (Line)GetTemplateChild("Bar");
_B.MouseEnter += ME;
_B.MouseLeave += ML;
_autoToolTip = GetTemplateChild("AutoToolTip") as Popup;
_TB = (TextBlock)GetTemplateChild("AutoToolTipContentTextBox");
}
catch (Exception)
{
}
}
protected override void OnRender(DrawingContext dc)
{
if (TickPlacement != TickPlacement.None)
{
Size size = new Size(base.ActualWidth, base.ActualHeight);
double MidHeight = size.Height / 2;
double BigCircle = size.Height / 5;
double SmallCircle = (BigCircle * 2) / 3;
dc.DrawEllipse(FillLineVisible? this.TickLineBrush: this.BorderBrush, new Pen(), new Point(10, MidHeight), BigCircle, BigCircle);
dc.DrawEllipse(this.BorderBrush, new Pen(), new Point(size.Width + 10, MidHeight), BigCircle, BigCircle);
int tickCount = (int)((this.Maximum - this.Minimum) / this.TickFrequency) -1;
Double tickFrequencySize = (size.Width * this.TickFrequency / (this.Maximum - this.Minimum));
for (int i = 0; i <tickCount; i++)
{
dc.DrawEllipse(this.BorderBrush, new Pen(), new Point(10 + (i + 1) * tickFrequencySize, MidHeight),
SmallCircle, SmallCircle);
}
}
base.OnRender(dc);
}
private async void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
if (_Trig)
return;
Point p = Mouse.GetPosition(_Matrix);
_autoToolTip.IsOpen = false;
_Trig = true;
var target = ConvertToValue(p.X);
await this.SmoothSetAsync(ValueProperty, target, TimeSpan.FromSeconds(0.1));
Value = target;
OnThumbDragCompleted(new DragCompletedEventArgs(0, 0, false));
if (DragCompleted != null)
DragCompleted(this, new EventArgs());
_Trig = false;
}
private void Image_MouseMove(object sender, MouseEventArgs e)
{
if (!_Trig)
return;
OnThumbDragDelta(e);
}
private bool _Trig = false;
private void Image_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
_Cursor.CaptureMouse();
e.Handled = true;
_Trig = true;
_autoToolTip.IsOpen = false;
OnThumbDragStarted(e);
if (DragStarted != null)
DragStarted(this, new EventArgs());
}
private void Image_MouseUp(object sender, MouseButtonEventArgs e)
{
if (!_Trig)
return;
_Cursor.ReleaseMouseCapture();
e.Handled = true;
_Trig = false;
OnThumbDragCompleted(e);
if (DragCompleted != null)
DragCompleted(this, new EventArgs());
}
private void OnThumbDragStarted(MouseEventArgs e)
{
if (NeedTP)
{
_autoToolTip.IsOpen = true;
UpdateToolTip(e.GetPosition(_Matrix));
}
}
private void OnThumbDragDelta(MouseEventArgs e)
{
Point p = e.GetPosition(_Matrix);
Value = ConvertToValue(p.X);
if (NeedTP)
{
UpdateToolTip(e.GetPosition(_Matrix));
}
}
public bool InDrag
{
get{ return _Trig; }
}
private void OnThumbDragCompleted(MouseEventArgs e)
{
Point p = e.GetPosition(_Matrix);
Value = ConvertToValue(p.X);
if (NeedTP)
{
_autoToolTip.IsOpen = false;
}
}
private bool NeedTP
{
get;
set;
}
protected void OnPropertyChanged(string pn)
{
if (PropertyChanged == null)
return;
PropertyChanged(this, new PropertyChangedEventArgs(pn));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
|
//
// --------------------------------------------------------------------------
// Gurux Ltd
//
//
//
// Filename: $HeadURL$
//
// Version: $Revision$,
// $Date$
// $Author$
//
// Copyright (c) Gurux Ltd
//
//---------------------------------------------------------------------------
//
// DESCRIPTION
//
// This file is a part of Gurux Device Framework.
//
// Gurux Device Framework is Open Source software; you can redistribute it
// and/or modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; version 2 of the License.
// Gurux Device Framework is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
//
// More information of Gurux products: https://www.gurux.org
//
// This code is licensed under the GNU General Public License v2.
// Full text may be retrieved at http://www.gnu.org/licenses/gpl-2.0.txt
//---------------------------------------------------------------------------
using Gurux.DLMS.Internal;
using Gurux.DLMS.Plc;
using Gurux.DLMS.Plc.Enums;
using System;
using System.Collections.Generic;
namespace Gurux.DLMS
{
/// <summary>
/// PLC communication settings.
/// </summary>
public class GXPlcSettings
{
byte[] _systemTitle;
private GXDLMSSettings settings;
/// <summary>
/// Initial credit (IC) tells how many times the frame must be repeated. Maximum value is 7.
/// </summary>
public byte InitialCredit
{
get;
set;
}
/// <summary>
/// The current credit (CC) initial value equal to IC and automatically decremented by the MAC layer after each repetition.
/// Maximum value is 7.
/// </summary>
public byte CurrentCredit
{
get;
set;
}
/// <summary>
/// Delta credit (DC) is used by the system management application entity
/// (SMAE) of the Client for credit management, while it has no meaning for a Server or a REPEATER.
/// It represents the difference(IC-CC) of the last communication originated by the system identified by the DA address to the system identified by the SA address.
/// Maximum value is 3.
/// </summary>
public byte DeltaCredit
{
get;
set;
}
/// <summary>
/// IEC 61334-4-32 LLC uses 6 bytes long system title. IEC 61334-5-1 uses 8 bytes long system title so we can use the default one.
/// </summary>
public byte[] SystemTitle
{
get
{
if (settings != null && settings.InterfaceType != Enums.InterfaceType.Plc && settings.Cipher != null)
{
return settings.Cipher.SystemTitle;
}
return _systemTitle;
}
set
{
if (settings != null && settings.InterfaceType != Enums.InterfaceType.Plc && settings.Cipher != null)
{
settings.Cipher.SystemTitle = value;
}
_systemTitle = value;
}
}
/// <summary>
/// Source MAC address.
/// </summary>
public UInt16 MacSourceAddress
{
get;
set;
}
/// <summary>
/// Destination MAC address.
/// </summary>
public UInt16 MacDestinationAddress
{
get;
set;
}
/// <summary>
/// Response probability.
/// </summary>
public byte ResponseProbability
{
get;
set;
}
/// <summary>
/// Allowed time slots.
/// </summary>
public UInt16 AllowedTimeSlots
{
get;
set;
}
/// <summary>
/// Server saves client system title.
/// </summary>
public byte[] ClientSystemTitle
{
get;
set;
}
/// <summary>
/// Set default values.
/// </summary>
public void Reset()
{
InitialCredit = 7;
CurrentCredit = 7;
DeltaCredit = 0;
//New device addresses are used.
if (settings.InterfaceType == Enums.InterfaceType.Plc)
{
if (settings.IsServer)
{
MacSourceAddress = (UInt16)PlcSourceAddress.New;
MacDestinationAddress = (UInt16)PlcSourceAddress.Initiator;
}
else
{
MacSourceAddress = (UInt16)PlcSourceAddress.Initiator;
MacDestinationAddress = (UInt16)PlcDestinationAddress.AllPhysical;
}
}
else
{
if (settings.IsServer)
{
MacSourceAddress = (UInt16)PlcSourceAddress.New;
MacDestinationAddress = (UInt16)PlcHdlcSourceAddress.Initiator;
}
else
{
MacSourceAddress = (UInt16)PlcHdlcSourceAddress.Initiator;
MacDestinationAddress = (UInt16)PlcDestinationAddress.AllPhysical;
}
}
ResponseProbability = 100;
if (settings.InterfaceType == Enums.InterfaceType.Plc)
{
AllowedTimeSlots = 10;
}
else
{
AllowedTimeSlots = 0x14;
}
}
internal GXPlcSettings(GXDLMSSettings s)
{
settings = s;
Reset();
}
/// <summary>
/// Discover available PLC meters.
/// </summary>
/// <returns>Generated bytes.</returns>
public byte[] DiscoverRequest()
{
GXByteBuffer bb = new GXByteBuffer();
if (settings.InterfaceType != Enums.InterfaceType.Plc &&
settings.InterfaceType != Enums.InterfaceType.PlcHdlc)
{
throw new ArgumentOutOfRangeException("Invalid interface type.");
}
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
bb.Set(GXCommon.LLCSendBytes);
}
bb.SetUInt8((byte)Command.DiscoverRequest);
bb.SetUInt8(ResponseProbability);
bb.SetUInt16(AllowedTimeSlots);
//DiscoverReport initial credit
bb.SetUInt8(0);
// IC Equal credit
bb.SetUInt8(0);
int val = 0;
int clientAddress = settings.ClientAddress;
int serverAddress = settings.ServerAddress;
UInt16 da = settings.Plc.MacDestinationAddress;
UInt16 sa = settings.Plc.MacSourceAddress;
try
{
//10.4.6.4 Source and destination APs and addresses of CI-PDUs
//Client address is No-station in discoverReport.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
settings.Plc.InitialCredit = 0;
settings.Plc.CurrentCredit = 0;
settings.Plc.MacSourceAddress = 0xC01;
settings.Plc.MacDestinationAddress = 0xFFF;
settings.ClientAddress = 0x66;
// All-station
settings.ServerAddress = 0x33FF;
}
else
{
val = settings.Plc.InitialCredit << 5;
val |= settings.Plc.CurrentCredit << 2;
val |= settings.Plc.DeltaCredit & 0x3;
settings.Plc.MacSourceAddress = 0xC00;
settings.ClientAddress = 1;
settings.ServerAddress = 0;
}
return GXDLMS.GetMacFrame(settings, 0x13, (byte)val, bb);
}
finally
{
settings.ClientAddress = clientAddress;
settings.ServerAddress = serverAddress;
settings.Plc.MacDestinationAddress = da;
settings.Plc.MacSourceAddress = sa;
}
}
/// <summary>
/// Generates discover report.
/// </summary>
/// <param name="systemTitle">System title</param>
/// <param name="newMeter">Is this a new meter.</param>
/// <returns>Generated bytes.</returns>
public byte[] DiscoverReport(byte[] systemTitle, bool newMeter)
{
GXByteBuffer bb = new GXByteBuffer();
if (settings.InterfaceType != Enums.InterfaceType.Plc &&
settings.InterfaceType != Enums.InterfaceType.PlcHdlc)
{
throw new ArgumentOutOfRangeException("Invalid interface type.");
}
byte alarmDescription;
if (settings.InterfaceType == Enums.InterfaceType.Plc)
{
alarmDescription = (byte)(newMeter ? 1 : 0x82);
}
else
{
alarmDescription = 0;
}
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
bb.Set(GXCommon.LLCReplyBytes);
}
bb.SetUInt8((byte)Command.DiscoverReport);
bb.SetUInt8(1);
bb.Set(systemTitle);
if (alarmDescription != 0)
{
bb.SetUInt8(1);
}
bb.SetUInt8(alarmDescription);
int clientAddress = settings.ClientAddress;
int serverAddress = settings.ServerAddress;
UInt16 macSourceAddress = settings.Plc.MacSourceAddress;
UInt16 macTargetAddress = settings.Plc.MacDestinationAddress;
try
{
//10.4.6.4 Source and destination APs and addresses of CI-PDUs
//Client address is No-station in discoverReport.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
settings.Plc.MacDestinationAddress = (UInt16) PlcHdlcSourceAddress.Initiator;
}
else
{
settings.ClientAddress = 0;
settings.ServerAddress = 0xFD;
}
return GXDLMS.GetMacFrame(settings, 0x13, 0, bb);
}
finally
{
settings.ClientAddress = clientAddress;
settings.ServerAddress = serverAddress;
settings.Plc.MacSourceAddress = macSourceAddress;
settings.Plc.MacDestinationAddress = macTargetAddress;
}
}
/// <summary>
/// Parse discover reply.
/// </summary>
/// <param name="value"></param>
/// <returns>Array of system titles and alarm descriptor error code</returns>
public List<GXDLMSPlcMeterInfo> ParseDiscover(GXByteBuffer value, UInt16 sa, UInt16 da)
{
List<GXDLMSPlcMeterInfo> list = new List<GXDLMSPlcMeterInfo>();
byte count = value.GetUInt8();
for (int pos = 0; pos != count; ++pos)
{
GXDLMSPlcMeterInfo info = new GXDLMSPlcMeterInfo();
info.SourceAddress = sa;
info.DestinationAddress = da;
//Get System title.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
info.SystemTitle = new byte[8];
}
else
{
info.SystemTitle = new byte[6];
}
value.Get(info.SystemTitle);
// Alarm descriptor of the reporting system.
// Alarm-Descriptor presence flag
if (value.GetUInt8() != 0)
{
//Alarm-Descriptor
info.AlarmDescriptor = value.GetUInt8();
}
list.Add(info);
}
return list;
}
/// <summary>
/// Register PLC meters.
/// </summary>
/// <param name="initiatorSystemTitle">Active initiator systemtitle</param>
/// <param name="systemTitle"></param>
/// <returns>Generated bytes.</returns>
public byte[] RegisterRequest(byte[] initiatorSystemTitle, byte[] systemTitle)
{
GXByteBuffer bb = new GXByteBuffer();
//Control byte.
bb.SetUInt8((byte)Command.RegisterRequest);
bb.Set(initiatorSystemTitle);
//LEN
bb.SetUInt8(0x1);
bb.Set(systemTitle);
//MAC address.
bb.SetUInt16(MacSourceAddress);
int val = settings.Plc.InitialCredit << 5;
val |= settings.Plc.CurrentCredit << 2;
val |= settings.Plc.DeltaCredit & 0x3;
int clientAddress = settings.ClientAddress;
int serverAddress = settings.ServerAddress;
UInt16 macSourceAddress = settings.Plc.MacSourceAddress;
UInt16 macTargetAddress = settings.Plc.MacDestinationAddress;
try
{
//10.4.6.4 Source and destination APs and addresses of CI-PDUs
//Client address is No-station in discoverReport.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
settings.Plc.InitialCredit = 0;
settings.Plc.CurrentCredit = 0;
settings.Plc.MacSourceAddress = 0xC01;
settings.Plc.MacDestinationAddress = 0xFFF;
settings.ClientAddress = 0x66;
// All-station
settings.ServerAddress = 0x33FF;
}
else
{
settings.ClientAddress = 1;
settings.ServerAddress = 0;
settings.Plc.MacSourceAddress = 0xC00;
settings.Plc.MacDestinationAddress = 0xFFF;
}
return GXDLMS.GetMacFrame(settings, 0x13, (byte)val, bb);
}
finally
{
settings.ClientAddress = clientAddress;
settings.ServerAddress = serverAddress;
settings.Plc.MacSourceAddress = macSourceAddress;
settings.Plc.MacDestinationAddress = macTargetAddress;
}
}
/// <summary>
/// Parse register request.
/// </summary>
/// <param name="value"></param>
/// <returns>System title mac address.</returns>
public void ParseRegisterRequest(GXByteBuffer value)
{
//Get System title.
byte[] st;
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
st = new byte[8];
}
else
{
st = new byte[6];
}
value.Get(st);
byte count = value.GetUInt8();
for (int pos = 0; pos != count; ++pos)
{
//Get System title.
if (settings.InterfaceType == Enums.InterfaceType.PlcHdlc)
{
st = new byte[8];
}
else
{
st = new byte[6];
}
value.Get(st);
SystemTitle = st;
//MAC address.
MacSourceAddress = value.GetUInt16();
}
}
/// <summary>
/// Parse discover request.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public GXDLMSPlcRegister ParseDiscoverRequest(GXByteBuffer value)
{
GXDLMSPlcRegister ret = new GXDLMSPlcRegister();
ret.ResponseProbability = value.GetUInt8();
ret.AllowedTimeSlots = value.GetUInt16();
ret.DiscoverReportInitialCredit = value.GetUInt8();
ret.ICEqualCredit = value.GetUInt8();
return ret;
}
/// <summary>
/// Ping PLC meter.
/// </summary>
/// <returns>Generated bytes.</returns>
public byte[] PingRequest(byte[] systemTitle)
{
GXByteBuffer bb = new GXByteBuffer();
//Control byte.
bb.SetUInt8((byte)Command.PingRequest);
bb.Set(systemTitle);
return GXDLMS.GetMacFrame(settings, 0x13, 0, bb);
}
/// <summary>
/// Parse ping response.
/// </summary>
/// <param name="value">Received data.</param>
public byte[] ParsePing(GXByteBuffer value)
{
return value.SubArray(1, 6);
}
/// <summary>
/// Repear call request.
/// </summary>
/// <returns>Generated bytes.</returns>
public byte[] RepeaterCallRequest()
{
GXByteBuffer bb = new GXByteBuffer();
//Control byte.
bb.SetUInt8((byte)Command.RepeatCallRequest);
//MaxAdrMac.
bb.SetUInt16(0x63);
//Nb_Tslot_For_New
bb.SetUInt8(0);
//Reception-Threshold default value
bb.SetUInt8(0);
return GXDLMS.GetMacFrame(settings, 0x13, 0xFC, bb);
}
}
} |
//
// Microsoft.VisualBasic.* Test Cases
//
// Authors:
// Gert Driesen (drieseng@users.sourceforge.net)
//
// (c) 2006 Novell
//
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Globalization;
using System.IO;
using System.Text;
using NUnit.Framework;
namespace MonoTests.Microsoft.VisualBasic
{
/// <summary>
/// Test ICodeGenerator's GenerateCodeFromNamespace, along with a
/// minimal set CodeDom components.
/// </summary>
[TestFixture]
public class CodeGeneratorFromNamespaceTest : CodeGeneratorTestBase
{
CodeNamespace codeNamespace = null;
[SetUp]
public void Init ()
{
InitBase ();
codeNamespace = new CodeNamespace ();
}
protected override string Generate (CodeGeneratorOptions options)
{
StringWriter writer = new StringWriter ();
writer.NewLine = NewLine;
generator.GenerateCodeFromNamespace (codeNamespace, writer, options);
writer.Close ();
return writer.ToString ();
}
[Test]
[ExpectedException (typeof (NullReferenceException))]
public void NullNamespaceTest ()
{
codeNamespace = null;
Generate ();
}
[Test]
public void NullNamespaceNameTest ()
{
codeNamespace.Name = null;
Assert.AreEqual ("\n", Generate ());
}
[Test]
public void DefaultNamespaceTest ()
{
Assert.AreEqual ("\n", Generate ());
}
[Test]
public void SimpleNamespaceTest ()
{
codeNamespace.Name = "A";
Assert.AreEqual ("\nNamespace A\nEnd Namespace\n", Generate ());
}
[Test]
public void InvalidNamespaceTest ()
{
codeNamespace.Name = "A,B";
Assert.AreEqual ("\nNamespace A,B\nEnd Namespace\n", Generate ());
}
[Test]
public void CommentOnlyNamespaceTest ()
{
CodeCommentStatement comment = new CodeCommentStatement ("a");
codeNamespace.Comments.Add (comment);
Assert.AreEqual ("\n'a\n", Generate ());
}
[Test]
public void ImportsTest ()
{
codeNamespace.Imports.Add (new CodeNamespaceImport ("System"));
codeNamespace.Imports.Add (new CodeNamespaceImport ("System.Collections"));
Assert.AreEqual (string.Format(CultureInfo.InvariantCulture,
"Imports System{0}" +
"Imports System.Collections{0}" +
"{0}", NewLine), Generate (), "#1");
codeNamespace.Name = "A";
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"Imports System{0}" +
"Imports System.Collections{0}" +
"{0}" +
"Namespace A{0}" +
"End Namespace{0}", NewLine), Generate (), "#2");
codeNamespace.Name = null;
codeNamespace.Comments.Add (new CodeCommentStatement ("a"));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"Imports System{0}" +
"Imports System.Collections{0}" +
"{0}" +
"'a{0}", NewLine), Generate (), "#3");
codeNamespace.Name = "A";
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"Imports System{0}" +
"Imports System.Collections{0}" +
"{0}" +
"'a{0}" +
"Namespace A{0}" +
"End Namespace{0}", NewLine), Generate (), "#4");
}
[Test]
public void TypeTest ()
{
codeNamespace.Types.Add (new CodeTypeDeclaration ("Person"));
Assert.AreEqual (string.Format(CultureInfo.InvariantCulture,
"{0}" +
"{0}" +
"Public Class Person{0}" +
"End Class{0}", NewLine), Generate (), "#A1");
CodeGeneratorOptions options = new CodeGeneratorOptions ();
options.BlankLinesBetweenMembers = false;
Assert.AreEqual (string.Format(CultureInfo.InvariantCulture,
"{0}" +
"Public Class Person{0}" +
"End Class{0}", NewLine), Generate (options), "#A2");
codeNamespace.Name = "A";
Assert.AreEqual (string.Format(CultureInfo.InvariantCulture,
"{0}" +
"Namespace A{0}" +
" {0}" +
" Public Class Person{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#B1");
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace A{0}" +
" Public Class Person{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (options), "#B2");
}
[Test]
public void Type_TypeParameters ()
{
codeNamespace.Name = "SomeNS";
CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass");
codeNamespace.Types.Add (type);
type.TypeParameters.Add (new CodeTypeParameter ("T"));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#1");
type.TypeParameters.Add (new CodeTypeParameter ("As"));
type.TypeParameters.Add (new CodeTypeParameter ("New"));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T, As, New){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#2");
CodeTypeParameter typeParamR = new CodeTypeParameter ("R");
typeParamR.Constraints.Add (new CodeTypeReference (typeof (IComparable)));
type.TypeParameters.Add (typeParamR);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T, As, New, R As System.IComparable){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#3");
type.TypeParameters.Add (new CodeTypeParameter ("S"));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T, As, New, R As System.IComparable, S){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#4");
}
[Test]
public void Type_TypeParameters_Constraints ()
{
codeNamespace.Name = "SomeNS";
CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass");
codeNamespace.Types.Add (type);
CodeTypeParameter typeParamT = new CodeTypeParameter ("T");
typeParamT.Constraints.Add (new CodeTypeReference (typeof (IComparable)));
type.TypeParameters.Add (typeParamT);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T As System.IComparable){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#1");
typeParamT.Constraints.Add (new CodeTypeReference (typeof (ICloneable)));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable}}){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#2");
typeParamT.HasConstructorConstraint = true;
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable, New}}){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#3");
CodeTypeParameter typeParamS = new CodeTypeParameter ("S");
typeParamS.Constraints.Add (new CodeTypeReference (typeof (IDisposable)));
type.TypeParameters.Add (typeParamS);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#4");
CodeTypeParameter typeParamR = new CodeTypeParameter ("R");
typeParamR.HasConstructorConstraint = true;
type.TypeParameters.Add (typeParamR);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable, R As New){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#5");
}
[Test]
public void Type_TypeParameters_ConstructorConstraint ()
{
codeNamespace.Name = "SomeNS";
CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass");
codeNamespace.Types.Add (type);
CodeTypeParameter typeParam = new CodeTypeParameter ("T");
typeParam.HasConstructorConstraint = true;
type.TypeParameters.Add (typeParam);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass(Of T As New){0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate ());
}
[Test]
public void Method_TypeParameters ()
{
codeNamespace.Name = "SomeNS";
CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass");
codeNamespace.Types.Add (type);
CodeMemberMethod method = new CodeMemberMethod ();
method.Name = "SomeMethod";
type.Members.Add (method);
method.TypeParameters.Add (new CodeTypeParameter ("T"));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#1");
method.TypeParameters.Add (new CodeTypeParameter ("As"));
method.TypeParameters.Add (new CodeTypeParameter ("New"));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T, As, New)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#2");
CodeTypeParameter typeParamR = new CodeTypeParameter ("R");
typeParamR.Constraints.Add (new CodeTypeReference (typeof (IComparable)));
method.TypeParameters.Add (typeParamR);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T, As, New, R As System.IComparable)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#3");
method.TypeParameters.Add (new CodeTypeParameter ("S"));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T, As, New, R As System.IComparable, S)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#4");
}
[Test]
public void Method_TypeParameters_Constraints ()
{
codeNamespace.Name = "SomeNS";
CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass");
codeNamespace.Types.Add (type);
CodeMemberMethod method = new CodeMemberMethod ();
method.Name = "SomeMethod";
type.Members.Add (method);
CodeTypeParameter typeParamT = new CodeTypeParameter ("T");
typeParamT.Constraints.Add (new CodeTypeReference (typeof (IComparable)));
method.TypeParameters.Add (typeParamT);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T As System.IComparable)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#1");
typeParamT.Constraints.Add (new CodeTypeReference (typeof (ICloneable)));
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable}})(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#2");
typeParamT.HasConstructorConstraint = true;
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable, New}})(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#3");
CodeTypeParameter typeParamS = new CodeTypeParameter ("S");
typeParamS.Constraints.Add (new CodeTypeReference (typeof (IDisposable)));
method.TypeParameters.Add (typeParamS);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#4");
CodeTypeParameter typeParamR = new CodeTypeParameter ("R");
typeParamR.HasConstructorConstraint = true;
method.TypeParameters.Add (typeParamR);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T As {{System.IComparable, System.ICloneable, New}}, S As System.IDisposable, R As New)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate (), "#5");
}
[Test]
public void Method_TypeParameters_ConstructorConstraint ()
{
codeNamespace.Name = "SomeNS";
CodeTypeDeclaration type = new CodeTypeDeclaration ("SomeClass");
codeNamespace.Types.Add (type);
CodeMemberMethod method = new CodeMemberMethod ();
method.Name = "SomeMethod";
type.Members.Add (method);
CodeTypeParameter typeParam = new CodeTypeParameter ("T");
typeParam.HasConstructorConstraint = true;
method.TypeParameters.Add (typeParam);
Assert.AreEqual (string.Format (CultureInfo.InvariantCulture,
"{0}" +
"Namespace SomeNS{0}" +
" {0}" +
" Public Class SomeClass{0}" +
" {0}" +
" Private Sub SomeMethod(Of T As New)(){0}" +
" End Sub{0}" +
" End Class{0}" +
"End Namespace{0}", NewLine), Generate ());
}
}
}
|
/*
Copyright (C) 2007 Volker Berlin
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jeroen Frijters
jeroen@frijters.net
*/
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using java.awt.peer;
using java.awt.@event;
namespace ikvm.awt
{
internal class WindowsRobot : RobotPeer
{
Screen screen;
internal WindowsRobot(java.awt.GraphicsDevice device)
{
screen = ((NetGraphicsDevice)device).screen;
}
public void dispose()
{
}
public int getRGBPixel(int x, int y)
{
Bitmap bitmap = new Bitmap(1, 1);
Graphics g = Graphics.FromImage(bitmap);
g.CopyFromScreen( x, y, 0, 0, new Size(1,1));
g.Dispose();
Color color = bitmap.GetPixel(0,0);
bitmap.Dispose();
return color.ToArgb();
}
public int[] getRGBPixels(java.awt.Rectangle r)
{
int width = r.width;
int height = r.height;
Bitmap bitmap = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bitmap);
g.CopyFromScreen(r.x, r.y, 0, 0, new Size(width, height));
g.Dispose();
int[] pixels = new int[width * height];
for (int i = 0; i < width; i++)
{
for (int j = 0; j < height; j++)
{
pixels[i+j*width] = bitmap.GetPixel(i, j).ToArgb();
}
}
bitmap.Dispose();
return pixels;
}
private byte MapKeyCode(int keyCode)
{
//TODO there need a keymap for some special chars
//http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/WinUI/WindowsUserInterface/UserInput/VirtualKeyCodes.asp
switch (keyCode)
{
case KeyEvent.VK_DELETE:
return VK_DELETE;
default:
return (byte)keyCode;
}
}
public void keyPress(int keycode)
{
keybd_event(MapKeyCode(keycode), 0, KEYEVENTF_KEYDOWN, IntPtr.Zero);
}
public void keyRelease(int keycode)
{
keybd_event(MapKeyCode(keycode), 0, KEYEVENTF_KEYUP, IntPtr.Zero);
}
public void mouseMove(int x, int y)
{
Cursor.Position = new Point(x,y);
}
public void mousePress(int button)
{
int dwFlags = 0;
switch (button)
{
case InputEvent.BUTTON1_MASK:
dwFlags |= MOUSEEVENTF_LEFTDOWN;
break;
case InputEvent.BUTTON2_MASK:
dwFlags |= MOUSEEVENTF_MIDDLEDOWN;
break;
case InputEvent.BUTTON3_MASK:
dwFlags |= MOUSEEVENTF_RIGHTDOWN;
break;
}
mouse_event(dwFlags, 0, 0, 0, IntPtr.Zero);
}
public void mouseRelease(int button)
{
int dwFlags = 0;
switch (button)
{
case InputEvent.BUTTON1_MASK:
dwFlags |= MOUSEEVENTF_LEFTUP;
break;
case InputEvent.BUTTON2_MASK:
dwFlags |= MOUSEEVENTF_MIDDLEUP;
break;
case InputEvent.BUTTON3_MASK:
dwFlags |= MOUSEEVENTF_RIGHTUP;
break;
}
mouse_event(dwFlags, 0, 0, 0, IntPtr.Zero);
}
public void mouseWheel(int wheel)
{
mouse_event(0, 0, 0, wheel, IntPtr.Zero);
}
[DllImport("user32.dll")]
private static extern void keybd_event(byte vk, byte scan, int flags, IntPtr extrainfo);
private const int KEYEVENTF_KEYDOWN = 0x0000;
private const int KEYEVENTF_KEYUP = 0x0002;
[DllImport("user32.dll")]
private static extern void mouse_event(
int dwFlags, // motion and click options
int dx, // horizontal position or change
int dy, // vertical position or change
int dwData, // wheel movement
IntPtr dwExtraInfo // application-defined information
);
private const int MOUSEEVENTF_LEFTDOWN = 0x0002;
private const int MOUSEEVENTF_LEFTUP = 0x0004;
private const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
private const int MOUSEEVENTF_RIGHTUP = 0x0010;
private const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
private const int MOUSEEVENTF_MIDDLEUP = 0x0040;
private const int VK_BACK = 0x08;
private const int VK_TAB = 0x09;
/*
* 0x0A - 0x0B : reserved
*/
private const int VK_CLEAR = 0x0C;
private const int VK_RETURN = 0x0D;
private const int VK_SHIFT = 0x10;
private const int VK_CONTROL = 0x11;
private const int VK_MENU = 0x12;
private const int VK_PAUSE = 0x13;
private const int VK_CAPITAL = 0x14;
private const int VK_KANA = 0x15;
private const int VK_HANGEUL = 0x15; /* old name - should be here for compatibility */
private const int VK_HANGUL = 0x15;
private const int VK_JUNJA = 0x17;
private const int VK_FINAL = 0x18;
private const int VK_HANJA = 0x19;
private const int VK_KANJI = 0x19;
private const int VK_ESCAPE = 0x1B;
private const int VK_CONVERT = 0x1C;
private const int VK_NONCONVERT = 0x1D;
private const int VK_ACCEPT = 0x1E;
private const int VK_MODECHANGE = 0x1F;
private const int VK_SPACE = 0x20;
private const int VK_PRIOR = 0x21;
private const int VK_NEXT = 0x22;
private const int VK_END = 0x23;
private const int VK_HOME = 0x24;
private const int VK_LEFT = 0x25;
private const int VK_UP = 0x26;
private const int VK_RIGHT = 0x27;
private const int VK_DOWN = 0x28;
private const int VK_SELECT = 0x29;
private const int VK_PRINT = 0x2A;
private const int VK_EXECUTE = 0x2B;
private const int VK_SNAPSHOT = 0x2C;
private const int VK_INSERT = 0x2D;
private const int VK_DELETE = 0x2E;
private const int VK_HELP = 0x2F;
/*
* VK_0 - VK_9 are the same as ASCII '0' - '9' (0x30 - 0x39)
* 0x40 : unassigned
* VK_A - VK_Z are the same as ASCII 'A' - 'Z' (0x41 - 0x5A)
*/
private const int VK_LWIN = 0x5B;
private const int VK_RWIN = 0x5C;
private const int VK_APPS = 0x5D;
/*
* 0x5E : reserved
*/
private const int VK_SLEEP = 0x5F;
private const int VK_NUMPAD0 = 0x60;
private const int VK_NUMPAD1 = 0x61;
private const int VK_NUMPAD2 = 0x62;
private const int VK_NUMPAD3 = 0x63;
private const int VK_NUMPAD4 = 0x64;
private const int VK_NUMPAD5 = 0x65;
private const int VK_NUMPAD6 = 0x66;
private const int VK_NUMPAD7 = 0x67;
private const int VK_NUMPAD8 = 0x68;
private const int VK_NUMPAD9 = 0x69;
private const int VK_MULTIPLY = 0x6A;
private const int VK_ADD = 0x6B;
private const int VK_SEPARATOR = 0x6C;
private const int VK_SUBTRACT = 0x6D;
private const int VK_DECIMAL = 0x6E;
private const int VK_DIVIDE = 0x6F;
private const int VK_F1 = 0x70;
private const int VK_F2 = 0x71;
private const int VK_F3 = 0x72;
private const int VK_F4 = 0x73;
private const int VK_F5 = 0x74;
private const int VK_F6 = 0x75;
private const int VK_F7 = 0x76;
private const int VK_F8 = 0x77;
private const int VK_F9 = 0x78;
private const int VK_F10 = 0x79;
private const int VK_F11 = 0x7A;
private const int VK_F12 = 0x7B;
private const int VK_F13 = 0x7C;
private const int VK_F14 = 0x7D;
private const int VK_F15 = 0x7E;
private const int VK_F16 = 0x7F;
private const int VK_F17 = 0x80;
private const int VK_F18 = 0x81;
private const int VK_F19 = 0x82;
private const int VK_F20 = 0x83;
private const int VK_F21 = 0x84;
private const int VK_F22 = 0x85;
private const int VK_F23 = 0x86;
private const int VK_F24 = 0x87;
/*
* 0x88 - 0x8F : unassigned
*/
private const int VK_NUMLOCK = 0x90;
private const int VK_SCROLL = 0x91;
/*
* NEC PC-9800 kbd definitions
*/
private const int VK_OEM_NEC_EQUAL = 0x92; // '=' key on numpad
/*
* Fujitsu/OASYS kbd definitions
*/
private const int VK_OEM_FJ_JISHO = 0x92; // 'Dictionary' key
private const int VK_OEM_FJ_MASSHOU= 0x93; // 'Unregister word' key
private const int VK_OEM_FJ_TOUROKU= 0x94; // 'Register word' key
private const int VK_OEM_FJ_LOYA = 0x95; // 'Left OYAYUBI' key
private const int VK_OEM_FJ_ROYA = 0x96; // 'Right OYAYUBI' key
/*
* 0x97 - 0x9F : unassigned
*/
/*
* VK_L* & VK_R* - left and right Alt, Ctrl and Shift virtual keys.
* Used only as parameters to GetAsyncKeyState() and GetKeyState().
* No other API or message will distinguish left and right keys in this way.
*/
private const int VK_LSHIFT = 0xA0;
private const int VK_RSHIFT = 0xA1;
private const int VK_LCONTROL = 0xA2;
private const int VK_RCONTROL = 0xA3;
private const int VK_LMENU = 0xA4;
private const int VK_RMENU = 0xA5;
private const int VK_BROWSER_BACK = 0xA6;
private const int VK_BROWSER_FORWARD = 0xA7;
private const int VK_BROWSER_REFRESH = 0xA8;
private const int VK_BROWSER_STOP = 0xA9;
private const int VK_BROWSER_SEARCH = 0xAA;
private const int VK_BROWSER_FAVORITES = 0xAB;
private const int VK_BROWSER_HOME = 0xAC;
private const int VK_VOLUME_MUTE = 0xAD;
private const int VK_VOLUME_DOWN = 0xAE;
private const int VK_VOLUME_UP = 0xAF;
private const int VK_MEDIA_NEXT_TRACK = 0xB0;
private const int VK_MEDIA_PREV_TRACK = 0xB1;
private const int VK_MEDIA_STOP = 0xB2;
private const int VK_MEDIA_PLAY_PAUSE = 0xB3;
private const int VK_LAUNCH_MAIL = 0xB4;
private const int VK_LAUNCH_MEDIA_SELECT= 0xB5;
private const int VK_LAUNCH_APP1 = 0xB6;
private const int VK_LAUNCH_APP2 = 0xB7;
/*
* 0xB8 - 0xB9 : reserved
*/
private const int VK_OEM_1 = 0xBA; // ';:' for US
private const int VK_OEM_PLUS = 0xBB; // '+' any country
private const int VK_OEM_COMMA = 0xBC; // ',' any country
private const int VK_OEM_MINUS = 0xBD; // '-' any country
private const int VK_OEM_PERIOD = 0xBE; // '.' any country
private const int VK_OEM_2 = 0xBF; // '/?' for US
private const int VK_OEM_3 = 0xC0; // '`~' for US
/*
* 0xC1 - 0xD7 : reserved
*/
/*
* 0xD8 - 0xDA : unassigned
*/
private const int VK_OEM_4 = 0xDB; // '[{' for US
private const int VK_OEM_5 = 0xDC; // '\|' for US
private const int VK_OEM_6 = 0xDD; // ']}' for US
private const int VK_OEM_7 = 0xDE; // ''"' for US
private const int VK_OEM_8 = 0xDF;
/*
* 0xE0 : reserved
*/
/*
* Various extended or enhanced keyboards
*/
private const int VK_OEM_AX = 0xE1; // 'AX' key on Japanese AX kbd
private const int VK_OEM_102 = 0xE2; // "<>" or "\|" on RT 102-key kbd.
private const int VK_ICO_HELP = 0xE3; // Help key on ICO
private const int VK_ICO_00 = 0xE4; // 00 key on ICO
/*
* 0xE8 : unassigned
*/
/*
* Nokia/Ericsson definitions
*/
private const int VK_OEM_RESET = 0xE9;
private const int VK_OEM_JUMP = 0xEA;
private const int VK_OEM_PA1 = 0xEB;
private const int VK_OEM_PA2 = 0xEC;
private const int VK_OEM_PA3 = 0xED;
private const int VK_OEM_WSCTRL = 0xEE;
private const int VK_OEM_CUSEL = 0xEF;
private const int VK_OEM_ATTN = 0xF0;
private const int VK_OEM_FINISH = 0xF1;
private const int VK_OEM_COPY = 0xF2;
private const int VK_OEM_AUTO = 0xF3;
private const int VK_OEM_ENLW = 0xF4;
private const int VK_OEM_BACKTAB = 0xF5;
private const int VK_ATTN = 0xF6;
private const int VK_CRSEL = 0xF7;
private const int VK_EXSEL = 0xF8;
private const int VK_EREOF = 0xF9;
private const int VK_PLAY = 0xFA;
private const int VK_ZOOM = 0xFB;
private const int VK_NONAME = 0xFC;
private const int VK_PA1 = 0xFD;
private const int VK_OEM_CLEAR = 0xFE;
}
} |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using Sudoku.Areas.HelpPage.Models;
namespace Sudoku.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
|
using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace WeifenLuo.WinFormsUI.Docking
{
#region DockPanelSkin classes
/// <summary>
/// The skin to use when displaying the DockPanel.
/// The skin allows custom gradient color schemes to be used when drawing the
/// DockStrips and Tabs.
/// </summary>
[TypeConverter(typeof(DockPanelSkinConverter))]
public class DockPanelSkin
{
private AutoHideStripSkin m_autoHideStripSkin;
private DockPaneStripSkin m_dockPaneStripSkin;
public DockPanelSkin()
{
m_autoHideStripSkin = new AutoHideStripSkin();
m_dockPaneStripSkin = new DockPaneStripSkin();
}
/// <summary>
/// The skin used to display the auto hide strips and tabs.
/// </summary>
public AutoHideStripSkin AutoHideStripSkin
{
get { return m_autoHideStripSkin; }
set { m_autoHideStripSkin = value; }
}
/// <summary>
/// The skin used to display the Document and ToolWindow style DockStrips and Tabs.
/// </summary>
public DockPaneStripSkin DockPaneStripSkin
{
get { return m_dockPaneStripSkin; }
set { m_dockPaneStripSkin = value; }
}
}
/// <summary>
/// The skin used to display the auto hide strip and tabs.
/// </summary>
[TypeConverter(typeof(AutoHideStripConverter))]
public class AutoHideStripSkin
{
private DockPanelGradient m_dockStripGradient;
private TabGradient m_TabGradient;
public AutoHideStripSkin()
{
m_dockStripGradient = new DockPanelGradient();
m_dockStripGradient.StartColor = SystemColors.ControlLight;
m_dockStripGradient.EndColor = SystemColors.ControlLight;
m_TabGradient = new TabGradient();
m_TabGradient.TextColor = SystemColors.ControlDarkDark;
}
/// <summary>
/// The gradient color skin for the DockStrips.
/// </summary>
public DockPanelGradient DockStripGradient
{
get { return m_dockStripGradient; }
set { m_dockStripGradient = value; }
}
/// <summary>
/// The gradient color skin for the Tabs.
/// </summary>
public TabGradient TabGradient
{
get { return m_TabGradient; }
set { m_TabGradient = value; }
}
}
/// <summary>
/// The skin used to display the document and tool strips and tabs.
/// </summary>
[TypeConverter(typeof(DockPaneStripConverter))]
public class DockPaneStripSkin
{
private DockPaneStripGradient m_DocumentGradient;
private DockPaneStripToolWindowGradient m_ToolWindowGradient;
public DockPaneStripSkin()
{
m_DocumentGradient = new DockPaneStripGradient();
m_DocumentGradient.DockStripGradient.StartColor = SystemColors.Control;
m_DocumentGradient.DockStripGradient.EndColor = SystemColors.Control;
m_DocumentGradient.ActiveTabGradient.StartColor = SystemColors.ControlLightLight;
m_DocumentGradient.ActiveTabGradient.EndColor = SystemColors.ControlLightLight;
m_DocumentGradient.InactiveTabGradient.StartColor = SystemColors.ControlLight;
m_DocumentGradient.InactiveTabGradient.EndColor = SystemColors.ControlLight;
m_ToolWindowGradient = new DockPaneStripToolWindowGradient();
m_ToolWindowGradient.DockStripGradient.StartColor = SystemColors.ControlLight;
m_ToolWindowGradient.DockStripGradient.EndColor = SystemColors.ControlLight;
m_ToolWindowGradient.ActiveTabGradient.StartColor = SystemColors.Control;
m_ToolWindowGradient.ActiveTabGradient.EndColor = SystemColors.Control;
m_ToolWindowGradient.InactiveTabGradient.StartColor = Color.Transparent;
m_ToolWindowGradient.InactiveTabGradient.EndColor = Color.Transparent;
m_ToolWindowGradient.InactiveTabGradient.TextColor = SystemColors.ControlDarkDark;
m_ToolWindowGradient.ActiveCaptionGradient.StartColor = SystemColors.GradientActiveCaption;
m_ToolWindowGradient.ActiveCaptionGradient.EndColor = SystemColors.ActiveCaption;
m_ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical;
m_ToolWindowGradient.ActiveCaptionGradient.TextColor = SystemColors.ActiveCaptionText;
m_ToolWindowGradient.InactiveCaptionGradient.StartColor = SystemColors.GradientInactiveCaption;
m_ToolWindowGradient.InactiveCaptionGradient.EndColor = SystemColors.GradientInactiveCaption;
m_ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical;
m_ToolWindowGradient.InactiveCaptionGradient.TextColor = SystemColors.ControlText;
}
/// <summary>
/// The skin used to display the Document style DockPane strip and tab.
/// </summary>
public DockPaneStripGradient DocumentGradient
{
get { return m_DocumentGradient; }
set { m_DocumentGradient = value; }
}
/// <summary>
/// The skin used to display the ToolWindow style DockPane strip and tab.
/// </summary>
public DockPaneStripToolWindowGradient ToolWindowGradient
{
get { return m_ToolWindowGradient; }
set { m_ToolWindowGradient = value; }
}
}
/// <summary>
/// The skin used to display the DockPane ToolWindow strip and tab.
/// </summary>
[TypeConverter(typeof(DockPaneStripGradientConverter))]
public class DockPaneStripToolWindowGradient : DockPaneStripGradient
{
private TabGradient m_activeCaptionGradient;
private TabGradient m_inactiveCaptionGradient;
public DockPaneStripToolWindowGradient()
{
m_activeCaptionGradient = new TabGradient();
m_inactiveCaptionGradient = new TabGradient();
}
/// <summary>
/// The skin used to display the active ToolWindow caption.
/// </summary>
public TabGradient ActiveCaptionGradient
{
get { return m_activeCaptionGradient; }
set { m_activeCaptionGradient = value; }
}
/// <summary>
/// The skin used to display the inactive ToolWindow caption.
/// </summary>
public TabGradient InactiveCaptionGradient
{
get { return m_inactiveCaptionGradient; }
set { m_inactiveCaptionGradient = value; }
}
}
/// <summary>
/// The skin used to display the DockPane strip and tab.
/// </summary>
[TypeConverter(typeof(DockPaneStripGradientConverter))]
public class DockPaneStripGradient
{
private DockPanelGradient m_dockStripGradient;
private TabGradient m_activeTabGradient;
private TabGradient m_inactiveTabGradient;
public DockPaneStripGradient()
{
m_dockStripGradient = new DockPanelGradient();
m_activeTabGradient = new TabGradient();
m_inactiveTabGradient = new TabGradient();
}
/// <summary>
/// The gradient color skin for the DockStrip.
/// </summary>
public DockPanelGradient DockStripGradient
{
get { return m_dockStripGradient; }
set { m_dockStripGradient = value; }
}
/// <summary>
/// The skin used to display the active DockPane tabs.
/// </summary>
public TabGradient ActiveTabGradient
{
get { return m_activeTabGradient; }
set { m_activeTabGradient = value; }
}
/// <summary>
/// The skin used to display the inactive DockPane tabs.
/// </summary>
public TabGradient InactiveTabGradient
{
get { return m_inactiveTabGradient; }
set { m_inactiveTabGradient = value; }
}
}
/// <summary>
/// The skin used to display the dock pane tab
/// </summary>
[TypeConverter(typeof(DockPaneTabGradientConverter))]
public class TabGradient : DockPanelGradient
{
private Color m_textColor;
public TabGradient()
{
m_textColor = SystemColors.ControlText;
}
/// <summary>
/// The text color.
/// </summary>
[DefaultValue(typeof(SystemColors), "ControlText")]
public Color TextColor
{
get { return m_textColor; }
set { m_textColor = value; }
}
}
/// <summary>
/// The gradient color skin.
/// </summary>
[TypeConverter(typeof(DockPanelGradientConverter))]
public class DockPanelGradient
{
private Color m_startColor;
private Color m_endColor;
private LinearGradientMode m_linearGradientMode;
public DockPanelGradient()
{
m_startColor = SystemColors.Control;
m_endColor = SystemColors.Control;
m_linearGradientMode = LinearGradientMode.Horizontal;
}
/// <summary>
/// The beginning gradient color.
/// </summary>
[DefaultValue(typeof(SystemColors), "Control")]
public Color StartColor
{
get { return m_startColor; }
set { m_startColor = value; }
}
/// <summary>
/// The ending gradient color.
/// </summary>
[DefaultValue(typeof(SystemColors), "Control")]
public Color EndColor
{
get { return m_endColor; }
set { m_endColor = value; }
}
/// <summary>
/// The gradient mode to display the colors.
/// </summary>
[DefaultValue(LinearGradientMode.Horizontal)]
public LinearGradientMode LinearGradientMode
{
get { return m_linearGradientMode; }
set { m_linearGradientMode = value; }
}
}
#endregion DockPanelSkin classes
#region Converters
public class DockPanelSkinConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(DockPanelSkin))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(String) && value is DockPanelSkin)
{
return "DockPanelSkin";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
public class DockPanelGradientConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(DockPanelGradient))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(String) && value is DockPanelGradient)
{
return "DockPanelGradient";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
public class AutoHideStripConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(AutoHideStripSkin))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(String) && value is AutoHideStripSkin)
{
return "AutoHideStripSkin";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
public class DockPaneStripConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(DockPaneStripSkin))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(String) && value is DockPaneStripSkin)
{
return "DockPaneStripSkin";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
public class DockPaneStripGradientConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(DockPaneStripGradient))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(String) && value is DockPaneStripGradient)
{
return "DockPaneStripGradient";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
public class DockPaneTabGradientConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType == typeof(TabGradient))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(String) && value is TabGradient)
{
return "DockPaneTabGradient";
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
#endregion Converters
} |
/*
Stuart Bowman 2016
This class contains the graph nodes themselves, as well as helper functions for use by the generation class
to better facilitate evaluation and breeding. It also contains the class definition for the nodes themselves,
as well as the A* search implementation used by the genetic algorithm to check if a path can be traced between
two given points on the maze.
*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Graph
{
public Dictionary<int, Node> nodes;
float AStarPathSuccess = 0.0f;//fraction of samples that could be maped to nodes and completed with AStar
float AStarAvgPathLength = 0.0f;//average path length of successful paths
public float getAStarPathSuccess() { return AStarPathSuccess; }
public float getAStarAvgPathLength() { return AStarAvgPathLength; }
public float getCompositeScore() { return AStarPathSuccess; }//a weighted, composite score of all evaluated attributes of this graph
public int newNodeStartingID = 0;
public Graph(int startingID)
{
newNodeStartingID = startingID;
nodes = new Dictionary<int, Node>();
}
public Graph(List<GameObject> floors, List<GameObject> walls, int initNumNodes = 20)
{
nodes = new Dictionary<int, Node>();
for (int i = 0; i < initNumNodes; i++)
{
int rndTile = Random.Range(0, floors.Count);
//get the 2d bounding area for any floor tile
MeshCollider mc = floors[rndTile].GetComponent<MeshCollider>();
Vector2 xyWorldSpaceBoundsBottomLeft = new Vector2(mc.bounds.center.x - mc.bounds.size.x/2, mc.bounds.center.z - mc.bounds.size.z/2);
Vector2 rndPosInTile = new Vector2(Random.Range(0, mc.bounds.size.x), Random.Range(0, mc.bounds.size.z));
Vector2 rndWorldPos = xyWorldSpaceBoundsBottomLeft + rndPosInTile;
Node n = addNewNode(rndWorldPos);
}
connectAllNodes();
}
public Graph(Graph g)//deep copy constructor
{
nodes = new Dictionary<int, Node>();
//deep copy
foreach (KeyValuePair<int, Node> entry in g.nodes)
{
//deep copy the node with the best score
bool inherited = entry.Value.isNodeInheritedFromParent();
Node currentNode = new Node(new Vector2(entry.Value.pos.x, entry.Value.pos.y), entry.Value.ID, inherited);
//don't bother copying the A* and heuristic stuff for each node, it's just going to be re-crunched later
nodes.Add(currentNode.ID, currentNode);
}
AStarPathSuccess = g.getAStarPathSuccess();
AStarAvgPathLength = g.getAStarAvgPathLength();
}
public static float normDistRand(float mean, float stdDev)
{
float u1 = Random.Range(0, 1.0f);
float u2 = Random.Range(0, 1.0f);
float randStdNormal = Mathf.Sqrt(-2.0f * Mathf.Log(u1) * Mathf.Sin(2.0f * 3.14159f * u2));
return mean + stdDev * randStdNormal;
}
public string getSummary()
{
string result = "";
result += nodes.Count + "\tNodes\t(" + getNumOfNewlyAddedNodes() + " new)\n";
result += getAStarPathSuccess() * 100 + "%\tA* Satisfaction\n";
result += getAStarAvgPathLength() + "\tUnit avg. A* Path\n";
return result;
}
int getNumOfNewlyAddedNodes()
{
int result = 0;
foreach (KeyValuePair<int, Node> entry in nodes)
{
if (entry.Value.isNodeInheritedFromParent() == false)
result++;
}
return result;
}
public void connectAllNodes()
{
foreach (KeyValuePair<int,Node> entry in nodes)
{
foreach (KeyValuePair<int, Node> entry2 in nodes)
{
if (entry.Value != entry2.Value)
{
if (!Physics.Linecast(new Vector3(entry.Value.pos.x, 2, entry.Value.pos.y), new Vector3(entry2.Value.pos.x, 2, entry2.Value.pos.y)))
{
entry.Value.connectTo(entry2.Value);
}
}
}
}
}
public int getFirstUnusedID()
{
for (int i = 0; i < nodes.Count; i++)
{
if (!nodes.ContainsKey(i))
return i;
}
return nodes.Count;
}
public int getMaxID()
{
int temp = 0;
foreach (KeyValuePair<int, Node> entry in nodes)
{
if (entry.Value.ID > temp) temp = entry.Value.ID;
}
if (temp < newNodeStartingID)
return newNodeStartingID;
return temp;
}
public class Node
{
public int ID;
public Vector2 pos;
public List<Node> connectedNodes;
bool inheritedFromParent;
public Node Ancestor;//used in A*
public float g, h;//public values for temporary use during searching and heuristic analysis
public float f
{
get {return g + h; }
private set { }
}
public bool isNodeInheritedFromParent()
{
return inheritedFromParent;
}
public Node(Vector2 position, int id, bool inherited)
{
connectedNodes = new List<Node>();
pos = position;
ID = id;
inheritedFromParent = inherited;
}
public void connectTo(Node node)
{
if (!connectedNodes.Contains(node))
{
connectedNodes.Add(node);
if (!node.connectedNodes.Contains(this))
{
node.connectedNodes.Add(this);
}
}
}
public void disconnectFrom(Node n)
{
for (int i = 0; i < connectedNodes.Count; i++)
{
if (connectedNodes[i] == n)
n.connectedNodes.Remove(this);
}
connectedNodes.Remove(n);
}
}
public Node addNewNode(Vector2 pos)
{
int newID = this.getMaxID()+1;//get the new id from the maxID property
Node tempNode = new Node(pos, newID, false);
nodes.Add(newID, tempNode);
return tempNode;
}
public Node addNewNode(Vector2 pos, int ID)
{
Node tempNode = new Node(pos, ID, false);
nodes.Add(ID, tempNode);
return tempNode;
}
public Node addNewNode(Vector2 pos, int ID, bool inherited)
{
Node tempNode = new Node(pos, ID, inherited);
nodes.Add(ID, tempNode);
return tempNode;
}
public void removeNode(int ID)
{
Node nodeToRemove = nodes[ID];
foreach (Node n in nodeToRemove.connectedNodes)
{
//remove symmetrical connections
n.connectedNodes.Remove(nodeToRemove);
}
nodes.Remove(ID);//delete the actual node
}
public void printAdjMatrix()
{
foreach (KeyValuePair<int, Node> entry in nodes)
{
string connNodes = "Node: " + entry.Value.ID + "\nConn: ";
foreach (Node n2 in entry.Value.connectedNodes)
{
connNodes += n2.ID + ", ";
}
Debug.Log(connNodes);
}
}
public List<Node> AStar(int startingNodeKey, int endingNodeKey)
{
List<Node> ClosedSet = new List<Node>();
List<Node> OpenSet = new List<Node>();
foreach(KeyValuePair<int, Node> entry in nodes)
{
entry.Value.g = 99999;//set all g values to infinity
entry.Value.Ancestor = null;//set all node ancestors to null
}
nodes[startingNodeKey].g = 0;
nodes[startingNodeKey].h = Vector2.Distance(nodes[startingNodeKey].pos, nodes[endingNodeKey].pos);
OpenSet.Add(nodes[startingNodeKey]);
while (OpenSet.Count > 0 )
{
float minscore = 99999;
int minIndex = 0;
for(int i = 0;i<OpenSet.Count;i++)
{
if (OpenSet[i].f < minscore)
{
minscore = OpenSet[i].f;
minIndex = i;
}
}
//deep copy the node with the best score
Node currentNode = new Node(new Vector2(OpenSet[minIndex].pos.x, OpenSet[minIndex].pos.y), OpenSet[minIndex].ID, false);
currentNode.g = OpenSet[minIndex].g;
currentNode.h = OpenSet[minIndex].h;
currentNode.Ancestor = OpenSet[minIndex].Ancestor;
if (currentNode.ID == endingNodeKey)
{
//build the path list
List<Node> fullPath = new List<Node>();
Node temp = currentNode;
while (temp != null)
{
fullPath.Add(temp);
temp = temp.Ancestor;
}
return fullPath;
}
//remove this node from the open set
OpenSet.RemoveAt(minIndex);
ClosedSet.Add(currentNode);
//go through the list of nodes that are connected to the current node
foreach(Node n in nodes[currentNode.ID].connectedNodes)
{
bool isInClosedSet = false;
//check if it's already in the closed set
for (int i = 0; i < ClosedSet.Count; i++)
{
if (ClosedSet[i].ID == n.ID)
{
isInClosedSet = true;
break;
}
}
if (isInClosedSet)
continue;
float tenativeG = currentNode.g + Vector2.Distance(n.pos, currentNode.pos);
bool isInOpenSet = false;
for (int i = 0; i < OpenSet.Count; i++)
{
if (OpenSet[i].ID == n.ID)
isInOpenSet = true;
}
if (!isInOpenSet)
OpenSet.Add(n);
else if (tenativeG >= n.g)
continue;
n.Ancestor = currentNode;
n.g = tenativeG;
n.h = Vector2.Distance(n.pos, nodes[endingNodeKey].pos);
}
}
//didn't find a path
return new List<Node>();
}
public void generateAStarSatisfaction(List<Vector2> startingPoint, List<Vector2> endingPoint)
{
int successfulPaths = 0;
float avgPathLen = 0.0f;
for (int i = 0; i < startingPoint.Count; i++)
{
Node startingNode = closestNodeToPoint(startingPoint[i]);
if (startingNode == null)
continue;//skip to next iteration if no starting node can be found
Node endingNode = closestNodeToPoint(endingPoint[i]);
if (endingNode == null)
continue;//skip to next iteration if no ending node can be found
List<Node> path = AStar(startingNode.ID, endingNode.ID);
if (path.Count != 0)//if the path was successful
{
successfulPaths++;
avgPathLen += path[path.Count - 1].g +
Vector2.Distance(startingPoint[i], startingNode.pos) + Vector2.Distance(endingPoint[i], endingNode.pos);
}
}
avgPathLen /= successfulPaths;
//store results
AStarAvgPathLength = avgPathLen;
AStarPathSuccess = successfulPaths / (float)startingPoint.Count;
}
Node closestNodeToPoint(Vector2 point)
{
//find closest node to the given starting point
List<Node> lineOfSightNodes = new List<Node>();
foreach (KeyValuePair<int, Node> entry in nodes)
{
if (!Physics.Linecast(new Vector3(point.x, 2, point.y), new Vector3(entry.Value.pos.x, 2, entry.Value.pos.y)))
{
lineOfSightNodes.Add(entry.Value);
}
}
float minDist = 999999;
int minIndex = 0;
if (lineOfSightNodes.Count == 0)
return null;//no nodes are line of sight to this point
for (int j = 0; j < lineOfSightNodes.Count; j++)
{
float dist = Vector2.Distance(point, lineOfSightNodes[j].pos);
if (dist < minDist)
{
minDist = dist;
minIndex = j;
}
}
return lineOfSightNodes[minIndex];
}
}
|
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace xServer.Core.Build
{
public static class IconInjector
{
// Basically, you can change icons with the UpdateResource api call.
// When you make the call you say "I'm updating an icon", and you send the icon data.
// The main problem is that ICO files store the icons in one set of structures, and exe/dll files store them in
// another set of structures. So you have to translate between the two -- you can't just load the ICO file as
// bytes and send them with the UpdateResource api call.
[SuppressUnmanagedCodeSecurity()]
private class NativeMethods
{
[DllImport("kernel32")]
public static extern IntPtr BeginUpdateResource(string fileName, [MarshalAs(UnmanagedType.Bool)]bool deleteExistingResources);
[DllImport("kernel32")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool UpdateResource(IntPtr hUpdate, IntPtr type, IntPtr name, short language, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)]byte[] data, int dataSize);
[DllImport("kernel32")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EndUpdateResource(IntPtr hUpdate, [MarshalAs(UnmanagedType.Bool)]bool discard);
}
// The first structure in an ICO file lets us know how many images are in the file.
[StructLayout(LayoutKind.Sequential)]
private struct ICONDIR
{
// Reserved, must be 0
public ushort Reserved;
// Resource type, 1 for icons.
public ushort Type;
// How many images.
public ushort Count;
// The native structure has an array of ICONDIRENTRYs as a final field.
}
// Each ICONDIRENTRY describes one icon stored in the ico file. The offset says where the icon image data
// starts in the file. The other fields give the information required to turn that image data into a valid
// bitmap.
[StructLayout(LayoutKind.Sequential)]
private struct ICONDIRENTRY
{
// Width, in pixels, of the image
public byte Width;
// Height, in pixels, of the image
public byte Height;
// Number of colors in image (0 if >=8bpp)
public byte ColorCount;
// Reserved ( must be 0)
public byte Reserved;
// Color Planes
public ushort Planes;
// Bits per pixel
public ushort BitCount;
// Length in bytes of the pixel data
public int BytesInRes;
// Offset in the file where the pixel data starts.
public int ImageOffset;
}
// Each image is stored in the file as an ICONIMAGE structure:
//typdef struct
//{
// BITMAPINFOHEADER icHeader; // DIB header
// RGBQUAD icColors[1]; // Color table
// BYTE icXOR[1]; // DIB bits for XOR mask
// BYTE icAND[1]; // DIB bits for AND mask
//} ICONIMAGE, *LPICONIMAGE;
[StructLayout(LayoutKind.Sequential)]
private struct BITMAPINFOHEADER
{
public uint Size;
public int Width;
public int Height;
public ushort Planes;
public ushort BitCount;
public uint Compression;
public uint SizeImage;
public int XPelsPerMeter;
public int YPelsPerMeter;
public uint ClrUsed;
public uint ClrImportant;
}
// The icon in an exe/dll file is stored in a very similar structure:
[StructLayout(LayoutKind.Sequential, Pack = 2)]
private struct GRPICONDIRENTRY
{
public byte Width;
public byte Height;
public byte ColorCount;
public byte Reserved;
public ushort Planes;
public ushort BitCount;
public int BytesInRes;
public ushort ID;
}
public static void InjectIcon(string exeFileName, string iconFileName)
{
InjectIcon(exeFileName, iconFileName, 1, 1);
}
public static void InjectIcon(string exeFileName, string iconFileName, uint iconGroupID, uint iconBaseID)
{
const uint RT_ICON = 3u;
const uint RT_GROUP_ICON = 14u;
IconFile iconFile = IconFile.FromFile(iconFileName);
var hUpdate = NativeMethods.BeginUpdateResource(exeFileName, false);
var data = iconFile.CreateIconGroupData(iconBaseID);
NativeMethods.UpdateResource(hUpdate, new IntPtr(RT_GROUP_ICON), new IntPtr(iconGroupID), 0, data, data.Length);
for (int i = 0; i <= iconFile.ImageCount - 1; i++)
{
var image = iconFile.ImageData(i);
NativeMethods.UpdateResource(hUpdate, new IntPtr(RT_ICON), new IntPtr(iconBaseID + i), 0, image, image.Length);
}
NativeMethods.EndUpdateResource(hUpdate, false);
}
private class IconFile
{
private ICONDIR iconDir = new ICONDIR();
private ICONDIRENTRY[] iconEntry;
private byte[][] iconImage;
public int ImageCount
{
get { return iconDir.Count; }
}
public byte[] ImageData (int index)
{
return iconImage[index];
}
public static IconFile FromFile(string filename)
{
IconFile instance = new IconFile();
// Read all the bytes from the file.
byte[] fileBytes = System.IO.File.ReadAllBytes(filename);
// First struct is an ICONDIR
// Pin the bytes from the file in memory so that we can read them.
// If we didn't pin them then they could move around (e.g. when the
// garbage collector compacts the heap)
GCHandle pinnedBytes = GCHandle.Alloc(fileBytes, GCHandleType.Pinned);
// Read the ICONDIR
instance.iconDir = (ICONDIR)Marshal.PtrToStructure(pinnedBytes.AddrOfPinnedObject(), typeof(ICONDIR));
// which tells us how many images are in the ico file. For each image, there's a ICONDIRENTRY, and associated pixel data.
instance.iconEntry = new ICONDIRENTRY[instance.iconDir.Count];
instance.iconImage = new byte[instance.iconDir.Count][];
// The first ICONDIRENTRY will be immediately after the ICONDIR, so the offset to it is the size of ICONDIR
int offset = Marshal.SizeOf(instance.iconDir);
// After reading an ICONDIRENTRY we step forward by the size of an ICONDIRENTRY
var iconDirEntryType = typeof(ICONDIRENTRY);
var size = Marshal.SizeOf(iconDirEntryType);
for (int i = 0; i <= instance.iconDir.Count - 1; i++)
{
// Grab the structure.
var entry = (ICONDIRENTRY)Marshal.PtrToStructure(new IntPtr(pinnedBytes.AddrOfPinnedObject().ToInt64() + offset), iconDirEntryType);
instance.iconEntry[i] = entry;
// Grab the associated pixel data.
instance.iconImage[i] = new byte[entry.BytesInRes];
Buffer.BlockCopy(fileBytes, entry.ImageOffset, instance.iconImage[i], 0, entry.BytesInRes);
offset += size;
}
pinnedBytes.Free();
return instance;
}
public byte[] CreateIconGroupData(uint iconBaseID)
{
// This will store the memory version of the icon.
int sizeOfIconGroupData = Marshal.SizeOf(typeof(ICONDIR)) + Marshal.SizeOf(typeof(GRPICONDIRENTRY)) * ImageCount;
byte[] data = new byte[sizeOfIconGroupData];
var pinnedData = GCHandle.Alloc(data, GCHandleType.Pinned);
Marshal.StructureToPtr(iconDir, pinnedData.AddrOfPinnedObject(), false);
var offset = Marshal.SizeOf(iconDir);
for (int i = 0; i <= ImageCount - 1; i++)
{
GRPICONDIRENTRY grpEntry = new GRPICONDIRENTRY();
BITMAPINFOHEADER bitmapheader = new BITMAPINFOHEADER();
var pinnedBitmapInfoHeader = GCHandle.Alloc(bitmapheader, GCHandleType.Pinned);
Marshal.Copy(ImageData(i), 0, pinnedBitmapInfoHeader.AddrOfPinnedObject(), Marshal.SizeOf(typeof(BITMAPINFOHEADER)));
pinnedBitmapInfoHeader.Free();
grpEntry.Width = iconEntry[i].Width;
grpEntry.Height = iconEntry[i].Height;
grpEntry.ColorCount = iconEntry[i].ColorCount;
grpEntry.Reserved = iconEntry[i].Reserved;
grpEntry.Planes = bitmapheader.Planes;
grpEntry.BitCount = bitmapheader.BitCount;
grpEntry.BytesInRes = iconEntry[i].BytesInRes;
grpEntry.ID = Convert.ToUInt16(iconBaseID + i);
Marshal.StructureToPtr(grpEntry, new IntPtr(pinnedData.AddrOfPinnedObject().ToInt64() + offset), false);
offset += Marshal.SizeOf(typeof(GRPICONDIRENTRY));
}
pinnedData.Free();
return data;
}
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Web;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using LyricsFetcher;
using iTunesLib;
using WMPLib;
using WMFSDKWrapper;
public class TestSong : Song
{
public TestSong(string title, string artist, string album, string genre) :
base(title, artist, album, genre) {
}
public override string FullPath {
get { return String.Empty; }
}
public override void Commit() {
}
public override void GetLyrics() {
}
}
namespace LyricsFetcher.CommandLine
{
class Program
{
static void TestWMPLyrics() {
WindowsMediaPlayer wmpPlayer = new WindowsMediaPlayer();
IWMPPlaylist playlist = wmpPlayer.mediaCollection.getByAttribute("MediaType", "audio");
IWMPMedia media = playlist.get_Item(100);
Console.WriteLine(media.name);
Console.WriteLine(media.getItemInfo("Lyrics"));
//media.setItemInfo("Lyrics", "");
}
static void TestSecondTry() {
// Is it actually worthwhile doing the second or subsequent attempt?
ITunesLibrary lib = new ITunesLibrary();
//lib.MaxSongsToFetch = 1000;
lib.LoadSongs();
lib.WaitLoad();
List<Song> songs = lib.Songs.FindAll(
delegate(Song s) {
LyricsStatus status = s.LyricsStatus;
return (status == LyricsStatus.Untried ||
status == LyricsStatus.Failed ||
status == LyricsStatus.Success);
}
);
ILyricsSource source2 = new LyricsSourceLyricsPlugin();
ILyricsSource source1 = new LyricsSourceLyrdb();
ILyricsSource source3 = new LyricsSourceLyricsFly();
Stopwatch sw1 = new Stopwatch();
Stopwatch sw2 = new Stopwatch();
Stopwatch sw3 = new Stopwatch();
int failures = 0;
int success1 = 0;
int success2 = 0;
int success3 = 0;
foreach (Song song in songs) {
sw1.Start();
string lyrics = source1.GetLyrics(song);
sw1.Stop();
if (lyrics == string.Empty) {
sw2.Start();
lyrics = source2.GetLyrics(song);
sw2.Stop();
if (lyrics == string.Empty) {
sw3.Start();
lyrics = source3.GetLyrics(song);
sw3.Stop();
if (lyrics == string.Empty)
failures++;
else
success3++;
} else
success2++;
} else
success1++;
}
Console.WriteLine("1st try: successes: {0} ({1}%), time: {2} ({3} each)",
success1, (success1 * 100 / songs.Count), sw1.Elapsed, sw1.ElapsedMilliseconds / songs.Count);
Console.WriteLine("2st try: successes: {0} ({1}%), time: {2} ({3} each)",
success2, (success2 * 100 / songs.Count), sw2.Elapsed, sw2.ElapsedMilliseconds / (songs.Count - success1));
Console.WriteLine("3st try: successes: {0} ({1}%), time: {2} ({3} each)",
success3, (success3 * 100 / songs.Count), sw3.Elapsed, sw3.ElapsedMilliseconds / (songs.Count - success1 - success2));
Console.WriteLine("failures: {0} ({1}%)",
failures, (failures * 100 / songs.Count));
}
static void TestSources() {
ITunesLibrary lib = new ITunesLibrary();
lib.MaxSongsToFetch = 150;
lib.LoadSongs();
lib.WaitLoad();
List<Song> songs = lib.Songs.FindAll(
delegate(Song s) {
LyricsStatus status = s.LyricsStatus;
return (status == LyricsStatus.Untried ||
status == LyricsStatus.Failed ||
status == LyricsStatus.Success);
}
);
songs = songs.GetRange(0, 10);
//TestOneSource(songs, new LyricsSourceLyricWiki());
//TestOneSource(songs, new LyricsSourceLyricWikiHtml());
TestOneSource(songs, new LyricsSourceLyricsPlugin());
TestOneSource(songs, new LyricsSourceLyrdb());
TestOneSource(songs, new LyricsSourceLyricsFly());
}
private static void TestOneSource(List<Song> songs, ILyricsSource source) {
Console.WriteLine("Testing {0}...", source.Name);
int successes = 0;
int failures = 0;
Stopwatch sw = new Stopwatch();
sw.Start();
foreach (Song song in songs) {
if (source.GetLyrics(song) == string.Empty)
failures++;
else
successes++;
}
sw.Stop();
Console.WriteLine("Successes: {0}, failure: {1}, time: {2} seconds ({3} per song)",
successes, failures, sw.Elapsed, sw.ElapsedMilliseconds / songs.Count);
}
static void lfm_StatusEvent(object sender, LyricsFetchStatusEventArgs e)
{
System.Diagnostics.Debug.WriteLine(e.Status);
}
static void TestMetaDataEditor() {
string file = @"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\After the fire\Der Kommissar\01 Der Kommissar.wma";
using (MetaDataEditor mde = new MetaDataEditor(file)) {
//mde.SetFieldValue("WM/Lyrics", "These are some more of my favourite things");
//mde.SetFieldValue("WM/Genre", "80's rock");
Console.WriteLine(mde.GetFieldValue("WM/Year"));
Console.WriteLine(mde.GetFieldValue("WM/Lyrics"));
Console.WriteLine(mde.GetFieldValue("Genre"));
Console.WriteLine(mde.GetFieldValue("WM/Publisher"));
Console.WriteLine(mde.GetFieldValue("unknown"));
}
}
static void TestMetaDataEditor2() {
WindowsMediaPlayer wmpPlayer = new WindowsMediaPlayer();
IWMPPlaylist playlist = wmpPlayer.mediaCollection.getByAttribute("MediaType", "audio");
IWMPMedia media = playlist.get_Item(100);
Console.WriteLine(media.name);
Console.WriteLine(media.getItemInfo("WM/Genre"));
Console.WriteLine("-");
using (MetaDataEditor mde = new MetaDataEditor(media.sourceURL)) {
//mde.SetFieldValue("WM/Lyrics", "MORE LIKE THIS things");
//mde.SetFieldValue("WM/Genre", "80's rock");
Console.WriteLine(mde.GetFieldValue("WM/Year"));
Console.WriteLine(mde.GetFieldValue("WM/Lyrics"));
Console.WriteLine(mde.GetFieldValue("WM/Genre"));
Console.WriteLine(mde.GetFieldValue("WM/Publisher"));
Console.WriteLine(mde.GetFieldValue("unknown"));
}
}
static void TestLyricsSource() {
//ILyricsSource strategy = new LyricsSourceLyricWiki();
//ILyricsSource strategy = new LyricsSourceLyricWikiHtml();
//ILyricsSource strategy = new LyricsSourceLyrdb();
//ILyricsSource strategy = new LyricsSourceLyricsPlugin();
ILyricsSource strategy = new LyricsSourceLyricsFly();
//TestSong song = new TestSong("Lips don't hie", "Shakira", "Music of the Sun", "");
//TestSong song = new TestSong("Hips don't lie", "Shakira", "Music of the Sun", "");
//TestSong song = new TestSong("Pon de replay", "Rihanna", "Music of the Sun", "");
//TestSong song = new TestSong("I Love to Move in Here", "Moby", "Last Night", "");
TestSong song = new TestSong("Year 3000", "Busted", "", "");
Console.WriteLine(song);
Console.WriteLine(strategy.GetLyrics(song));
}
static void TestMetaDataLookup() {
string file = @"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\After the fire\Der Kommissar\01 Der Kommissar.mp3";
//string file = @"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\Alanis Morissette\So-Called Chaos\01 Eight Easy Steps.mp3";
//string file = @"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\Unknown Artist\Unknown Album\16 Pump UP the jam.mp3";
//string file = @"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\Ziqo\Unknown Album\01 Vamos Embora.mp3";
MetaDataLookup req = new MetaDataLookup();
Console.WriteLine("looking up '{0}'...", file);
req.Lookup(file);
Console.WriteLine("puid={0}", req.MetaData.Puid);
Console.WriteLine("title={0}", req.MetaData.Title);
Console.WriteLine("artist={0}", req.MetaData.Artist);
Console.WriteLine("genre={0}", req.MetaData.Genre);
}
static void TestManyMetaDataLookup() {
ITunesLibrary lib = new ITunesLibrary();
lib.MaxSongsToFetch = 50;
lib.LoadSongs();
lib.WaitLoad();
Stopwatch sw = new Stopwatch();
sw.Start();
try {
foreach (Song song in lib.Songs) {
MetaDataLookup req = new MetaDataLookup();
//MetaDataLookupOld req = new MetaDataLookupOld();
req.Lookup(song);
if (req.Status == MetaDataStatus.Success) {
if (song.Title == req.MetaData.Title && song.Artist == req.MetaData.Artist)
System.Diagnostics.Debug.WriteLine(String.Format("same: {0}", song));
else
System.Diagnostics.Debug.WriteLine(String.Format("different: {0}. title={1}, artist={2}", song, req.MetaData.Title, req.MetaData.Artist));
} else {
System.Diagnostics.Debug.WriteLine(String.Format("failed: {0}", song));
}
}
}
finally {
sw.Stop();
System.Diagnostics.Debug.WriteLine(String.Format("Tried {0} song in {1} ({2} secs per song)", lib.Songs.Count, sw.Elapsed, (sw.ElapsedMilliseconds / lib.Songs.Count) / 1000));
}
}
static void Main(string[] args)
{
Console.WriteLine("start");
TestSources();
//TestManyMetaDataLookup();
//Console.WriteLine("start");
//string value = GetFieldByName(@"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\After the fire\Der Kommissar\01 Der Kommissar.mp3", "WM/Lyrics");
//Console.WriteLine(value);
//Console.WriteLine(GetFieldByName(@"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\After the fire\Der Kommissar\01 Der Kommissar.mp3", "WM/Genre"));
//Console.WriteLine(GetFieldByName(@"C:\Documents and Settings\Admin_2\My Documents\My Music\iTunes\iTunes Music\After the fire\Der Kommissar\01 Der Kommissar.mp3", "WM/Publisher"));
//Console.ReadKey();
//------------------------------------------------------------
//System.Diagnostics.Debug.WriteLine("start");
//Stopwatch watch = new Stopwatch();
//SongLibrary library = new WmpLibrary();
////SongLibrary library = new ITunesLibrary();
////library.MaxSongsToFetch = 1000;
//watch.Start();
//library.LoadSongs();
//library.WaitLoad();
//watch.Stop();
//System.Diagnostics.Debug.WriteLine(String.Format("Loaded {0} songs in {1}ms",
// library.Songs.Count, watch.ElapsedMilliseconds));
//------------------------------------------------------------
//LyricsFetchManager lfm = new LyricsFetchManager();
//lfm.AutoUpdateLyrics = true;
//lfm.StatusEvent += new EventHandler<FetchStatusEventArgs>(lfm_StatusEvent);
//lfm.Sources.Add(new LyricsSourceLyrdb());
//lfm.Sources.Add(new LyricsSourceLyricWiki());
//System.Diagnostics.Debug.WriteLine("--------------");
//Song song = new TestSong("seconds", "u2", "Music of the Sun", "");
//lfm.Queue(song);
//lfm.Start();
//lfm.WaitUntilFinished();
//System.Diagnostics.Debug.WriteLine(song);
//System.Diagnostics.Debug.Write(song.Lyrics);
//System.Diagnostics.Debug.WriteLine("========");
//------------------------------------------------------------
//System.Diagnostics.Debug.WriteLine(Wmp.Instance.Player.versionInfo);
//SongLibrary library = new WmpLibrary();
//library.MaxSongsToFetch = 100;
//foreach (Song x in library.Songs)
// System.Diagnostics.Debug.WriteLine(x);
//------------------------------------------------------------
//IWMPPlaylist playlist = Wmp.Instance.AllTracks;
//System.Diagnostics.Debug.WriteLine(Wmp.Instance.Player.versionInfo);
//for (int i = 0; i < playlist.count; i++) {
// IWMPMedia media = playlist.get_Item(i);
// System.Diagnostics.Debug.WriteLine(media.name);
//}
Console.WriteLine("done");
Console.ReadKey();
}
}
}
|
// Author:
// Noah Ablaseau <nablaseau@hotmail.com>
//
// Copyright (c) 2017
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
namespace linerider.IO.ffmpeg
{
public static class FFMPEG
{
private const int MaximumBuffers = 25;
private static bool inited = false;
public static bool HasExecutable
{
get
{
return File.Exists(ffmpeg_path);
}
}
public static string ffmpeg_dir
{
get
{
string dir = Program.UserDirectory + "ffmpeg" + Path.DirectorySeparatorChar;
if (OpenTK.Configuration.RunningOnMacOS)
dir += "mac" + Path.DirectorySeparatorChar;
else if (OpenTK.Configuration.RunningOnWindows)
dir += "win" + Path.DirectorySeparatorChar;
else if (OpenTK.Configuration.RunningOnUnix)
{
dir += "linux" + Path.DirectorySeparatorChar;
}
else
{
return null;
}
return dir;
}
}
public static string ffmpeg_path
{
get
{
var dir = ffmpeg_dir;
if (dir == null)
return null;
if (OpenTK.Configuration.RunningOnWindows)
return dir + "ffmpeg.exe";
else
return dir + "ffmpeg";
}
}
static FFMPEG()
{
}
private static void TryInitialize()
{
if (inited)
return;
inited = true;
if (ffmpeg_path == null)
throw new Exception("Unable to detect platform for ffmpeg");
MakeffmpegExecutable();
}
public static string ConvertSongToOgg(string file, Func<string, bool> stdout)
{
TryInitialize();
if (!file.EndsWith(".ogg", true, Program.Culture))
{
var par = new IO.ffmpeg.FFMPEGParameters();
par.AddOption("i", "\"" + file + "\"");
par.OutputFilePath = file.Remove(file.IndexOf(".", StringComparison.Ordinal)) + ".ogg";
if (File.Exists(par.OutputFilePath))
{
if (File.Exists(file))
{
File.Delete(par.OutputFilePath);
}
else
{
return par.OutputFilePath;
}
}
Execute(par, stdout);
file = par.OutputFilePath;
}
return file;
}
public static void Execute(FFMPEGParameters parameters, Func<string, bool> stdout)
{
TryInitialize();
if (String.IsNullOrWhiteSpace(ffmpeg_path))
{
throw new Exception("Path to FFMPEG executable cannot be null");
}
if (parameters == null)
{
throw new Exception("FFMPEG parameters cannot be completely null");
}
using (Process ffmpegProcess = new Process())
{
ProcessStartInfo info = new ProcessStartInfo(ffmpeg_path)
{
Arguments = parameters.ToString(),
WorkingDirectory = Path.GetDirectoryName(ffmpeg_dir),
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = false,
RedirectStandardError = false
};
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
ffmpegProcess.StartInfo = info;
ffmpegProcess.Start();
if (stdout != null)
{
while (true)
{
string str = "";
try
{
str = ffmpegProcess.StandardError.ReadLine();
}
catch
{
Console.WriteLine("stdout log failed");
break;
//ignored
}
if (ffmpegProcess.HasExited)
break;
if (str == null)
str = "";
if (!stdout.Invoke(str))
{
ffmpegProcess.Kill();
return;
}
}
}
else
{
/*if (debug)
{
string processOutput = ffmpegProcess.StandardError.ReadToEnd();
}*/
ffmpegProcess.WaitForExit();
}
}
}
private static void MakeffmpegExecutable()
{
if (OpenTK.Configuration.RunningOnUnix)
{
try
{
using (Process chmod = new Process())
{
ProcessStartInfo info = new ProcessStartInfo("/bin/chmod")
{
Arguments = "+x ffmpeg",
WorkingDirectory = Path.GetDirectoryName(ffmpeg_dir),
UseShellExecute = false,
};
chmod.StartInfo = info;
chmod.Start();
if (!chmod.WaitForExit(1000))
{
chmod.Close();
}
}
}
catch (Exception e)
{
linerider.Utils.ErrorLog.WriteLine(
"chmod error on ffmpeg" + Environment.NewLine + e.ToString());
}
}
}
}
} |
/////////////////////////////////////////////////////////////////////////////
// C# Version Copyright (c) 2003 CenterSpace Software, LLC //
// //
// This code is free software under the Artistic license. //
// //
// CenterSpace Software //
// 2098 NW Myrtlewood Way //
// Corvallis, Oregon, 97330 //
// USA //
// http://www.centerspace.net //
/////////////////////////////////////////////////////////////////////////////
/*
A C-program for MT19937, with initialization improved 2002/1/26.
Coded by Takuji Nishimura and Makoto Matsumoto.
Before using, initialize the state by using init_genrand(seed)
or init_by_array(init_key, key_length).
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The names of its contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Any feedback is very welcome.
http://www.math.keio.ac.jp/matumoto/emt.html
email: matumoto@math.keio.ac.jp
*/
using System;
namespace CenterSpace.Free
{
/// <summary>
/// Class MersenneTwister generates random numbers from a uniform distribution using
/// the Mersenne Twister algorithm.
/// </summary>
/// <remarks>Caution: MT is for MonteCarlo, and is NOT SECURE for CRYPTOGRAPHY
/// as it is.</remarks>
public class MersenneTwister
{
#region Constants -------------------------------------------------------
// Period parameters.
private const int N = 624;
private const int M = 397;
private const uint MATRIX_A = 0x9908b0dfU; // constant vector a
private const uint UPPER_MASK = 0x80000000U; // most significant w-r bits
private const uint LOWER_MASK = 0x7fffffffU; // least significant r bits
private const int MAX_RAND_INT = 0x7fffffff;
#endregion Constants
#region Instance Variables ----------------------------------------------
// mag01[x] = x * MATRIX_A for x=0,1
private uint[] mag01 = {0x0U, MATRIX_A};
// the array for the state vector
private uint[] mt = new uint[N];
// mti==N+1 means mt[N] is not initialized
private int mti = N+1;
#endregion Instance Variables
#region Constructors ----------------------------------------------------
/// <summary>
/// Creates a random number generator using the time of day in milliseconds as
/// the seed.
/// </summary>
public MersenneTwister()
{
init_genrand( (uint)DateTime.Now.Millisecond );
}
/// <summary>
/// Creates a random number generator initialized with the given seed.
/// </summary>
/// <param name="seed">The seed.</param>
public MersenneTwister( int seed )
{
init_genrand( (uint)seed );
}
/// <summary>
/// Creates a random number generator initialized with the given array.
/// </summary>
/// <param name="init">The array for initializing keys.</param>
public MersenneTwister( int[] init )
{
uint[] initArray = new uint[init.Length];
for ( int i = 0; i < init.Length; ++i )
initArray[i] = (uint)init[i];
init_by_array( initArray, (uint)initArray.Length );
}
#endregion Constructors
#region Properties ------------------------------------------------------
/// <summary>
/// Gets the maximum random integer value. All random integers generated
/// by instances of this class are less than or equal to this value. This
/// value is <c>0x7fffffff</c> (<c>2,147,483,647</c>).
/// </summary>
public static int MaxRandomInt
{
get
{
return 0x7fffffff;
}
}
#endregion Properties
#region Member Functions ------------------------------------------------
/// <summary>
/// Returns a random integer greater than or equal to zero and
/// less than or equal to <c>MaxRandomInt</c>.
/// </summary>
/// <returns>The next random integer.</returns>
public int Next()
{
return genrand_int31();
}
/// <summary>
/// Returns a positive random integer less than the specified maximum.
/// </summary>
/// <param name="maxValue">The maximum value. Must be greater than zero.</param>
/// <returns>A positive random integer less than or equal to <c>maxValue</c>.</returns>
public int Next( int maxValue )
{
return Next( 0, maxValue );
}
/// <summary>
/// Returns a random integer within the specified range.
/// </summary>
/// <param name="minValue">The lower bound.</param>
/// <param name="maxValue">The upper bound.</param>
/// <returns>A random integer greater than or equal to <c>minValue</c>, and less than
/// or equal to <c>maxValue</c>.</returns>
public int Next( int minValue, int maxValue )
{
if ( minValue > maxValue )
{
int tmp = maxValue;
maxValue = minValue;
minValue = tmp;
}
return (int)( Math.Floor((maxValue-minValue+1)*genrand_real1() + minValue) );
}
/// <summary>
/// Returns a random number between 0.0 and 1.0.
/// </summary>
/// <returns>A single-precision floating point number greater than or equal to 0.0,
/// and less than 1.0.</returns>
public float NextFloat()
{
return (float) genrand_real2();
}
/// <summary>
/// Returns a random number greater than or equal to zero, and either strictly
/// less than one, or less than or equal to one, depending on the value of the
/// given boolean parameter.
/// </summary>
/// <param name="includeOne">
/// If <c>true</c>, the random number returned will be
/// less than or equal to one; otherwise, the random number returned will
/// be strictly less than one.
/// </param>
/// <returns>
/// If <c>includeOne</c> is <c>true</c>, this method returns a
/// single-precision random number greater than or equal to zero, and less
/// than or equal to one. If <c>includeOne</c> is <c>false</c>, this method
/// returns a single-precision random number greater than or equal to zero and
/// strictly less than one.
/// </returns>
public float NextFloat( bool includeOne )
{
if ( includeOne )
{
return (float) genrand_real1();
}
return (float) genrand_real2();
}
/// <summary>
/// Returns a random number greater than 0.0 and less than 1.0.
/// </summary>
/// <returns>A random number greater than 0.0 and less than 1.0.</returns>
public float NextFloatPositive()
{
return (float) genrand_real3();
}
/// <summary>
/// Returns a random number between 0.0 and 1.0.
/// </summary>
/// <returns>A double-precision floating point number greater than or equal to 0.0,
/// and less than 1.0.</returns>
public double NextDouble()
{
return genrand_real2();
}
/// <summary>
/// Returns a random number greater than or equal to zero, and either strictly
/// less than one, or less than or equal to one, depending on the value of the
/// given boolean parameter.
/// </summary>
/// <param name="includeOne">
/// If <c>true</c>, the random number returned will be
/// less than or equal to one; otherwise, the random number returned will
/// be strictly less than one.
/// </param>
/// <returns>
/// If <c>includeOne</c> is <c>true</c>, this method returns a
/// single-precision random number greater than or equal to zero, and less
/// than or equal to one. If <c>includeOne</c> is <c>false</c>, this method
/// returns a single-precision random number greater than or equal to zero and
/// strictly less than one.
/// </returns>
public double NextDouble( bool includeOne )
{
if ( includeOne )
{
return genrand_real1();
}
return genrand_real2();
}
/// <summary>
/// Returns a random number greater than 0.0 and less than 1.0.
/// </summary>
/// <returns>A random number greater than 0.0 and less than 1.0.</returns>
public double NextDoublePositive()
{
return genrand_real3();
}
/// <summary>
/// Generates a random number on <c>[0,1)</c> with 53-bit resolution.
/// </summary>
/// <returns>A random number on <c>[0,1)</c> with 53-bit resolution</returns>
public double Next53BitRes()
{
return genrand_res53();
}
/// <summary>
/// Reinitializes the random number generator using the time of day in
/// milliseconds as the seed.
/// </summary>
public void Initialize()
{
init_genrand( (uint)DateTime.Now.Millisecond );
}
/// <summary>
/// Reinitializes the random number generator with the given seed.
/// </summary>
/// <param name="seed">The seed.</param>
public void Initialize( int seed )
{
init_genrand( (uint)seed );
}
/// <summary>
/// Reinitializes the random number generator with the given array.
/// </summary>
/// <param name="init">The array for initializing keys.</param>
public void Initialize( int[] init )
{
uint[] initArray = new uint[init.Length];
for ( int i = 0; i < init.Length; ++i )
initArray[i] = (uint)init[i];
init_by_array( initArray, (uint)initArray.Length );
}
#region Methods ported from C -------------------------------------------
// initializes mt[N] with a seed
private void init_genrand( uint s)
{
mt[0]= s & 0xffffffffU;
for (mti=1; mti<N; mti++)
{
mt[mti] =
(uint)(1812433253U * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
// See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier.
// In the previous versions, MSBs of the seed affect
// only MSBs of the array mt[].
// 2002/01/09 modified by Makoto Matsumoto
mt[mti] &= 0xffffffffU;
// for >32 bit machines
}
}
// initialize by an array with array-length
// init_key is the array for initializing keys
// key_length is its length
private void init_by_array(uint[] init_key, uint key_length)
{
int i, j, k;
init_genrand(19650218U);
i=1; j=0;
k = (int)(N>key_length ? N : key_length);
for (; k>0; k--)
{
mt[i] = (uint)((uint)(mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525U)) + init_key[j] + j); /* non linear */
mt[i] &= 0xffffffffU; // for WORDSIZE > 32 machines
i++; j++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
if (j>=key_length) j=0;
}
for (k=N-1; k>0; k--)
{
mt[i] = (uint)((uint)(mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941U))- i); /* non linear */
mt[i] &= 0xffffffffU; // for WORDSIZE > 32 machines
i++;
if (i>=N) { mt[0] = mt[N-1]; i=1; }
}
mt[0] = 0x80000000U; // MSB is 1; assuring non-zero initial array
}
// generates a random number on [0,0xffffffff]-interval
uint genrand_int32()
{
uint y;
if (mti >= N)
{ /* generate N words at one time */
int kk;
if (mti == N+1) /* if init_genrand() has not been called, */
init_genrand(5489U); /* a default initial seed is used */
for (kk=0;kk<N-M;kk++)
{
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1U];
}
for (;kk<N-1;kk++)
{
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1U];
}
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1U];
mti = 0;
}
y = mt[mti++];
// Tempering
y ^= (y >> 11);
y ^= (y << 7) & 0x9d2c5680U;
y ^= (y << 15) & 0xefc60000U;
y ^= (y >> 18);
return y;
}
// generates a random number on [0,0x7fffffff]-interval
private int genrand_int31()
{
return (int)(genrand_int32()>>1);
}
// generates a random number on [0,1]-real-interval
double genrand_real1()
{
return genrand_int32()*(1.0/4294967295.0);
// divided by 2^32-1
}
// generates a random number on [0,1)-real-interval
double genrand_real2()
{
return genrand_int32()*(1.0/4294967296.0);
// divided by 2^32
}
// generates a random number on (0,1)-real-interval
double genrand_real3()
{
return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0);
// divided by 2^32
}
// generates a random number on [0,1) with 53-bit resolution
double genrand_res53()
{
uint a=genrand_int32()>>5, b=genrand_int32()>>6;
return(a*67108864.0+b)*(1.0/9007199254740992.0);
}
// These real versions are due to Isaku Wada, 2002/01/09 added
#endregion Methods ported from C
#endregion Member Functions
}
}
|
using System;
using System.Collections;
using System.IO;
namespace Server.Engines.Reports
{
public class StaffHistory : PersistableObject
{
#region Type Identification
public static readonly PersistableType ThisTypeID = new PersistableType("stfhst", new ConstructCallback(Construct));
private static PersistableObject Construct()
{
return new StaffHistory();
}
public override PersistableType TypeID
{
get
{
return ThisTypeID;
}
}
#endregion
private PageInfoCollection m_Pages;
private QueueStatusCollection m_QueueStats;
private Hashtable m_UserInfo;
private Hashtable m_StaffInfo;
public PageInfoCollection Pages
{
get
{
return this.m_Pages;
}
set
{
this.m_Pages = value;
}
}
public QueueStatusCollection QueueStats
{
get
{
return this.m_QueueStats;
}
set
{
this.m_QueueStats = value;
}
}
public Hashtable UserInfo
{
get
{
return this.m_UserInfo;
}
set
{
this.m_UserInfo = value;
}
}
public Hashtable StaffInfo
{
get
{
return this.m_StaffInfo;
}
set
{
this.m_StaffInfo = value;
}
}
public void AddPage(PageInfo info)
{
lock (SaveLock)
this.m_Pages.Add(info);
info.History = this;
}
public StaffHistory()
{
this.m_Pages = new PageInfoCollection();
this.m_QueueStats = new QueueStatusCollection();
this.m_UserInfo = new Hashtable(StringComparer.OrdinalIgnoreCase);
this.m_StaffInfo = new Hashtable(StringComparer.OrdinalIgnoreCase);
}
public StaffInfo GetStaffInfo(string account)
{
lock (RenderLock)
{
if (account == null || account.Length == 0)
return null;
StaffInfo info = this.m_StaffInfo[account] as StaffInfo;
if (info == null)
this.m_StaffInfo[account] = info = new StaffInfo(account);
return info;
}
}
public UserInfo GetUserInfo(string account)
{
if (account == null || account.Length == 0)
return null;
UserInfo info = this.m_UserInfo[account] as UserInfo;
if (info == null)
this.m_UserInfo[account] = info = new UserInfo(account);
return info;
}
public static readonly object RenderLock = new object();
public static readonly object SaveLock = new object();
public void Save()
{
lock (SaveLock)
{
if (!Directory.Exists("Output"))
{
Directory.CreateDirectory("Output");
}
string path = Path.Combine(Core.BaseDirectory, "Output/staffHistory.xml");
PersistanceWriter pw = new XmlPersistanceWriter(path, "Staff");
pw.WriteDocument(this);
pw.Close();
}
}
public void Load()
{
string path = Path.Combine(Core.BaseDirectory, "Output/staffHistory.xml");
if (!File.Exists(path))
return;
PersistanceReader pr = new XmlPersistanceReader(path, "Staff");
pr.ReadDocument(this);
pr.Close();
}
public override void SerializeChildren(PersistanceWriter op)
{
for (int i = 0; i < this.m_Pages.Count; ++i)
this.m_Pages[i].Serialize(op);
for (int i = 0; i < this.m_QueueStats.Count; ++i)
this.m_QueueStats[i].Serialize(op);
}
public override void DeserializeChildren(PersistanceReader ip)
{
DateTime min = DateTime.UtcNow - TimeSpan.FromDays(8.0);
while (ip.HasChild)
{
PersistableObject obj = ip.GetChild();
if (obj is PageInfo)
{
PageInfo pageInfo = obj as PageInfo;
pageInfo.UpdateResolver();
if (pageInfo.TimeSent >= min || pageInfo.TimeResolved >= min)
{
this.m_Pages.Add(pageInfo);
pageInfo.History = this;
}
else
{
pageInfo.Sender = null;
pageInfo.Resolver = null;
}
}
else if (obj is QueueStatus)
{
QueueStatus queueStatus = obj as QueueStatus;
if (queueStatus.TimeStamp >= min)
this.m_QueueStats.Add(queueStatus);
}
}
}
public StaffInfo[] GetStaff()
{
StaffInfo[] staff = new StaffInfo[this.m_StaffInfo.Count];
int index = 0;
foreach (StaffInfo staffInfo in this.m_StaffInfo.Values)
staff[index++] = staffInfo;
return staff;
}
public void Render(ObjectCollection objects)
{
lock (RenderLock)
{
objects.Add(this.GraphQueueStatus());
StaffInfo[] staff = this.GetStaff();
BaseInfo.SortRange = TimeSpan.FromDays(7.0);
Array.Sort(staff);
objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.None, "New pages by hour", "graph_new_pages_hr"));
objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.Handled, "Handled pages by hour", "graph_handled_pages_hr"));
objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.Deleted, "Deleted pages by hour", "graph_deleted_pages_hr"));
objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.Canceled, "Canceled pages by hour", "graph_canceled_pages_hr"));
objects.Add(this.GraphHourlyPages(this.m_Pages, PageResolution.Logged, "Logged-out pages by hour", "graph_logged_pages_hr"));
BaseInfo.SortRange = TimeSpan.FromDays(1.0);
Array.Sort(staff);
objects.Add(this.ReportTotalPages(staff, TimeSpan.FromDays(1.0), "1 Day"));
objects.AddRange((PersistableObject[])this.ChartTotalPages(staff, TimeSpan.FromDays(1.0), "1 Day", "graph_daily_pages"));
BaseInfo.SortRange = TimeSpan.FromDays(7.0);
Array.Sort(staff);
objects.Add(this.ReportTotalPages(staff, TimeSpan.FromDays(7.0), "1 Week"));
objects.AddRange((PersistableObject[])this.ChartTotalPages(staff, TimeSpan.FromDays(7.0), "1 Week", "graph_weekly_pages"));
BaseInfo.SortRange = TimeSpan.FromDays(30.0);
Array.Sort(staff);
objects.Add(this.ReportTotalPages(staff, TimeSpan.FromDays(30.0), "1 Month"));
objects.AddRange((PersistableObject[])this.ChartTotalPages(staff, TimeSpan.FromDays(30.0), "1 Month", "graph_monthly_pages"));
for (int i = 0; i < staff.Length; ++i)
objects.Add(this.GraphHourlyPages(staff[i]));
}
}
public static int GetPageCount(StaffInfo staff, DateTime min, DateTime max)
{
return GetPageCount(staff.Pages, PageResolution.Handled, min, max);
}
public static int GetPageCount(PageInfoCollection pages, PageResolution res, DateTime min, DateTime max)
{
int count = 0;
for (int i = 0; i < pages.Count; ++i)
{
if (res != PageResolution.None && pages[i].Resolution != res)
continue;
DateTime ts = pages[i].TimeResolved;
if (ts >= min && ts < max)
++count;
}
return count;
}
private BarGraph GraphQueueStatus()
{
int[] totals = new int[24];
int[] counts = new int[24];
DateTime max = DateTime.UtcNow;
DateTime min = max - TimeSpan.FromDays(7.0);
for (int i = 0; i < this.m_QueueStats.Count; ++i)
{
DateTime ts = this.m_QueueStats[i].TimeStamp;
if (ts >= min && ts < max)
{
DateTime date = ts.Date;
TimeSpan time = ts.TimeOfDay;
int hour = time.Hours;
totals[hour] += this.m_QueueStats[i].Count;
counts[hour]++;
}
}
BarGraph barGraph = new BarGraph("Average pages in queue", "graph_pagequeue_avg", 10, "Time", "Pages", BarGraphRenderMode.Lines);
barGraph.FontSize = 6;
for (int i = 7; i <= totals.Length + 7; ++i)
{
int val;
if (counts[i % totals.Length] == 0)
val = 0;
else
val = (totals[i % totals.Length] + (counts[i % totals.Length] / 2)) / counts[i % totals.Length];
int realHours = i % totals.Length;
int hours;
if (realHours == 0)
hours = 12;
else if (realHours > 12)
hours = realHours - 12;
else
hours = realHours;
barGraph.Items.Add(hours + (realHours >= 12 ? " PM" : " AM"), val);
}
return barGraph;
}
private BarGraph GraphHourlyPages(StaffInfo staff)
{
return this.GraphHourlyPages(staff.Pages, PageResolution.Handled, "Average pages handled by " + staff.Display, "graphs_" + staff.Account.ToLower() + "_avg");
}
private BarGraph GraphHourlyPages(PageInfoCollection pages, PageResolution res, string title, string fname)
{
int[] totals = new int[24];
int[] counts = new int[24];
DateTime[] dates = new DateTime[24];
DateTime max = DateTime.UtcNow;
DateTime min = max - TimeSpan.FromDays(7.0);
bool sentStamp = (res == PageResolution.None);
for (int i = 0; i < pages.Count; ++i)
{
if (res != PageResolution.None && pages[i].Resolution != res)
continue;
DateTime ts = (sentStamp ? pages[i].TimeSent : pages[i].TimeResolved);
if (ts >= min && ts < max)
{
DateTime date = ts.Date;
TimeSpan time = ts.TimeOfDay;
int hour = time.Hours;
totals[hour]++;
if (dates[hour] != date)
{
counts[hour]++;
dates[hour] = date;
}
}
}
BarGraph barGraph = new BarGraph(title, fname, 10, "Time", "Pages", BarGraphRenderMode.Lines);
barGraph.FontSize = 6;
for (int i = 7; i <= totals.Length + 7; ++i)
{
int val;
if (counts[i % totals.Length] == 0)
val = 0;
else
val = (totals[i % totals.Length] + (counts[i % totals.Length] / 2)) / counts[i % totals.Length];
int realHours = i % totals.Length;
int hours;
if (realHours == 0)
hours = 12;
else if (realHours > 12)
hours = realHours - 12;
else
hours = realHours;
barGraph.Items.Add(hours + (realHours >= 12 ? " PM" : " AM"), val);
}
return barGraph;
}
private Report ReportTotalPages(StaffInfo[] staff, TimeSpan ts, string title)
{
DateTime max = DateTime.UtcNow;
DateTime min = max - ts;
Report report = new Report(title + " Staff Report", "400");
report.Columns.Add("65%", "left", "Staff Name");
report.Columns.Add("35%", "center", "Page Count");
for (int i = 0; i < staff.Length; ++i)
report.Items.Add(staff[i].Display, GetPageCount(staff[i], min, max));
return report;
}
private PieChart[] ChartTotalPages(StaffInfo[] staff, TimeSpan ts, string title, string fname)
{
DateTime max = DateTime.UtcNow;
DateTime min = max - ts;
PieChart staffChart = new PieChart(title + " Staff Chart", fname + "_staff", true);
int other = 0;
for (int i = 0; i < staff.Length; ++i)
{
int count = GetPageCount(staff[i], min, max);
if (i < 12 && count > 0)
staffChart.Items.Add(staff[i].Display, count);
else
other += count;
}
if (other > 0)
staffChart.Items.Add("Other", other);
PieChart resChart = new PieChart(title + " Resolutions", fname + "_resol", true);
int countTotal = GetPageCount(this.m_Pages, PageResolution.None, min, max);
int countHandled = GetPageCount(this.m_Pages, PageResolution.Handled, min, max);
int countDeleted = GetPageCount(this.m_Pages, PageResolution.Deleted, min, max);
int countCanceled = GetPageCount(this.m_Pages, PageResolution.Canceled, min, max);
int countLogged = GetPageCount(this.m_Pages, PageResolution.Logged, min, max);
int countUnres = countTotal - (countHandled + countDeleted + countCanceled + countLogged);
resChart.Items.Add("Handled", countHandled);
resChart.Items.Add("Deleted", countDeleted);
resChart.Items.Add("Canceled", countCanceled);
resChart.Items.Add("Logged Out", countLogged);
resChart.Items.Add("Unresolved", countUnres);
return new PieChart[] { staffChart, resChart };
}
}
} |
/*
Copyright (C) 2014-2019 de4dot@gmail.com
This file is part of dnSpy
dnSpy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
dnSpy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with dnSpy. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using dnSpy.Contracts.Debugger;
using dnSpy.Contracts.Debugger.Breakpoints.Code;
using dnSpy.Contracts.Debugger.Code;
using dnSpy.Debugger.Impl;
namespace dnSpy.Debugger.Breakpoints.Code {
abstract class DbgCodeBreakpointsService2 : DbgCodeBreakpointsService {
public abstract void UpdateIsDebugging_DbgThread(bool newIsDebugging);
public abstract DbgBoundCodeBreakpoint[] AddBoundBreakpoints_DbgThread(IList<DbgBoundCodeBreakpoint> boundBreakpoints);
public abstract void RemoveBoundBreakpoints_DbgThread(IList<DbgBoundCodeBreakpoint> boundBreakpoints);
public abstract DbgBoundCodeBreakpoint[] RemoveBoundBreakpoints_DbgThread(DbgRuntime runtime);
}
[Export(typeof(DbgCodeBreakpointsService))]
[Export(typeof(DbgCodeBreakpointsService2))]
sealed class DbgCodeBreakpointsServiceImpl : DbgCodeBreakpointsService2 {
readonly object lockObj;
readonly HashSet<DbgCodeBreakpointImpl> breakpoints;
readonly Dictionary<DbgCodeLocation, DbgCodeBreakpointImpl> locationToBreakpoint;
readonly DbgDispatcherProvider dbgDispatcherProvider;
int breakpointId;
bool isDebugging;
public override event EventHandler<DbgBoundBreakpointsMessageChangedEventArgs> BoundBreakpointsMessageChanged;
internal DbgDispatcherProvider DbgDispatcher => dbgDispatcherProvider;
[ImportingConstructor]
DbgCodeBreakpointsServiceImpl(DbgDispatcherProvider dbgDispatcherProvider, [ImportMany] IEnumerable<Lazy<IDbgCodeBreakpointsServiceListener>> dbgCodeBreakpointsServiceListener) {
lockObj = new object();
breakpoints = new HashSet<DbgCodeBreakpointImpl>();
locationToBreakpoint = new Dictionary<DbgCodeLocation, DbgCodeBreakpointImpl>();
this.dbgDispatcherProvider = dbgDispatcherProvider;
breakpointId = 0;
isDebugging = false;
foreach (var lz in dbgCodeBreakpointsServiceListener)
lz.Value.Initialize(this);
}
void Dbg(Action callback) => dbgDispatcherProvider.Dbg(callback);
public override void Modify(DbgCodeBreakpointAndSettings[] settings) {
if (settings is null)
throw new ArgumentNullException(nameof(settings));
Dbg(() => ModifyCore(settings));
}
void ModifyCore(DbgCodeBreakpointAndSettings[] settings) {
dbgDispatcherProvider.VerifyAccess();
List<DbgCodeBreakpointImpl>? updatedBreakpoints = null;
var bps = new List<DbgCodeBreakpointAndOldSettings>(settings.Length);
lock (lockObj) {
foreach (var info in settings) {
var bpImpl = info.Breakpoint as DbgCodeBreakpointImpl;
Debug.Assert(!(bpImpl is null));
if (bpImpl is null)
continue;
Debug.Assert(breakpoints.Contains(bpImpl));
if (!breakpoints.Contains(bpImpl))
continue;
var currentSettings = bpImpl.Settings;
if (currentSettings == info.Settings)
continue;
bps.Add(new DbgCodeBreakpointAndOldSettings(bpImpl, currentSettings));
if (bpImpl.WriteSettings_DbgThread(info.Settings)) {
if (updatedBreakpoints is null)
updatedBreakpoints = new List<DbgCodeBreakpointImpl>(settings.Length);
updatedBreakpoints.Add(bpImpl);
}
}
}
if (bps.Count > 0)
BreakpointsModified?.Invoke(this, new DbgBreakpointsModifiedEventArgs(new ReadOnlyCollection<DbgCodeBreakpointAndOldSettings>(bps)));
if (!(updatedBreakpoints is null)) {
foreach (var bp in updatedBreakpoints)
bp.RaiseBoundBreakpointsMessageChanged_DbgThread();
BoundBreakpointsMessageChanged?.Invoke(this, new DbgBoundBreakpointsMessageChangedEventArgs(new ReadOnlyCollection<DbgCodeBreakpoint>(updatedBreakpoints.ToArray())));
}
}
public override event EventHandler<DbgBreakpointsModifiedEventArgs> BreakpointsModified;
public override event EventHandler<DbgCollectionChangedEventArgs<DbgCodeBreakpoint>> BreakpointsChanged;
public override DbgCodeBreakpoint[] Breakpoints {
get {
lock (lockObj)
return breakpoints.ToArray();
}
}
public override DbgCodeBreakpoint[] Add(DbgCodeBreakpointInfo[] breakpoints) {
if (breakpoints is null)
throw new ArgumentNullException(nameof(breakpoints));
var bpImpls = new List<DbgCodeBreakpointImpl>(breakpoints.Length);
List<DbgObject>? objsToClose = null;
lock (lockObj) {
for (int i = 0; i < breakpoints.Length; i++) {
var info = breakpoints[i];
var location = info.Location;
if (locationToBreakpoint.ContainsKey(location)) {
if (objsToClose is null)
objsToClose = new List<DbgObject>();
objsToClose.Add(location);
}
else {
var bp = new DbgCodeBreakpointImpl(this, breakpointId++, info.Options, location, info.Settings, isDebugging);
bpImpls.Add(bp);
}
}
Dbg(() => AddCore(bpImpls, objsToClose));
}
return bpImpls.ToArray();
}
void AddCore(List<DbgCodeBreakpointImpl> breakpoints, List<DbgObject>? objsToClose) {
dbgDispatcherProvider.VerifyAccess();
var added = new List<DbgCodeBreakpoint>(breakpoints.Count);
List<DbgCodeBreakpointImpl>? updatedBreakpoints = null;
lock (lockObj) {
foreach (var bp in breakpoints) {
Debug.Assert(!this.breakpoints.Contains(bp));
if (this.breakpoints.Contains(bp))
continue;
if (locationToBreakpoint.ContainsKey(bp.Location)) {
if (objsToClose is null)
objsToClose = new List<DbgObject>();
objsToClose.Add(bp);
}
else {
added.Add(bp);
this.breakpoints.Add(bp);
locationToBreakpoint.Add(bp.Location, bp);
if (bp.WriteIsDebugging_DbgThread(isDebugging)) {
if (updatedBreakpoints is null)
updatedBreakpoints = new List<DbgCodeBreakpointImpl>(breakpoints.Count);
updatedBreakpoints.Add(bp);
}
}
}
}
if (!(objsToClose is null)) {
foreach (var obj in objsToClose)
obj.Close(dbgDispatcherProvider.Dispatcher);
}
if (added.Count > 0)
BreakpointsChanged?.Invoke(this, new DbgCollectionChangedEventArgs<DbgCodeBreakpoint>(added, added: true));
if (!(updatedBreakpoints is null)) {
foreach (var bp in updatedBreakpoints)
bp.RaiseBoundBreakpointsMessageChanged_DbgThread();
BoundBreakpointsMessageChanged?.Invoke(this, new DbgBoundBreakpointsMessageChangedEventArgs(new ReadOnlyCollection<DbgCodeBreakpoint>(updatedBreakpoints.ToArray())));
}
}
public override void Remove(DbgCodeBreakpoint[] breakpoints) {
if (breakpoints is null)
throw new ArgumentNullException(nameof(breakpoints));
Dbg(() => RemoveCore(breakpoints));
}
void RemoveCore(DbgCodeBreakpoint[] breakpoints) {
dbgDispatcherProvider.VerifyAccess();
var removed = new List<DbgCodeBreakpoint>(breakpoints.Length);
lock (lockObj) {
foreach (var bp in breakpoints) {
var bpImpl = bp as DbgCodeBreakpointImpl;
Debug.Assert(!(bpImpl is null));
if (bpImpl is null)
continue;
if (!this.breakpoints.Contains(bpImpl))
continue;
removed.Add(bpImpl);
this.breakpoints.Remove(bpImpl);
bool b = locationToBreakpoint.Remove(bpImpl.Location);
Debug.Assert(b);
}
}
if (removed.Count > 0) {
BreakpointsChanged?.Invoke(this, new DbgCollectionChangedEventArgs<DbgCodeBreakpoint>(removed, added: false));
foreach (var bp in removed)
bp.Close(dbgDispatcherProvider.Dispatcher);
}
}
public override DbgCodeBreakpoint? TryGetBreakpoint(DbgCodeLocation location) {
if (location is null)
throw new ArgumentNullException(nameof(location));
lock (lockObj) {
if (locationToBreakpoint.TryGetValue(location, out var bp))
return bp;
}
return null;
}
public override void Clear() => Dbg(() => RemoveCore(VisibleBreakpoints.ToArray()));
public override void UpdateIsDebugging_DbgThread(bool newIsDebugging) {
dbgDispatcherProvider.VerifyAccess();
List<DbgCodeBreakpointImpl> updatedBreakpoints;
lock (lockObj) {
if (isDebugging == newIsDebugging)
return;
isDebugging = newIsDebugging;
updatedBreakpoints = new List<DbgCodeBreakpointImpl>(breakpoints.Count);
foreach (var bp in breakpoints) {
bool updated = bp.WriteIsDebugging_DbgThread(isDebugging);
if (updated)
updatedBreakpoints.Add(bp);
}
}
foreach (var bp in updatedBreakpoints)
bp.RaiseBoundBreakpointsMessageChanged_DbgThread();
if (updatedBreakpoints.Count > 0)
BoundBreakpointsMessageChanged?.Invoke(this, new DbgBoundBreakpointsMessageChangedEventArgs(new ReadOnlyCollection<DbgCodeBreakpoint>(updatedBreakpoints.ToArray())));
}
public override DbgBoundCodeBreakpoint[] AddBoundBreakpoints_DbgThread(IList<DbgBoundCodeBreakpoint> boundBreakpoints) {
dbgDispatcherProvider.VerifyAccess();
var dict = CreateBreakpointDictionary(boundBreakpoints);
var updatedBreakpoints = new List<(bool raiseMessageChanged, DbgCodeBreakpointImpl breakpoint, List<DbgBoundCodeBreakpoint> boundBreakpoints)>(dict.Count);
List<DbgBoundCodeBreakpoint>? unusedBoundBreakpoints = null;
lock (lockObj) {
foreach (var kv in dict) {
var bp = kv.Key;
if (breakpoints.Contains(bp)) {
bool raiseMessageChanged = bp.AddBoundBreakpoints_DbgThread(kv.Value);
updatedBreakpoints.Add((raiseMessageChanged, bp, kv.Value));
}
else {
if (unusedBoundBreakpoints is null)
unusedBoundBreakpoints = new List<DbgBoundCodeBreakpoint>();
unusedBoundBreakpoints.AddRange(kv.Value);
}
}
}
foreach (var info in updatedBreakpoints)
info.breakpoint.RaiseEvents_DbgThread(info.raiseMessageChanged, info.boundBreakpoints, added: true);
if (updatedBreakpoints.Count > 0)
BoundBreakpointsMessageChanged?.Invoke(this, new DbgBoundBreakpointsMessageChangedEventArgs(new ReadOnlyCollection<DbgCodeBreakpoint>(updatedBreakpoints.Where(a => a.raiseMessageChanged).Select(a => a.breakpoint).ToArray())));
return unusedBoundBreakpoints?.ToArray() ?? Array.Empty<DbgBoundCodeBreakpoint>();
}
public override void RemoveBoundBreakpoints_DbgThread(IList<DbgBoundCodeBreakpoint> boundBreakpoints) {
dbgDispatcherProvider.VerifyAccess();
var dict = CreateBreakpointDictionary(boundBreakpoints);
var updatedBreakpoints = new List<(bool raiseMessageChanged, DbgCodeBreakpointImpl breakpoint, List<DbgBoundCodeBreakpoint> boundBreakpoints)>(dict.Count);
lock (lockObj) {
foreach (var kv in dict) {
var bp = kv.Key;
if (breakpoints.Contains(bp)) {
bool raiseMessageChanged = bp.RemoveBoundBreakpoints_DbgThread(kv.Value);
updatedBreakpoints.Add((raiseMessageChanged, bp, kv.Value));
}
}
}
foreach (var info in updatedBreakpoints)
info.breakpoint.RaiseEvents_DbgThread(info.raiseMessageChanged, info.boundBreakpoints, added: false);
if (updatedBreakpoints.Count > 0)
BoundBreakpointsMessageChanged?.Invoke(this, new DbgBoundBreakpointsMessageChangedEventArgs(new ReadOnlyCollection<DbgCodeBreakpoint>(updatedBreakpoints.Where(a => a.raiseMessageChanged).Select(a => a.breakpoint).ToArray())));
}
static Dictionary<DbgCodeBreakpointImpl, List<DbgBoundCodeBreakpoint>> CreateBreakpointDictionary(IList<DbgBoundCodeBreakpoint> boundBreakpoints) {
int count = boundBreakpoints.Count;
var dict = new Dictionary<DbgCodeBreakpointImpl, List<DbgBoundCodeBreakpoint>>(count);
for (int i = 0; i < boundBreakpoints.Count; i++) {
var bound = boundBreakpoints[i];
var bpImpl = bound.Breakpoint as DbgCodeBreakpointImpl;
Debug.Assert(!(bpImpl is null));
if (bpImpl is null)
continue;
if (!dict.TryGetValue(bpImpl, out var list))
dict.Add(bpImpl, list = new List<DbgBoundCodeBreakpoint>());
list.Add(bound);
}
return dict;
}
public override DbgBoundCodeBreakpoint[] RemoveBoundBreakpoints_DbgThread(DbgRuntime runtime) {
dbgDispatcherProvider.VerifyAccess();
var list = new List<DbgBoundCodeBreakpoint>();
lock (lockObj) {
foreach (var bp in breakpoints) {
foreach (var boundBreakpoint in bp.BoundBreakpoints) {
if (boundBreakpoint.Runtime == runtime)
list.Add(boundBreakpoint);
}
}
}
var res = list.ToArray();
RemoveBoundBreakpoints_DbgThread(res);
return res;
}
internal void OnBoundBreakpointsMessageChanged_DbgThread(DbgCodeBreakpointImpl bp) {
dbgDispatcherProvider.VerifyAccess();
bp.RaiseBoundBreakpointsMessageChanged_DbgThread();
BoundBreakpointsMessageChanged?.Invoke(this, new DbgBoundBreakpointsMessageChangedEventArgs(new ReadOnlyCollection<DbgCodeBreakpoint>(new[] { bp })));
}
}
}
|
using System;
using System.Web;
using System.Web.Routing;
using System.Drawing;
using System.Drawing.Imaging;
using Meridian59.Files.BGF;
namespace Meridian59.BgfService
{
/// <summary>
///
/// </summary>
public class FileRouteHandler : IRouteHandler
{
public FileRouteHandler()
{
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new FileHttpHandler();
}
}
/// <summary>
/// Provides contents from BGF file. This includes meta data
/// like offsets and hotspots as well as frame images as PNG or BMP.
/// </summary>
public class FileHttpHandler : IHttpHandler
{
/// <summary>
/// Handles the HTTP request
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
// --------------------------------------------------------------------------------------------
// 1) PARSE URL PARAMETERS
// --------------------------------------------------------------------------------------------
// read parameters from url-path (see Global.asax):
RouteValueDictionary parms = context.Request.RequestContext.RouteData.Values;
string parmFile = parms.ContainsKey("file") ? (string)parms["file"] : null;
string parmReq = parms.ContainsKey("req") ? (string)parms["req"] : null;
string parm1 = parms.ContainsKey("parm1") ? (string)parms["parm1"] : null;
string parm2 = parms.ContainsKey("parm2") ? (string)parms["parm2"] : null;
string parm3 = parms.ContainsKey("parm3") ? (string)parms["parm3"] : null;
BgfCache.Entry entry;
// no filename or request type
if (String.IsNullOrEmpty(parmFile) || !BgfCache.GetBGF(parmFile, out entry) ||
String.IsNullOrEmpty(parmReq))
{
context.Response.StatusCode = 404;
return;
}
// set cache behaviour
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.Cache.VaryByParams["*"] = false;
context.Response.Cache.SetLastModified(entry.LastModified);
// --------------------------------------------------------------------------------------------
// FRAME IMAGE
// --------------------------------------------------------------------------------------------
if (parmReq == "frame")
{
ushort index;
byte palette = 0;
Byte.TryParse(parm3, out palette);
// try to parse index and palette and validate range
if (!UInt16.TryParse(parm2, out index) || index >= entry.Bgf.Frames.Count)
{
context.Response.StatusCode = 404;
return;
}
// create BMP (256 col) or PNG (32-bit) or return raw pixels (8bit indices)
if (parm1 == "bmp")
{
response.ContentType = "image/bmp";
response.AddHeader(
"Content-Disposition",
"inline; filename=" + entry.Bgf.Filename + "-" + index.ToString() + ".bmp");
Bitmap bmp = entry.Bgf.Frames[index].GetBitmap(palette);
bmp.Save(context.Response.OutputStream, ImageFormat.Bmp);
bmp.Dispose();
}
else if (parm1 == "png")
{
response.ContentType = "image/png";
response.AddHeader(
"Content-Disposition",
"inline; filename=" + entry.Bgf.Filename + "-" + index.ToString() + ".png");
Bitmap bmp = entry.Bgf.Frames[index].GetBitmapA8R8G8B8(palette);
bmp.Save(context.Response.OutputStream, ImageFormat.Png);
bmp.Dispose();
}
else if (parm1 == "bin")
{
response.ContentType = "application/octet-stream";
response.AddHeader(
"Content-Disposition",
"attachment; filename=" + entry.Bgf.Filename + "-" + index.ToString() + ".bin");
byte[] pixels = entry.Bgf.Frames[index].PixelData;
context.Response.OutputStream.Write(pixels, 0, pixels.Length);
}
else
context.Response.StatusCode = 404;
}
// --------------------------------------------------------------------------------------------
// JSON META DATA
// --------------------------------------------------------------------------------------------
else if (parmReq == "meta")
{
// set response type
response.ContentType = "application/json";
response.ContentEncoding = new System.Text.UTF8Encoding(false);
response.AddHeader("Content-Disposition", "inline; filename=" + entry.Bgf.Filename + ".json");
// unix timestamp
long stamp = (entry.LastModified.Ticks - 621355968000000000) / 10000000;
/////////////////////////////////////////////////////////////
response.Write("{\"file\":\"");
response.Write(entry.Bgf.Filename);
response.Write("\",\"size\":");
response.Write(entry.Size.ToString());
response.Write(",\"modified\":");
response.Write(stamp.ToString());
response.Write(",\"shrink\":");
response.Write(entry.Bgf.ShrinkFactor.ToString());
response.Write(",\"frames\":[");
for (int i = 0; i < entry.Bgf.Frames.Count; i++)
{
BgfBitmap frame = entry.Bgf.Frames[i];
if (i > 0)
response.Write(',');
response.Write("{\"w\":");
response.Write(frame.Width.ToString());
response.Write(",\"h\":");
response.Write(frame.Height.ToString());
response.Write(",\"x\":");
response.Write(frame.XOffset.ToString());
response.Write(",\"y\":");
response.Write(frame.YOffset.ToString());
response.Write(",\"hs\":[");
for (int j = 0; j < frame.HotSpots.Count; j++)
{
BgfBitmapHotspot hs = frame.HotSpots[j];
if (j > 0)
response.Write(',');
response.Write("{\"i\":");
response.Write(hs.Index.ToString());
response.Write(",\"x\":");
response.Write(hs.X.ToString());
response.Write(",\"y\":");
response.Write(hs.Y.ToString());
response.Write('}');
}
response.Write("]}");
}
response.Write("],\"groups\":[");
for (int i = 0; i < entry.Bgf.FrameSets.Count; i++)
{
BgfFrameSet group = entry.Bgf.FrameSets[i];
if (i > 0)
response.Write(',');
response.Write('[');
for (int j = 0; j < group.FrameIndices.Count; j++)
{
if (j > 0)
response.Write(',');
response.Write(group.FrameIndices[j].ToString());
}
response.Write(']');
}
response.Write("]}");
}
// --------------------------------------------------------------------------------------------
// INVALID
// --------------------------------------------------------------------------------------------
else
{
context.Response.StatusCode = 404;
return;
}
}
public bool IsReusable
{
get { return true; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using KSP;
namespace panelfar
{
public static class PANELFARMeshSimplification
{
//Take the raw part geometry and simplify it so that further simplification of the entire vessel is faster
public static PANELFARPartLocalMesh PreProcessLocalMesh(PANELFARPartLocalMesh mesh)
{
//Array of vertices; indexing must not change
Vector3[] verts = new Vector3[mesh.vertexes.Length];
mesh.vertexes.CopyTo(verts, 0);
//Array of triangles; each triangle points to an index in verts
MeshIndexTriangle[] indexTris = new MeshIndexTriangle[mesh.triangles.Length];
mesh.triangles.CopyTo(indexTris, 0);
//Array of a list of triangles that contain a given vertex; indexing is same as verts, each index in list points to an index in indexTris
List<int>[] trisAttachedToVerts = GetTrisAttachedToVerts(verts, indexTris);
//Array of quadrics associated with a particular vertex; indexing is same as verts
Quadric[] vertQuadrics = CalculateVertQuadrics(verts, indexTris);
//A list of possible vertex pairs that can be contracted into a single point
MinHeap<MeshPairContraction> pairContractions = GeneratePairContractions(indexTris, verts, vertQuadrics);
int faces = (int)Math.Floor(indexTris.Length * 0.5);
faces = DecimateVertices(faces, ref pairContractions, ref verts, ref indexTris, ref trisAttachedToVerts, ref vertQuadrics);
//This will be used to update the old array (which has many empty elements) to a new vertex array and allow the indexTris to be updated as well
Dictionary<int, int> beforeIndexAfterIndex = new Dictionary<int, int>();
int currentIndex = 0;
List<Vector3> newVerts = new List<Vector3>();
for (int i = 0; i < verts.Length; i++)
{
Vector3 v = verts[i];
if (trisAttachedToVerts[i] != null)
{
beforeIndexAfterIndex.Add(i, currentIndex);
currentIndex++;
newVerts.Add(v);
}
}
MeshIndexTriangle[] newIndexTris = new MeshIndexTriangle[faces];
currentIndex = 0;
foreach(MeshIndexTriangle tri in indexTris)
{
if(tri != null)
{
MeshIndexTriangle newTri = new MeshIndexTriangle(beforeIndexAfterIndex[tri.v0], beforeIndexAfterIndex[tri.v1], beforeIndexAfterIndex[tri.v2]);
newIndexTris[currentIndex] = newTri;
currentIndex++;
}
}
mesh.vertexes = newVerts.ToArray();
mesh.triangles = newIndexTris;
return mesh;
}
public static int DecimateVertices(int targetFaces, ref MinHeap<MeshPairContraction> pairContractions, ref Vector3[] verts, ref MeshIndexTriangle[] indexTris, ref List<int>[] trisAttachedToVerts, ref Quadric[] vertQuadrics)
{
int validFaces = indexTris.Length;
int counter = 1;
StringBuilder debug = new StringBuilder();
debug.AppendLine("Target Faces: " + targetFaces);
try
{
while (validFaces > targetFaces)
{
debug.AppendLine("Iteration: " + counter + " Faces: " + validFaces);
//Get the pair contraction with the least error associated with it
MeshPairContraction pair = pairContractions.ExtractDominating();
debug.AppendLine("Contraction between vertices at indicies: " + pair.v0 + " and " + pair.v1);
debug.AppendLine("Tris attached to v0: " + trisAttachedToVerts[pair.v0].Count + " Tris attached to v1: " + trisAttachedToVerts[pair.v1].Count);
//Get faces that will be deleted / changed by contraction
ComputeContraction(ref pair, indexTris, trisAttachedToVerts);
//Act on faces, delete extra vertex, change all references to second vertex
validFaces -= ApplyContraction(ref pair, ref pairContractions, ref verts, ref indexTris, ref trisAttachedToVerts, ref vertQuadrics);
counter++;
}
for(int i = 0; i < indexTris.Length; i++)
{
MeshIndexTriangle tri = indexTris[i];
if (tri == null)
continue;
if (trisAttachedToVerts[tri.v0] == null)
{
debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v0);
}
if (trisAttachedToVerts[tri.v1] == null)
{
debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v1);
}
if (trisAttachedToVerts[tri.v2] == null)
{
debug.AppendLine("Tri at index " + i + " points to nonexistent vertex at index " + tri.v2);
}
}
debug.AppendLine("Final: Faces: " + validFaces);
}
catch (Exception e)
{
debug.AppendLine("Error: " + e.Message);
debug.AppendLine("Stack trace");
debug.AppendLine(e.StackTrace);
}
Debug.Log(debug.ToString());
return validFaces;
}
public static int ApplyContraction(ref MeshPairContraction pair, ref MinHeap<MeshPairContraction> pairContractions, ref Vector3[] verts, ref MeshIndexTriangle[] indexTris, ref List<int>[] trisAttachedToVerts, ref Quadric[] vertQuadrics)
{
int removedFaces = pair.deletedFaces.Count;
//Move v0, clear v1
verts[pair.v0] = pair.contractedPosition;
verts[pair.v1] = Vector3.zero;
foreach (int triIndex in trisAttachedToVerts[pair.v1])
if (!pair.deletedFaces.Contains(triIndex) && !trisAttachedToVerts[pair.v0].Contains(triIndex))
trisAttachedToVerts[pair.v0].Add(triIndex);
//Clear out all the tris attached to a non-existent vertex
trisAttachedToVerts[pair.v1] = null;
//Accumulate quadrics, clear unused one
vertQuadrics[pair.v0] += vertQuadrics[pair.v1];
vertQuadrics[pair.v1] = new Quadric();
//Adjust deformed triangles
foreach (int changedTri in pair.deformedFaces)
{
MeshIndexTriangle tri = indexTris[changedTri];
if (tri.v0.Equals(pair.v1))
tri.v0 = pair.v0;
else if (tri.v1.Equals(pair.v1))
tri.v1 = pair.v0;
else
tri.v2 = pair.v0;
indexTris[changedTri] = tri;
}
//Clear deleted triangles
foreach(int deletedTri in pair.deletedFaces)
{
indexTris[deletedTri] = null;
}
List<MeshPairContraction> pairList = pairContractions.ToList();
for (int i = 0; i < pairContractions.Count; i++)
{
MeshPairContraction otherPair = pairList[i];
if (otherPair.v0.Equals(pair.v1))
{
otherPair.v0 = pair.v0;
}
else if (otherPair.v1.Equals(pair.v1))
{
otherPair.v1 = pair.v0;
}
pairList[i] = otherPair;
}
int count = pairList.Count;
for (int i = 0; i < count; i++ )
{
MeshPairContraction iItem = pairList[i];
for(int j = i + 1; j < count; j++)
{
if (pairList[j].Equals(iItem))
{
pairList.RemoveAt(j); //Remove duplicate element
count--; //Reduce length to iterate over
j--; //Make sure not to skip over a duplicate
}
}
if(iItem.v1 == iItem.v0)
{
pairList.RemoveAt(i); //Remove degenerate edge
count--; //Reduce length to iterate over
i--; //Make sure not to skip over a duplicate
continue;
}
CalculateTargetPositionForPairContraction(ref iItem, verts, vertQuadrics);
pairList[i] = iItem;
}
pairContractions = new MinHeap<MeshPairContraction>(pairList);
return removedFaces;
}
public static void ComputeContraction(ref MeshPairContraction pair, MeshIndexTriangle[] indexTris, List<int>[] trisAttachedToVerts)
{
//This contains a list of all tris that will be changed by this contraction; boolean indicates whether they will be removed or not
Dictionary<int, bool> trisToChange = new Dictionary<int, bool>();
pair.deformedFaces.Clear();
pair.deletedFaces.Clear();
//Iterate through every triangle attached to vertex 0 of this pair and add them to the dict
foreach(int triIndex in trisAttachedToVerts[pair.v0])
{
if(indexTris[triIndex] != null)
trisToChange.Add(triIndex, false);
}
//Iterate through tris attached to vert 1...
foreach (int triIndex in trisAttachedToVerts[pair.v1])
{
if (indexTris[triIndex] == null)
continue;
//if the tri is already there, it will become degenerate during this contraction and should be removed
if (trisToChange.ContainsKey(triIndex))
trisToChange[triIndex] = true;
//else, add it and it will simply be deformed
else
trisToChange.Add(triIndex, false);
}
//Now, divide them into the appropriate lists
foreach(KeyValuePair<int, bool> triIndex in trisToChange)
{
if (triIndex.Value)
pair.deletedFaces.Add(triIndex.Key);
else
pair.deformedFaces.Add(triIndex.Key);
}
}
public static MinHeap<MeshPairContraction> GeneratePairContractions(MeshIndexTriangle[] indexTris, Vector3[] verts, Quadric[] vertQuadrics)
{
List<MeshPairContraction> pairContractions = new List<MeshPairContraction>();
foreach(MeshIndexTriangle tri in indexTris)
{
MeshPairContraction e0 = new MeshPairContraction(tri.v0, tri.v1),
e1 = new MeshPairContraction(tri.v1, tri.v2),
e2 = new MeshPairContraction(tri.v2, tri.v0);
if (!pairContractions.Contains(e0))
pairContractions.Add(e0);
if (!pairContractions.Contains(e1))
pairContractions.Add(e1);
if (!pairContractions.Contains(e2))
pairContractions.Add(e2);
}
//Calculate point that each pair contraction will contract to if it is to be done
CalculateTargetPositionForAllPairContractions(ref pairContractions, verts, vertQuadrics);
MinHeap<MeshPairContraction> heap = new MinHeap<MeshPairContraction>(pairContractions);
return heap;
}
public static void CalculateTargetPositionForAllPairContractions(ref List<MeshPairContraction> pairContractions, Vector3[] verts, Quadric[] vertQuadrics)
{
for (int i = 0; i < pairContractions.Count; i++)
{
MeshPairContraction pair = pairContractions[i];
CalculateTargetPositionForPairContraction(ref pair, verts, vertQuadrics);
pairContractions[i] = pair;
}
}
public static void CalculateTargetPositionForPairContraction(ref MeshPairContraction pair, Vector3[] verts, Quadric[] vertQuadrics)
{
Vector3 v0 = verts[pair.v0], v1 = verts[pair.v1];
Quadric Q0 = vertQuadrics[pair.v0], Q1 = vertQuadrics[pair.v1];
Quadric Q = Q0 + Q1;
if (Q.Optimize(ref pair.contractedPosition, 1e-12))
pair.error = Q.Evaluate(pair.contractedPosition);
else
{
double ei = Q.Evaluate(v0), ej = Q.Evaluate(v1);
if (ei < ej)
{
pair.error = ei;
pair.contractedPosition = v0;
}
else
{
pair.error = ej;
pair.contractedPosition = v1;
}
}
}
//This returns an array that contains (in each element) a list of indexes that specify which MeshIndexTriangles (in indexTris) are connected to which Vector3s (in verts)
public static List<int>[] GetTrisAttachedToVerts(Vector3[] verts, MeshIndexTriangle[] indexTris)
{
List<int>[] trisAttachedToVerts = new List<int>[verts.Length];
for (int i = 0; i < trisAttachedToVerts.Length; i++)
{
trisAttachedToVerts[i] = new List<int>();
}
for (int i = 0; i < indexTris.Length; i++)
{
MeshIndexTriangle tri = indexTris[i];
trisAttachedToVerts[tri.v0].Add(i);
trisAttachedToVerts[tri.v1].Add(i);
trisAttachedToVerts[tri.v2].Add(i);
}
return trisAttachedToVerts;
}
//Returns an array of quadrics for evaluating the error of each possible contraction
public static Quadric[] CalculateVertQuadrics(Vector3[] verts, MeshIndexTriangle[] indexTris)
{
Quadric[] vertQuadrics = new Quadric[verts.Length];
for (int i = 0; i < vertQuadrics.Length; i++ )
vertQuadrics[i] = new Quadric();
foreach (MeshIndexTriangle tri in indexTris)
{
Vector3 v0, v1, v2;
v0 = verts[tri.v0];
v1 = verts[tri.v1];
v2 = verts[tri.v2];
double area = PANELFARTriangleUtils.triangle_area(v0, v1, v2);
Vector4 p;
if (area > 0)
p = PANELFARTriangleUtils.triangle_plane(v0, v1, v2);
else
{
p = PANELFARTriangleUtils.triangle_plane(v2, v1, v0);
area = -area;
}
Quadric Q = new Quadric(p.x, p.y, p.z, p.w, area);
// Area-weight quadric and add it into the three quadrics for the corners
Q *= Q.area;
vertQuadrics[tri.v0] += Q;
vertQuadrics[tri.v1] += Q;
vertQuadrics[tri.v2] += Q;
}
return vertQuadrics;
}
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using log4net;
using System.ComponentModel;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using common;
using jm726.lib.wrapper;
using jm726.lib.wrapper.logger;
namespace jm726.lib.wrapper.logger {
/// <summary>
/// Class which uses the ISpy interface to record all method calls to a given object. These are recorded to Xml.
/// Can also play back recordings
///
/// ONLY PUBLIC PROPERTIES WITH GETTERS _AND_ SETTERS WILL BE LOGGED CORRECTLY
/// </summary>
/// <typeparam name="TToLog">The interface which is being logged.</typeparam>
public class XmlLogWriter<TToLog> : Wrapper<TToLog>, IXmlLogWriter<TToLog> where TToLog : class {
#region Private Fields
/// <summary>
/// The log4net logger object used to log information to the console or log events.
/// </summary>
private readonly ILog _logger;
/// <summary>
/// The name of this logger. This is the name of the type being logged with '_Logger' added onto the end.
/// </summary>
private readonly string _name;
/// <summary>
/// The XML document which stores the event logging document as it is being built.
/// </summary>
private XmlDocument _doc;
/// <summary>
/// The root XML node to which all events are to be appended as children.
/// </summary>
private XmlNode _root;
/// <summary>
/// The XML document being built up to log all the events happening to the wrapped instance of TToLog.
/// </summary>
private DateTime _lastEvent;
/// <summary>
/// Wether or not events are to be logged currently.
/// </summary>
private bool _logging;
/// <summary>
/// Whether or not to serialize the return value of the method.
/// </summary>
private bool _recordForPlayback;
#endregion
#region XmlLogWriter Properties
/// <inheritdoc />
public XmlDocument Log {
get { return _doc; }
}
#endregion
#region Constructor
/// <summary>
/// Constructor which creates a generic logger. Instantiates a series of helper fields and stores the TToLog instance which is to be wrapped by this logger.
/// </summary>
/// <param name="spy">The instance of TToLog which this logger will log calls to.</param>
public XmlLogWriter(TToLog instance, bool recordForPlayback = false, bool recursive = true)
: base(instance, "XmlLogWriter", recursive) {
_lastEvent = default(DateTime);
_recordForPlayback = recordForPlayback;
_name = typeof(TToLog).FullName + "_Logger";
_logger = LogManager.GetLogger(_name);
_doc = new XmlDocument();
XmlNode declaration = _doc.CreateXmlDeclaration("1.0", "utf-8", "yes");
_doc.AppendChild(declaration);
}
#endregion
#region Override Abstract Methods from Wrapper
public override void ReportMethodCallVoid(string methodName, object[] parameters) {
if (!_logging) {
CallMethod(methodName, parameters);
return;
}
MethodCall m = new MethodCall(GetMethod(methodName, parameters), WrappedInstance, parameters);
if (_recordForPlayback && !m.Type.Equals("Method") && !m.Type.Equals("PropertySet"))
return;
XmlNode callNode = m.Serialize(_doc, SwitchArgument);
callNode.Attributes.Append(GetTimeAttr());
_root.AppendChild(callNode);
}
public override object ReportMethodCallReturn(string methodName, object[] parameters) {
if (!_logging)
return CallMethod(methodName, parameters);
MethodCall m = new MethodCall(GetMethod(methodName, parameters), WrappedInstance, parameters);
if (_recordForPlayback && !m.Type.Equals("Method") && !m.Type.Equals("PropertySet"))
return m.Return;
XmlNode callNode = m.Serialize(_doc, SwitchArgument, _recordForPlayback);
callNode.Attributes.Append(GetTimeAttr());
_root.AppendChild(callNode);
return m.Return;
}
public override void ReportEventTriggered(string eventName, object[] parameters) {
//Do Nothing
}
/// <summary>
/// Log the time at which a method call was made.
/// </summary>
private XmlAttribute GetTimeAttr() {
XmlAttribute time = _doc.CreateAttribute("Time");
if (_lastEvent.Equals(default(DateTime)))
time.Value = "0";
else
time.Value = DateTime.Now.Subtract(_lastEvent).TotalMilliseconds + "";
_lastEvent = DateTime.Now;
return time;
}
#endregion
#region XmlLogWriter Methods
/// <inheritdoc />
public void StartRecording() {
if (_root != null)
_doc.RemoveChild(_root);
XmlNode root = _doc.CreateElement("Events");
_doc.AppendChild(root);
StartRecording(_doc);
}
public void StartRecording(XmlDocument doc) {
XmlNodeList roots = doc.GetElementsByTagName("Events");
if (roots.Count == 0)
throw new ArgumentException("Unable to append events to supplied XML document. Document is not in the correct format");
_doc = doc;
_doc.NodeInserted += (source, args) => {
if (args.NewParent.Name.Equals("Events"))
_lastEvent = DateTime.Now;
};
_root = roots[0];
_lastEvent = default(DateTime);
_logging = true;
}
/// <inheritdoc />
public void StopRecording() {
_logging = false;
}
/// <inheritdoc />
public void PauseRecording() {
_lastEvent = DateTime.Now;
_logging = false;
}
/// <inheritdoc />
public void RestartRecording() {
_logging = false;
}
#endregion
#region Util
/// <summary>
/// Used for extensibility.
///
/// Override this and check the type of the argument to define special behaviour for special types.
/// Original defined so that instance specific IDs can be swapped to general but less unique names in the XML
/// which can then be resolved back to new specific IDs when the sequence is played back.
/// </summary>
/// <param name="arg">The argument to swap for a different type.</param>
/// <returns>The type to swap the argument to.</returns>
protected virtual XmlNode SwitchArgument(ParameterInfo param, object arg) {
return null;
}
#endregion
}
} |
/**
* This file defines the fitness_params object.
*
* TODOs:
* - a few TODOs in the file but ok
*
* FINISHED!
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using toolbox;
/**
* namespace for biogas plant optimization
*
* Definition of:
* - fitness_params
* - objective function
* - weights used inside objective function
*
*/
namespace biooptim
{
/// <summary>
/// definition of fitness parameters used in objective function
/// </summary>
public partial class fitness_params
{
// -------------------------------------------------------------------------------------
// !!! CONSTRUCTOR METHODS !!!
// -------------------------------------------------------------------------------------
/// <summary>
/// Standard Constructor creates the fitness_params object with default params
/// </summary>
/// <param name="numDigesters">number of digesters on plant</param>
public fitness_params(int numDigesters/*biogas.plant myPlant*/)
{
set_params_to_default(/*myPlant*/numDigesters);
}
/// <summary>
/// Constructor used to read fitness_params out of a XML file
/// </summary>
/// <param name="XMLfile">name of the xml file</param>
public fitness_params(string XMLfile)
{
XmlTextReader reader= new System.Xml.XmlTextReader(XMLfile);
getParamsFromXMLReader(ref reader);
reader.Close();
}
// -------------------------------------------------------------------------------------
// !!! PUBLIC METHODS !!!
// -------------------------------------------------------------------------------------
/// <summary>
/// set fitness params to values read out of a xml file
/// </summary>
/// <param name="reader"></param>
public void getParamsFromXMLReader(ref XmlTextReader reader)
{
string xml_tag = "";
int digester_index = 0;
// do not set params, because plant is not known
// TODO - macht probleme wenn ein neuer parameter hinzugefügt wird, da dann
// dessen list leer bleibt
// im grunde müsste man am ende der funktion die listen füllen, welche
// leer geblieben sind mit default werten
bool do_while = true;
// go through the file
while (reader.Read() && do_while)
{
switch (reader.NodeType)
{
case System.Xml.XmlNodeType.Element: // this knot is an element
xml_tag = reader.Name;
while (reader.MoveToNextAttribute())
{ // read the attributes, here only the attribute of digester
// is of interest, all other attributes are ignored,
// actually there usally are no other attributes
if (xml_tag == "digester" && reader.Name == "index")
{
// TODO
// index of digester, not used at the moment
digester_index = Convert.ToInt32(reader.Value);
break;
}
}
if (xml_tag == "weights")
{
myWeights.getParamsFromXMLReader(ref reader);
}
else if (xml_tag == "setpoints")
{
mySetpoints.getParamsFromXMLReader(ref reader);
}
break;
case System.Xml.XmlNodeType.Text: // text, thus value, of each element
switch (xml_tag)
{
// TODO - use digester_index here, compare with size of pH_min, ...
// here we assume that params are given in the correct
// order, thus first the first digester, then the 2nd digester, ...
case "pH_min":
pH_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "pH_max":
pH_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "pH_optimum":
pH_optimum.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "TS_max":
TS_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "VFA_TAC_min":
VFA_TAC_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "VFA_TAC_max":
VFA_TAC_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "VFA_min":
VFA_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "VFA_max":
VFA_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "TAC_min":
TAC_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "HRT_min":
HRT_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "HRT_max":
HRT_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "OLR_max":
OLR_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "Snh4_max":
Snh4_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "Snh3_max":
Snh3_max.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "AcVsPro_min":
AcVsPro_min.Add(System.Xml.XmlConvert.ToDouble(reader.Value));
break;
case "TS_feed_max":
_TS_feed_max= System.Xml.XmlConvert.ToDouble(reader.Value);
break;
case "HRT_plant_min":
_HRT_plant_min = System.Xml.XmlConvert.ToDouble(reader.Value);
break;
case "HRT_plant_max":
_HRT_plant_max = System.Xml.XmlConvert.ToDouble(reader.Value);
break;
case "OLR_plant_max":
_OLR_plant_max = System.Xml.XmlConvert.ToDouble(reader.Value);
break;
// read in manurebonus
case "manurebonus":
_manurebonus = System.Xml.XmlConvert.ToBoolean(reader.Value);
break;
case "fitness_function":
_fitness_function = reader.Value;
break;
case "nObjectives":
_nObjectives = System.Xml.XmlConvert.ToInt32(reader.Value);
break;
//case "Ndelta":
// _Ndelta = System.Xml.XmlConvert.ToInt32(reader.Value);
// break;
}
break;
case System.Xml.XmlNodeType.EndElement: // end of fitness_params
if (reader.Name == "fitness_params")
do_while = false; // end while loop
break;
}
}
}
/// <summary>
/// Returns fitness params as XML string, such that it can be saved
/// in a XML file
/// </summary>
/// <returns></returns>
public string getParamsAsXMLString()
{
StringBuilder sb = new StringBuilder();
sb.Append("<fitness_params>\n");
for (int idigester = 0; idigester < pH_min.Count; idigester++)
{
sb.Append(String.Format("<digester index= \"{0}\">\n", idigester));
sb.Append(xmlInterface.setXMLTag("pH_min", pH_min[idigester]));
sb.Append(xmlInterface.setXMLTag("pH_max", pH_max[idigester]));
sb.Append(xmlInterface.setXMLTag("pH_optimum", pH_optimum[idigester]));
sb.Append(xmlInterface.setXMLTag("TS_max", TS_max[idigester]));
sb.Append(xmlInterface.setXMLTag("VFA_TAC_min", VFA_TAC_min[idigester]));
sb.Append(xmlInterface.setXMLTag("VFA_TAC_max", VFA_TAC_max[idigester]));
sb.Append(xmlInterface.setXMLTag("VFA_min", VFA_min[idigester]));
sb.Append(xmlInterface.setXMLTag("VFA_max", VFA_max[idigester]));
sb.Append(xmlInterface.setXMLTag("TAC_min", TAC_min[idigester]));
sb.Append(xmlInterface.setXMLTag("HRT_min", HRT_min[idigester]));
sb.Append(xmlInterface.setXMLTag("HRT_max", HRT_max[idigester]));
sb.Append(xmlInterface.setXMLTag("OLR_max", OLR_max[idigester]));
sb.Append(xmlInterface.setXMLTag("Snh4_max", Snh4_max[idigester]));
sb.Append(xmlInterface.setXMLTag("Snh3_max", Snh3_max[idigester]));
sb.Append(xmlInterface.setXMLTag("AcVsPro_min", AcVsPro_min[idigester]));
sb.Append("</digester>\n");
}
sb.Append(xmlInterface.setXMLTag("TS_feed_max", TS_feed_max));
// add weights
sb.Append(myWeights.getParamsAsXMLString());
sb.Append(xmlInterface.setXMLTag("HRT_plant_min", HRT_plant_min));
sb.Append(xmlInterface.setXMLTag("HRT_plant_max", HRT_plant_max));
sb.Append(xmlInterface.setXMLTag("OLR_plant_max", OLR_plant_max));
// write manurebonus inside file
sb.Append(xmlInterface.setXMLTag("manurebonus", manurebonus));
sb.Append(xmlInterface.setXMLTag("fitness_function", fitness_function));
sb.Append(xmlInterface.setXMLTag("nObjectives", nObjectives));
//sb.Append(xmlInterface.setXMLTag("Ndelta", _Ndelta));
// add setpoints
sb.Append(mySetpoints.getParamsAsXMLString());
//
sb.Append("</fitness_params>\n");
return sb.ToString();
}
/// <summary>
/// Saves the fitness_params in a xml file
/// </summary>
/// <param name="XMLfile">name of the xml file</param>
public void saveAsXML(string XMLfile)
{
StreamWriter writer = File.CreateText(XMLfile);
writer.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
writer.Write(getParamsAsXMLString());
writer.Close();
}
/// <summary>
/// Prints the fitness params to a string, such that the string
/// can be written to a console.
///
/// For Custom Numeric Format Strings see:
///
/// http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
///
/// </summary>
/// <returns></returns>
public string print()
{
StringBuilder sb = new StringBuilder();
sb.Append(" ---------- fitness_params: ---------- \r\n");
for (int idigester = 0; idigester < pH_min.Count; idigester++)
{
sb.Append(String.Format("digester: {0}\n", idigester));
sb.Append(String.Format("pH_min: {0}\t\t\t", pH_min[idigester]));
sb.Append(String.Format("pH_max: {0}\t\t\t", pH_max[idigester]));
sb.Append(String.Format("pH_optimum: {0}\n", pH_optimum[idigester]));
sb.Append(String.Format("TS_max: {0}\t\t\t", TS_max[idigester]));
sb.Append(String.Format("VFA_TAC_min: {0}\t\t\t", VFA_TAC_min[idigester]));
sb.Append(String.Format("VFA_TAC_max: {0}\n", VFA_TAC_max[idigester]));
sb.Append(String.Format("VFA_min: {0}\t\t\t", VFA_min[idigester]));
sb.Append(String.Format("VFA_max: {0}\t\t\t", VFA_max[idigester]));
sb.Append(String.Format("TAC_min: {0}\n", TAC_min[idigester]));
sb.Append(String.Format("HRT_min: {0}\t\t\t", HRT_min[idigester]));
sb.Append(String.Format("HRT_max: {0}\t\t\t", HRT_max[idigester]));
sb.Append(String.Format("OLR_max: {0}\n", OLR_max[idigester]));
sb.Append(String.Format("Snh4_max: {0}\t\t\t", Snh4_max[idigester]));
sb.Append(String.Format("Snh3_max: {0}\t\t\t", Snh3_max[idigester]));
sb.Append(String.Format("AcVsPro_min: {0}\r\n", AcVsPro_min[idigester]));
}
sb.Append(String.Format("TS_feed_max: {0}\r\n", TS_feed_max));
// add weights
sb.Append(myWeights.print());
sb.Append(String.Format("\nHRT_plant_min: {0}\t\t\t", HRT_plant_min));
sb.Append(String.Format("HRT_plant_max: {0}\t\t\t", HRT_plant_max));
sb.Append(String.Format("OLR_plant_max: {0}\n", OLR_plant_max));
sb.Append(String.Format("manurebonus: {0}\n", manurebonus));
sb.Append(String.Format("fitness_function: {0}\t\t", fitness_function));
sb.Append(String.Format("nObjectives: {0}\r\n", nObjectives));
//sb.Append(String.Format("Ndelta: {0}\n", _Ndelta));
// add setpoints
sb.Append(mySetpoints.print());
sb.Append(" ---------- ---------- ---------- ---------- \n");
return sb.ToString();
}
}
}
|
using System;
using System.Linq;
using LeagueSharp;
using LeagueSharp.Common;
using Slutty_ryze.Properties;
namespace Slutty_ryze
{
internal class Program
{
readonly static Random Seeder = new Random();
private static bool _casted;
private static int _lastw;
#region onload
private static void Main(string[] args)
{
if (args == null) throw new ArgumentNullException("args");
// So you can test if it in VS wihout crahses
#if !DEBUG
CustomEvents.Game.OnGameLoad += OnLoad;
#endif
}
private static void OnLoad(EventArgs args)
{
if (GlobalManager.GetHero.ChampionName != Champion.ChampName)
return;
Console.WriteLine(@"Loading Your Slutty Ryze");
Humanizer.AddAction("generalDelay",35.0f);
Champion.Q = new Spell(SpellSlot.Q, 865);
Champion.Qn = new Spell(SpellSlot.Q, 865);
Champion.W = new Spell(SpellSlot.W, 585);
Champion.E = new Spell(SpellSlot.E, 585);
Champion.R = new Spell(SpellSlot.R);
Champion.Q.SetSkillshot(0.26f, 50f, 1700f, true, SkillshotType.SkillshotLine);
Champion.Qn.SetSkillshot(0.26f, 50f, 1700f, false, SkillshotType.SkillshotLine);
//assign menu from MenuManager to Config
Console.WriteLine(@"Loading Your Slutty Menu...");
GlobalManager.Config = MenuManager.GetMenu();
GlobalManager.Config.AddToMainMenu();
Printmsg("Ryze Assembly Loaded");
Printmsg1("Current Version: " + typeof(Program).Assembly.GetName().Version);
Printmsg2("Don't Forget To " + "<font color='#00ff00'>[Upvote]</font> <font color='#FFFFFF'>" + "The Assembly In The Databse" + "</font>");
//Other damge inficators in MenuManager ????
GlobalManager.DamageToUnit = Champion.GetComboDamage;
Drawing.OnDraw += DrawManager.Drawing_OnDraw;
Game.OnUpdate += Game_OnUpdate;
#pragma warning disable 618
Interrupter.OnPossibleToInterrupt += Champion.RyzeInterruptableSpell;
Spellbook.OnCastSpell += Champion.OnProcess;
#pragma warning restore 618
Orbwalking.BeforeAttack += Champion.Orbwalking_BeforeAttack;
//CustomEvents.Unit.OnDash += Champion;
ShowDisplayMessage();
}
#endregion
private static void Printmsg(string message)
{
Game.PrintChat(
"<font color='#6f00ff'>[Slutty Ryze]:</font> <font color='#FFFFFF'>" + message + "</font>");
}
private static void Printmsg1(string message)
{
Game.PrintChat(
"<font color='#ff00ff'>[Slutty Ryze]:</font> <font color='#FFFFFF'>" + message + "</font>");
}
private static void Printmsg2(string message)
{
Game.PrintChat(
"<font color='#00abff'>[Slutty Ryze]:</font> <font color='#FFFFFF'>" + message + "</font>");
}
#region onGameUpdate
private static void ShowDisplayMessage()
{
var r = new Random();
var txt = Resources.display.Split('\n');
switch (r.Next(1, 3))
{
case 2:
txt = Resources.display2.Split('\n');
break;
case 3:
txt = Resources.display3.Split('\n');
break;
}
foreach (var s in txt)
Console.WriteLine(s);
#region L# does not allow D:
//try
//{
// var sr = new System.IO.StreamReader(System.Net.WebRequest.Create(string.Format("http://www.fiikus.net/asciiart/pokemon/{0}{1}{2}.txt", r.Next(0, 1), r.Next(0, 3), r.Next(0, 9))).GetResponse().GetResponseStream());
// string line;
// while ((line = sr.ReadLine()) != null)
// {
// Console.WriteLine(line);
// }
//}
//catch
//{
// // ignored
//}
#endregion
}
private static void Game_OnUpdate(EventArgs args)
{
try // lazy
{
if (GlobalManager.Config.Item("test").GetValue<KeyBind>().Active)
{
GlobalManager.GetHero.IssueOrder(GameObjectOrder.MoveTo, Game.CursorPos);
var targets = TargetSelector.GetTarget(Champion.W.Range, TargetSelector.DamageType.Magical);
if (targets == null)
return;
if (Champion.W.IsReady())
{
LaneOptions.CastW(targets);
{
_lastw = Environment.TickCount;
}
}
if (Environment.TickCount - _lastw >= 700 - Game.Ping)
{
if (Champion.Q.IsReady())
{
LaneOptions.CastQn(targets);
_casted = true;
}
}
if (_casted)
{
LaneOptions.CastE(targets);
LaneOptions.CastQn(targets);
_casted = false;
}
}
if (GlobalManager.Config.Item("chase").GetValue<KeyBind>().Active)
{
GlobalManager.GetHero.IssueOrder(GameObjectOrder.MoveTo, Game.CursorPos);
var targets = TargetSelector.GetTarget(Champion.W.Range + 200, TargetSelector.DamageType.Magical);
if (targets == null)
return;
if (GlobalManager.Config.Item("usewchase").GetValue<bool>())
LaneOptions.CastW(targets);
if (GlobalManager.Config.Item("chaser").GetValue<bool>() &&
targets.Distance(GlobalManager.GetHero) > Champion.W.Range + 200)
Champion.R.Cast();
}
if (GlobalManager.GetHero.IsDead)
return;
if (GlobalManager.GetHero.IsRecalling())
return;
if (Champion.casted == false)
{
MenuManager.Orbwalker.SetAttack(true);
}
var target = TargetSelector.GetTarget(Champion.Q.Range, TargetSelector.DamageType.Magical);
if (GlobalManager.Config.Item("doHuman").GetValue<bool>())
{
if (!Humanizer.CheckDelay("generalDelay")) // Wait for delay for all other events
{
Console.WriteLine(@"Waiting on Human delay");
return;
}
//Console.WriteLine("Seeding Human Delay");
var nDelay = Seeder.Next(GlobalManager.Config.Item("minDelay").GetValue<Slider>().Value, GlobalManager.Config.Item("maxDelay").GetValue<Slider>().Value); // set a new random delay :D
Humanizer.ChangeDelay("generalDelay", nDelay);
}
if (MenuManager.Orbwalker.ActiveMode == Orbwalking.OrbwalkingMode.Combo)
{
//
// if (target.IsValidTarget()
// && GlobalManager.GetHero.Distance(target) > 400 && (Champion.Q.IsReady() && Champion.W.IsReady() && Champion.E.IsReady()))
// {
// MenuManager.Orbwalker.SetAttack(false);
// }
//
// if (target.IsValidTarget() && GlobalManager.GetHero.Distance(target) > 400
// && (GlobalManager.GetPassiveBuff == 4 || GlobalManager.GetHero.HasBuff("ryzepassivecharged"))
// &&
// ((!Champion.Q.IsReady() && !Champion.W.IsReady() && !Champion.E.IsReady()) ||
// (Champion.Q.IsReady() && Champion.W.IsReady() && Champion.E.IsReady())))
// {
// MenuManager.Orbwalker.SetAttack(false);
// }
Champion.AABlock();
LaneOptions.ImprovedCombo();
if (target.Distance(GlobalManager.GetHero) >=
GlobalManager.Config.Item("minaarange").GetValue<Slider>().Value)
{
MenuManager.Orbwalker.SetAttack(false);
}
else
{
MenuManager.Orbwalker.SetAttack(true);
}
}
if (MenuManager.Orbwalker.ActiveMode == Orbwalking.OrbwalkingMode.Mixed)
{
LaneOptions.Mixed();
MenuManager.Orbwalker.SetAttack(true);
}
if (MenuManager.Orbwalker.ActiveMode == Orbwalking.OrbwalkingMode.LaneClear)
{
if (!GlobalManager.Config.Item("disablelane").GetValue<KeyBind>().Active)
LaneOptions.LaneClear();
LaneOptions.JungleClear();
}
if (MenuManager.Orbwalker.ActiveMode == Orbwalking.OrbwalkingMode.LastHit)
LaneOptions.LastHit();
if (MenuManager.Orbwalker.ActiveMode == Orbwalking.OrbwalkingMode.None)
{
if (GlobalManager.Config.Item("tearS").GetValue<KeyBind>().Active)
ItemManager.TearStack();
if (GlobalManager.Config.Item("autoPassive").GetValue<KeyBind>().Active)
Champion.AutoPassive();
ItemManager.Potion();
MenuManager.Orbwalker.SetAttack(true);
}
if (GlobalManager.Config.Item("UseQauto").GetValue<bool>() && target != null)
{
if (Champion.Q.IsReady() && target.IsValidTarget(Champion.Q.Range))
Champion.Q.Cast(target);
}
// Seplane();
ItemManager.Item();
Champion.KillSteal();
ItemManager.Potion();
if (GlobalManager.Config.Item("level").GetValue<bool>())
{
AutoLevelManager.LevelUpSpells();
}
if (!GlobalManager.Config.Item("autow").GetValue<bool>() || !target.UnderTurret(true)) return;
if (target == null)
return;
if (!ObjectManager.Get<Obj_AI_Turret>()
.Any(turret => turret.IsValidTarget(300) && turret.IsAlly && turret.Health > 0))
return;
Champion.W.CastOnUnit(target);
// DebugClass.ShowDebugInfo(true);
}
catch
{
// ignored
}
}
#endregion
/*
private static void Seplane()
{
if (GlobalManager.GetHero.IsValid &&
GlobalManager.Config.Item("seplane").GetValue<KeyBind>().Active)
{
ObjectManager.GlobalManager.GetHero.IssueOrder(GameObjectOrder.MoveTo, Game.CursorPos);
LaneClear();
}
}
*/
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEditor;
using System.IO;
public class Serializer : MonoBehaviour {
//save defaults are only used to set the data used when initializing that map the next time.
string saveFile;
string loadFile;
string fileName;
public string saveData;
public string defaults;
CharacterControllerScript player;
// Use this for initialization
void Start () {
player = Globals.playerScript;
//save on disc
saveData = Path.Combine(Application.persistentDataPath, "SaveData");
// defaults included in project
defaults = "Assets/Resources/Defaults/";
CreateDirectories();
}
// Update is called once per frame
void Update () {
}
void CreateDirectories()
{
if(!Directory.Exists(saveData))
{
Directory.CreateDirectory(saveData);
}
/*if(!Directory.Exists(defaults))
{
Directory.CreateDirectory(defaults);
}*/
}
public void SavePlayerData()
{
PlayerSaveData playerData = new PlayerSaveData()
{
level = player.level,
statPoints = player.statPoints,
skillPoints = player.skillPoints,
spentStatPoints = player.spentStatPoints,
spentSkillPoints = player.spentSkillPoints,
currentHealth = player.currentHealth,
maxHealth = player.maxHealth,
currentXP = player.currentXP,
xpToLevel = player.xpToLevel,
atk = player.atk,
atkItemBonus = player.atkItemBonus,
statAtk = player.statAtk,
def = player.def,
defItemBonus = player.defItemBonus,
statDef = player.statDef,
skill1Lvl = player.skills[0].level,
skill2Lvl = player.skills[1].level,
skill3Lvl = player.skills[2].level,
skill4Lvl = player.skills[3].level,
lookingX = (int)player.looking.x,
lookingY = (int)player.looking.y,
direction = player.direction,
bronzeKeys = player.bronzeKeys,
silverKeys = player.silverKeys,
goldKeys = player.goldKeys,
currentMap = Globals.currentMap,
redOrbState = player.redOrbState,
blueOrbState = player.blueOrbState,
storyProgress = player.storyProgress,
sideQuests = new List<PlayerSaveData.PlayerQuests>()
};
foreach(Quest q in player.quests)
{
PlayerSaveData.PlayerQuests quest = new PlayerSaveData.PlayerQuests();
quest.questName = q.questName;
quest.description = q.description;
quest.complete = q.complete;
quest.progress = q.progress;
playerData.sideQuests.Add(quest);
}
string json = JsonUtility.ToJson(playerData);
string fileName = Path.Combine(saveData, "player.json");
if(File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
SavePlayerInventory();
//Debug.Log(json);
Debug.Log(fileName);
}
public void SavePlayerInventory()
{
PlayerInventory playerInventory = new PlayerInventory();
try
{
foreach (InventoryItemBase i in player.inventory)
{
playerInventory.inventoryItems.Add(i);
}
}
catch
{
Debug.Log("Empty Inventory");
}
string json = JsonUtility.ToJson(playerInventory);
string fileName = Path.Combine(saveData, "inventory.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
public void LoadPlayerInventory()
{
try
{
fileName = Path.Combine(saveData, "inventory.json");
loadFile = File.ReadAllText(fileName);
PlayerInventory load = JsonUtility.FromJson<PlayerInventory>(loadFile);
if (load.inventoryItems.Count > 0)
{
player.inventory.Clear();
foreach (InventoryItemBase i in load.inventoryItems)
{
player.inventory.Add(i);
}
}
}
catch
{
Debug.Log("Problem loading inventory");
}
}
public void LoadPlayerData()
{
fileName = Path.Combine(saveData, "player.json");
loadFile = File.ReadAllText(fileName);
PlayerSaveData load = JsonUtility.FromJson<PlayerSaveData>(loadFile);
//Debug.Log(load.level+ "" + load.statPoints+""+ load.skillPoints+ "" +load.currentMap);
player.level = load.level;
player.statPoints = load.statPoints;
player.skillPoints = load.skillPoints;
player.spentStatPoints = load.spentStatPoints;
player.spentSkillPoints = load.spentSkillPoints;
player.maxHealth = load.maxHealth;
player.currentHealth = load.currentHealth;
player.xpToLevel = load.xpToLevel;
player.currentXP = load.currentXP;
player.atk = load.atk;
player.statAtk = load.statAtk;
player.atkItemBonus = load.atkItemBonus;
player.def = load.def;
player.statDef = load.statDef;
player.defItemBonus = load.defItemBonus;
player.skills[0].level = load.skill1Lvl;
player.skills[1].level = load.skill2Lvl;
player.skills[2].level = load.skill3Lvl;
player.skills[3].level = load.skill4Lvl;
player.looking = new Vector2(load.lookingX, load.lookingY);
player.direction = load.direction;
player.bronzeKeys = load.bronzeKeys;
player.silverKeys = load.silverKeys;
player.goldKeys = load.goldKeys;
player.redOrbState = load.redOrbState;
player.blueOrbState = load.blueOrbState;
player.storyProgress = load.storyProgress;
//for (int x = 0; x < load.sideQuests.Count; x++)
// {
// Debug.Log(load.sideQuests[x].questName);
// Debug.Log(load.sideQuests[x].description);
// Debug.Log(load.sideQuests[x].complete);
// Debug.Log(load.sideQuests[x].progress);
// player.quests.Add(new Quest(load.sideQuests[x].questName, load.sideQuests[x].description, load.sideQuests[x].complete, load.sideQuests[0].progress));
//}
foreach (PlayerSaveData.PlayerQuests q in load.sideQuests)
{
//Debug.Log(q.questName);
//Debug.Log(q.description);
//Debug.Log(q.complete);
//Debug.Log(q.progress);
player.quests.Add(new Quest(q.questName, q.description, q.complete, q.progress));
//Debug.Log(player.quests[0].questName);
}
LoadPlayerInventory();
}
public string SavedFloor()
{
//used to load in saved floor
fileName = Path.Combine(saveData, "player.json");
loadFile = File.ReadAllText(fileName);
PlayerSaveData load = JsonUtility.FromJson<PlayerSaveData>(loadFile);
return load.currentMap;
}
//public void SaveMap(int x, int y)
//{
// MapSaveData mapData = new MapSaveData()
// {
// returnPointX = x,
// returnPointY = y
// };
// string json = JsonUtility.ToJson(mapData);
// string fileName = Path.Combine(saveData, SceneManager.GetActiveScene().name + ".json");
// if (File.Exists(fileName))
// {
// File.Delete(fileName);
// }
// File.WriteAllText(fileName, json);
//}
//public void LoadMap(string nextMap)
//{
// fileName = Path.Combine(saveData, nextMap + ".json");
// loadFile = File.ReadAllText(fileName);
// MapSaveData load = JsonUtility.FromJson<MapSaveData>(loadFile);
// player.gameObject.transform.position = new Vector2(load.returnPointX + .5f, load.returnPointY-.5f);
//}
/*public void SaveEnemies()
{
try
{
EnemiesOnMap mapEnemies = new EnemiesOnMap
{
mapEnemyInfo = new List<EnemiesOnMap.EnemyInfo>()
};
foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
{
EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>();
EnemiesOnMap.EnemyInfo newInfo = new EnemiesOnMap.EnemyInfo();
{
newInfo.enemyName = currentEnemy.enemyName.ToString();
newInfo.posX = (int)currentEnemy.transform.position.x;
newInfo.posY = (int)currentEnemy.transform.position.y;
newInfo.alive = currentEnemy.alive;
newInfo.heldItem = currentEnemy.heldItem;
}
mapEnemies.mapEnemyInfo.Add(newInfo);
}
string json = JsonUtility.ToJson(mapEnemies);
string fileName = Path.Combine(saveData, Globals.currentMap + "enemies.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Enemies here");
}
}
public void SaveEnemiesDefault()
{
try
{
EnemiesOnMap mapEnemies = new EnemiesOnMap
{
mapEnemyInfo = new List<EnemiesOnMap.EnemyInfo>()
};
foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
{
EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>();
EnemiesOnMap.EnemyInfo newInfo = new EnemiesOnMap.EnemyInfo();
{
newInfo.enemyName = currentEnemy.enemyName.ToString();
newInfo.posX = (int)currentEnemy.transform.position.x;
newInfo.posY = (int)currentEnemy.transform.position.y;
newInfo.alive = currentEnemy.alive;
newInfo.heldItem = currentEnemy.heldItem;
}
mapEnemies.mapEnemyInfo.Add(newInfo);
Destroy(enemy);
}
string json = JsonUtility.ToJson(mapEnemies);
string fileName = Path.Combine(defaults, Globals.currentMap + "defaultenemies.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Enemies here");
}
}
public void LoadEnemies()
{try
{
StartCoroutine(LoadEnemiesDelay());
}
catch
{
Debug.Log("No Enemies Loaded");
}
}
public IEnumerator LoadEnemiesDelay()
{
yield return new WaitForSeconds(.5f);
if (File.Exists(Path.Combine(saveData, Globals.currentMap + "enemies.json")))
{
fileName = Path.Combine(saveData, Globals.currentMap + "enemies.json");
}
else
{
fileName = Path.Combine(defaults, Globals.currentMap + "defaultenemies.json");
}
Debug.Log("loading enemies from " + fileName);
loadFile = File.ReadAllText(fileName);
EnemiesOnMap load = JsonUtility.FromJson<EnemiesOnMap>(loadFile);
Container enemyContainer = GameObject.FindWithTag("Container").GetComponent<Container>();
//foreach (EnemiesOnMap.EnemyInfo info in load.mapEnemyInfo)
//{
// //load into a list.
// //enemyContainer.CreateEnemy(info.enemyName, info.posX, info.posY, info.alive);
//}
for(int x = load.mapEnemyInfo.Count -1; x>-1; x--)
{
//start new enemy
//set its info to load[x]
//create from container
//clear entry from list
EnemiesOnMap.EnemyInfo e = load.mapEnemyInfo[x];
enemyContainer.CreateEnemy(e.enemyName, e.posX, e.posY, e.alive,e.heldItem);
load.mapEnemyInfo.RemoveAt(x);
}
yield return null;
}
public void SaveItems()
{
try
{
ItemsOnMap mapItems = new ItemsOnMap
{
mapItemInfo = new List<ItemsOnMap.ItemInfo>()
};
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Item"))
{
ItemBase currentItem = item.GetComponent<ItemBase>();
ItemsOnMap.ItemInfo newInfo = new ItemsOnMap.ItemInfo();
{
newInfo.itemName = currentItem.itemName.ToString();
newInfo.value = currentItem.value;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
//newInfo.active = currentItem.active;
}
mapItems.mapItemInfo.Add(newInfo);
}
string json = JsonUtility.ToJson(mapItems);
string fileName = Path.Combine(saveData, Globals.currentMap + "items.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Items Here");
}
}
public void SaveItemsDefault()
{
try
{
ItemsOnMap mapItems = new ItemsOnMap
{
mapItemInfo = new List<ItemsOnMap.ItemInfo>()
};
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Item"))
{
ItemBase currentItem = item.GetComponent<ItemBase>();
ItemsOnMap.ItemInfo newInfo = new ItemsOnMap.ItemInfo();
{
newInfo.itemName = currentItem.itemName.ToString();
newInfo.value = currentItem.value;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
//newInfo.active = currentItem.active;
}
mapItems.mapItemInfo.Add(newInfo);
Destroy(item);
}
string json = JsonUtility.ToJson(mapItems);
string fileName = Path.Combine(defaults, Globals.currentMap + "defaultitems.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Items Here");
}
}
public void LoadItems()
{
try
{
StartCoroutine(LoadItemsDelay());
}
catch
{
Debug.Log("No items loaded");
}
}
public IEnumerator LoadItemsDelay()
{
yield return new WaitForSeconds(.5f);
if (File.Exists(Path.Combine(saveData, Globals.currentMap + "items.json")))
{
fileName = Path.Combine(saveData, Globals.currentMap + "items.json");
}
else
{
fileName = Path.Combine(defaults, Globals.currentMap + "defaultitems.json");
}
Debug.Log("loading items from " + fileName);
loadFile = File.ReadAllText(fileName);
ItemsOnMap load = JsonUtility.FromJson<ItemsOnMap>(loadFile);
Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>();
//foreach (ItemsOnMap.ItemInfo info in load.mapItemInfo)
//{
// Debug.Log(info.itemName);
// itemContainer.CreateItem(info.itemName, info.value, info.posX, info.posY, info.active);
//}
for (int x = load.mapItemInfo.Count - 1; x > -1; x--)
{
ItemsOnMap.ItemInfo i = load.mapItemInfo[x];
itemContainer.CreateItem(i.itemName,i.value, i.posX, i.posY);
load.mapItemInfo.RemoveAt(x);
}
yield return null;
}
public void SaveDoors()
{
try
{
DoorsOnMap mapDoors = new DoorsOnMap
{
mapDoorInfo = new List<DoorsOnMap.DoorInfo>()
};
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Door"))
{
DoorBase currentItem = item.GetComponent<DoorBase>();
DoorsOnMap.DoorInfo newInfo = new DoorsOnMap.DoorInfo();
{
newInfo.doorType = currentItem.doorType.ToString();
newInfo.doorName = currentItem.doorName;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
}
mapDoors.mapDoorInfo.Add(newInfo);
}
string json = JsonUtility.ToJson(mapDoors);
string fileName = Path.Combine(saveData, Globals.currentMap + "doors.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Doors Here");
}
}
public void SaveDoorsDefault()
{
try
{
DoorsOnMap mapDoors = new DoorsOnMap
{
mapDoorInfo = new List<DoorsOnMap.DoorInfo>()
};
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Door"))
{
DoorBase currentItem = item.GetComponent<DoorBase>();
DoorsOnMap.DoorInfo newInfo = new DoorsOnMap.DoorInfo();
{
newInfo.doorType = currentItem.doorType.ToString();
newInfo.doorName = currentItem.doorName;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
}
mapDoors.mapDoorInfo.Add(newInfo);
Destroy(item);
}
string json = JsonUtility.ToJson(mapDoors);
string fileName = Path.Combine(defaults, Globals.currentMap + "defaultdoors.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Doors Here");
}
}
public void LoadDoors()
{
StartCoroutine(LoadDoorsDelay());
}
public IEnumerator LoadDoorsDelay()
{
yield return new WaitForSeconds(.5f);
try
{
if (File.Exists(Path.Combine(saveData, Globals.currentMap + "doors.json")))
{
fileName = Path.Combine(saveData, Globals.currentMap + "doors.json");
}
else
{
fileName = Path.Combine(defaults, Globals.currentMap + "defaultdoors.json");
}
Debug.Log("loading doors from " + fileName);
loadFile = File.ReadAllText(fileName);
DoorsOnMap load = JsonUtility.FromJson<DoorsOnMap>(loadFile);
Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>();
//foreach (DoorsOnMap.DoorInfo info in load.mapDoorInfo)
//{
// itemContainer.CreateDoor(info.doorType, info.posX, info.posY);
//}
try
{
for (int x = load.mapDoorInfo.Count - 1; x > -1; x--)
{
DoorsOnMap.DoorInfo d = load.mapDoorInfo[x];
itemContainer.CreateDoor(d.doorType, d.doorName, d.posX, d.posY);
load.mapDoorInfo.RemoveAt(x);
}
}
catch
{
for (int x = load.mapDoorInfo.Count - 1; x > -1; x--)
{
DoorsOnMap.DoorInfo d = load.mapDoorInfo[x];
itemContainer.CreateDoor(d.doorType, d.posX, d.posY);
load.mapDoorInfo.RemoveAt(x);
}
}
}
catch { }
yield return null;
}*/
public void SaveMapData(bool d)
{
//true = default; false = other
fileName = "";
MapData mapData = new MapData
{
mapDoorInfo = new List<MapData.Door>(),
mapEnemyInfo = new List<MapData.Enemy>(),
mapItemInfo = new List<MapData.Item>(),
mapBinaryObjectInfo = new List<MapData.BinaryObject>()
};
//Save Doors
try
{
foreach (GameObject door in GameObject.FindGameObjectsWithTag("Door"))
{
DoorBase currentItem = door.GetComponent<DoorBase>();
MapData.Door newInfo = new MapData.Door();
{
//newInfo.doorType = currentItem.doorType.ToString();
newInfo.doorName = currentItem.doorName;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
}
mapData.mapDoorInfo.Add(newInfo);
Destroy(door);
}
}
catch
{
Debug.Log("problem saving doors");
}
//Save Items
try
{
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Item"))
{
ItemBase currentItem = item.GetComponent<ItemBase>();
MapData.Item newInfo = new MapData.Item();
{
newInfo.itemName = currentItem.itemName.ToString();
newInfo.value = currentItem.value;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
//newInfo.active = currentItem.active;
}
mapData.mapItemInfo.Add(newInfo);
Destroy(item);
}
}
catch
{
Debug.Log("problem saving items");
}
//Save Enemies
try
{
foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
{
EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>();
MapData.Enemy newInfo = new MapData.Enemy();
{
newInfo.enemyName = currentEnemy.enemyName.ToString();
newInfo.posX = (int)currentEnemy.transform.position.x;
newInfo.posY = (int)currentEnemy.transform.position.y;
newInfo.alive = currentEnemy.alive;
newInfo.heldItem = currentEnemy.heldItem;
}
mapData.mapEnemyInfo.Add(newInfo);
Destroy(enemy);
}
}
catch
{
Debug.Log("problem saving enemies");
}
//Save BinaryItems
try
{
foreach(GameObject binary in GameObject.FindGameObjectsWithTag("Button"))
{
BinaryObject currentObject = binary.GetComponent<BinaryObject>();
MapData.BinaryObject newObject = new MapData.BinaryObject();
{
newObject.objectName = currentObject.objectName.ToString();
newObject.buttonState = currentObject.buttonState;
newObject.objectState = currentObject.objectState;
newObject.buttonX = (int)currentObject.transform.position.x;
newObject.buttonY = (int)currentObject.transform.position.y;
newObject.objectX = currentObject.objectLocationX;
newObject.objectY = currentObject.objectLocationY;
newObject.canToggle = currentObject.canToggle;
}
}
}
catch
{
//nothing to save
}
string json = JsonUtility.ToJson(mapData);
if(d == true)
{
fileName = Path.Combine(defaults, Globals.currentMap + ".json");
Debug.Log(d);
}
else
{
fileName = Path.Combine(saveData, Globals.currentMap + ".json");
Debug.Log(d);
}
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
Debug.Log("save complete" + fileName);
}
public IEnumerator LoadMapData()
{
yield return new WaitForSeconds(.5f);
Debug.Log("loading map data");
try
{
if (File.Exists(Path.Combine(saveData, Globals.currentMap + ".json")))
{
fileName = Path.Combine(saveData, Globals.currentMap + ".json");
}
else
{
fileName = Path.Combine(defaults, Globals.currentMap + ".json");
}
Debug.Log("loading from " + fileName);
loadFile = File.ReadAllText(fileName);
MapData load = JsonUtility.FromJson<MapData>(loadFile);
Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>();
try
{
for (int x = load.mapDoorInfo.Count - 1; x > -1; x--)
{
MapData.Door d = load.mapDoorInfo[x];
itemContainer.CreateDoor(d.doorName, d.posX, d.posY);
load.mapDoorInfo.RemoveAt(x);
}
}
catch
{
Debug.Log("problem loading doors");
}
try
{
for (int x = load.mapItemInfo.Count - 1; x > -1; x--)
{
MapData.Item i = load.mapItemInfo[x];
itemContainer.CreateItem(i.itemName, i.value, i.posX, i.posY);
load.mapItemInfo.RemoveAt(x);
}
}
catch
{
}
try
{
for (int x = load.mapEnemyInfo.Count - 1; x > -1; x--)
{
MapData.Enemy e = load.mapEnemyInfo[x];
itemContainer.CreateEnemy(e.enemyName, e.posX, e.posY,e.alive,e.heldItem);
load.mapEnemyInfo.RemoveAt(x);
}
}
catch
{
}
try
{
for (int x = load.mapBinaryObjectInfo.Count - 1; x > -1; x--)
{
MapData.BinaryObject o = load.mapBinaryObjectInfo[x];
itemContainer.CreateBinaryObject(o.objectName, o.buttonState, o.objectState, o.buttonX, o.buttonY, o.objectX, o.objectY, o.canToggle);
load.mapBinaryObjectInfo.RemoveAt(x);
}
}
catch
{
}
}
catch { }
yield return null;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Engine;
using Micropolis.Common;
using Microsoft.ApplicationInsights;
namespace Micropolis.ViewModels
{
public class EvaluationPaneViewModel : BindableBase, Engine.IListener
{
private Engine.Micropolis _engine;
private MainGamePageViewModel _mainPageViewModel;
/// <summary>
/// Sets the engine.
/// </summary>
/// <param name="newEngine">The new engine.</param>
public void SetEngine(Engine.Micropolis newEngine)
{
if (_engine != null)
{
//old engine
_engine.RemoveListener(this);
}
_engine = newEngine;
if (_engine != null)
{
//new engine
_engine.AddListener(this);
LoadEvaluation();
}
}
public EvaluationPaneViewModel()
{
DismissCommand = new DelegateCommand(OnDismissClicked);
try
{
_telemetry = new TelemetryClient();
}
catch (Exception)
{
}
}
/// <summary>
/// Called when user clicked the dismiss button to close the window.
/// </summary>
private void OnDismissClicked()
{
try {
_telemetry.TrackEvent("EvaluationPaneDismissClicked");
}
catch (Exception) { }
_mainPageViewModel.HideEvaluationPane();
}
private string _headerPublicOpinionTextBlockText;
public string HeaderPublicOpinionTextBlockText
{
get
{
return this._headerPublicOpinionTextBlockText;
}
set
{
this.SetProperty(ref this._headerPublicOpinionTextBlockText, value);
}
}
private string _pubOpTextBlockText;
public string PubOpTextBlockText
{
get
{
return this._pubOpTextBlockText;
}
set
{
this.SetProperty(ref this._pubOpTextBlockText, value);
}
}
private string _pubOp2TextBlockText;
public string PubOp2TextBlockText
{
get
{
return this._pubOp2TextBlockText;
}
set
{
this.SetProperty(ref this._pubOp2TextBlockText, value);
}
}
private string _pubOp3TextBlockText;
public string PubOp3TextBlockText
{
get
{
return this._pubOp3TextBlockText;
}
set
{
this.SetProperty(ref this._pubOp3TextBlockText, value);
}
}
private string _pubOp4TextBlockText;
public string PubOp4TextBlockText
{
get
{
return this._pubOp4TextBlockText;
}
set
{
this.SetProperty(ref this._pubOp4TextBlockText, value);
}
}
/// <summary>
/// Makes the public opinion pane.
/// </summary>
/// <returns></returns>
private void MakePublicOpinionPane()
{
HeaderPublicOpinionTextBlockText = Strings.GetString("public-opinion");
PubOpTextBlockText = Strings.GetString("public-opinion-1");
PubOp2TextBlockText = Strings.GetString("public-opinion-2");
PubOp3TextBlockText = Strings.GetString("public-opinion-yes");
PubOp4TextBlockText = Strings.GetString("public-opinion-no");
VoterProblem1TextBlockText = "";
VoterCount1TextBlockText = "";
VoterProblem2TextBlockText = "";
VoterCount2TextBlockText = "";
VoterProblem3TextBlockText = "";
VoterCount3TextBlockText = "";
VoterProblem4TextBlockText = "";
VoterCount4TextBlockText = "";
}
private string _voterProblem4TextBlockText;
public string VoterProblem4TextBlockText
{
get
{
return this._voterProblem4TextBlockText;
}
set
{
this.SetProperty(ref this._voterProblem4TextBlockText, value);
}
}
private string _voterProblem3TextBlockText;
public string VoterProblem3TextBlockText
{
get
{
return this._voterProblem3TextBlockText;
}
set
{
this.SetProperty(ref this._voterProblem3TextBlockText, value);
}
}
private string _voterProblem2TextBlockText;
public string VoterProblem2TextBlockText
{
get
{
return this._voterProblem2TextBlockText;
}
set
{
this.SetProperty(ref this._voterProblem2TextBlockText, value);
}
}
private string _voterProblem1TextBlockText;
public string VoterProblem1TextBlockText
{
get
{
return this._voterProblem1TextBlockText;
}
set
{
this.SetProperty(ref this._voterProblem1TextBlockText, value);
}
}
private string _voterCount1TextBlockText;
public string VoterCount1TextBlockText
{
get
{
return this._voterCount1TextBlockText;
}
set
{
this.SetProperty(ref this._voterCount1TextBlockText, value);
}
}
private string _voterCount2TextBlockText;
public string VoterCount2TextBlockText
{
get
{
return this._voterCount2TextBlockText;
}
set
{
this.SetProperty(ref this._voterCount2TextBlockText, value);
}
}
private string _voterCount3TextBlockText;
public string VoterCount3TextBlockText
{
get
{
return this._voterCount3TextBlockText;
}
set
{
this.SetProperty(ref this._voterCount3TextBlockText, value);
}
}
private string _voterCount4TextBlockText;
public string VoterCount4TextBlockText
{
get
{
return this._voterCount4TextBlockText;
}
set
{
this.SetProperty(ref this._voterCount4TextBlockText, value);
}
}
/// <summary>
/// Makes the statistics pane.
/// </summary>
/// <returns></returns>
private void MakeStatisticsPane()
{
HeaderStatisticsTextBlockText = Strings.GetString("statistics-head");
CityScoreHeaderTextBlockText = Strings.GetString("city-score-head");
StatPopTextBlockText = Strings.GetString("stats-population");
StatMigTextBlockText = Strings.GetString("stats-net-migration");
StatsLastYearTextBlockText = Strings.GetString("stats-last-year");
StatsAssessedValueTextBlockText = Strings.GetString("stats-assessed-value");
StatsCategoryTextBlockText = Strings.GetString("stats-category");
StatsGameLevelTextBlockText = Strings.GetString("stats-game-level");
CityScoreCurrentTextBlockText = Strings.GetString("city-score-current");
CityScoreChangeTextBlockText = Strings.GetString("city-score-change");
}
private string _headerStatisticsTextBlockText;
public string HeaderStatisticsTextBlockText
{
get
{
return this._headerStatisticsTextBlockText;
}
set
{
this.SetProperty(ref this._headerStatisticsTextBlockText, value);
}
}
private string _cityScoreHeaderTextBlockText;
public string CityScoreHeaderTextBlockText
{
get
{
return this._cityScoreHeaderTextBlockText;
}
set
{
this.SetProperty(ref this._cityScoreHeaderTextBlockText, value);
}
}
private string _statPopTextBlockText;
public string StatPopTextBlockText
{
get
{
return this._statPopTextBlockText;
}
set
{
this.SetProperty(ref this._statPopTextBlockText, value);
}
}
private string _statMigTextBlockText;
public string StatMigTextBlockText
{
get
{
return this._statMigTextBlockText;
}
set
{
this.SetProperty(ref this._statMigTextBlockText, value);
}
}
private string _statsLastYearTextBlockText;
public string StatsLastYearTextBlockText
{
get
{
return this._statsLastYearTextBlockText;
}
set
{
this.SetProperty(ref this._statsLastYearTextBlockText, value);
}
}
private string _statsAssessedValueTextBlockText;
public string StatsAssessedValueTextBlockText
{
get
{
return this._statsAssessedValueTextBlockText;
}
set
{
this.SetProperty(ref this._statsAssessedValueTextBlockText, value);
}
}
private string _statsCategoryTextBlockText;
public string StatsCategoryTextBlockText
{
get
{
return this._statsCategoryTextBlockText;
}
set
{
this.SetProperty(ref this._statsCategoryTextBlockText, value);
}
}
private string _statsGameLevelTextBlockText;
public string StatsGameLevelTextBlockText
{
get
{
return this._statsGameLevelTextBlockText;
}
set
{
this.SetProperty(ref this._statsGameLevelTextBlockText, value);
}
}
private string _cityScoreCurrentTextBlockText;
public string CityScoreCurrentTextBlockText
{
get
{
return this._cityScoreCurrentTextBlockText;
}
set
{
this.SetProperty(ref this._cityScoreCurrentTextBlockText, value);
}
}
private string _cityScoreChangeTextBlockText;
public string CityScoreChangeTextBlockText
{
get
{
return this._cityScoreChangeTextBlockText;
}
set
{
this.SetProperty(ref this._cityScoreChangeTextBlockText, value);
}
}
private string _yesTextBlockText;
public string YesTextBlockText
{
get
{
return this._yesTextBlockText;
}
set
{
this.SetProperty(ref this._yesTextBlockText, value);
}
}
private string _noTextBlockText;
public string NoTextBlockText
{
get
{
return this._noTextBlockText;
}
set
{
this.SetProperty(ref this._noTextBlockText, value);
}
}
/// <summary>
/// Loads the evaluation.
/// </summary>
private void LoadEvaluation()
{
YesTextBlockText = ((_engine.Evaluation.CityYes).ToString()+"%");
NoTextBlockText = ((_engine.Evaluation.CityNo).ToString()+"%");
CityProblem p;
int numVotes;
p = 0 < _engine.Evaluation.ProblemOrder.Length
? _engine.Evaluation.ProblemOrder[0]
: default(CityProblem);
numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0;
if (numVotes != 0)
{
VoterProblem1TextBlockText = ("problem." + p); //name
VoterCount1TextBlockText = (0.01*numVotes).ToString();
VoterProblem1IsVisible = true;
VoterCount1IsVisible = true;
}
else
{
VoterProblem1IsVisible = false;
VoterCount1IsVisible = false;
}
p = 1 < _engine.Evaluation.ProblemOrder.Length
? _engine.Evaluation.ProblemOrder[1]
: default(CityProblem);
numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0;
if (numVotes != 0)
{
VoterProblem2TextBlockText = ("problem." + p); //name
VoterCount2TextBlockText = (0.01 * numVotes).ToString();
VoterProblem2IsVisible = true;
VoterCount2IsVisible = true;
}
else
{
VoterProblem2IsVisible = false;
VoterCount2IsVisible = false;
}
p = 2 < _engine.Evaluation.ProblemOrder.Length
? _engine.Evaluation.ProblemOrder[2]
: default(CityProblem);
numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0;
if (numVotes != 0)
{
VoterProblem3TextBlockText = ("problem." + p); //name
VoterCount3TextBlockText = (0.01 * numVotes).ToString();
VoterProblem3IsVisible = true;
VoterCount3IsVisible = true;
}
else
{
VoterProblem3IsVisible = false;
VoterCount3IsVisible = false;
}
p = 3 < _engine.Evaluation.ProblemOrder.Length
? _engine.Evaluation.ProblemOrder[3]
: default(CityProblem);
numVotes = p != default(CityProblem) ? _engine.Evaluation.ProblemVotes[p] : 0;
if (numVotes != 0)
{
VoterProblem4TextBlockText = ("problem." + p); //name
VoterCount4TextBlockText = (0.01 * numVotes).ToString();
VoterProblem4IsVisible = true;
VoterCount4IsVisible = true;
}
else
{
VoterProblem4IsVisible = false;
VoterCount4IsVisible = false;
}
PopTextBlockText = (_engine.Evaluation.CityPop).ToString();
DeltaTextBlockText = (_engine.Evaluation.DeltaCityPop).ToString();
AssessTextBlockText = (_engine.Evaluation.CityAssValue).ToString();
CityClassTextBlockText = (GetCityClassName(_engine.Evaluation.CityClass));
GameLevelTextBlockText = (GetGameLevelName(_engine.GameLevel));
ScoreTextBlockText = (_engine.Evaluation.CityScore).ToString();
ScoreDeltaTextBlockText = (_engine.Evaluation.DeltaCityScore).ToString();
}
private bool _voterCount4IsVisible;
public bool VoterCount4IsVisible
{
get
{
return this._voterCount4IsVisible;
}
set
{
this.SetProperty(ref this._voterCount4IsVisible, value);
}
}
private bool _voterCount3IsVisible;
public bool VoterCount3IsVisible
{
get
{
return this._voterCount3IsVisible;
}
set
{
this.SetProperty(ref this._voterCount3IsVisible, value);
}
}
private bool _voterCount2IsVisible;
public bool VoterCount2IsVisible
{
get
{
return this._voterCount2IsVisible;
}
set
{
this.SetProperty(ref this._voterCount2IsVisible, value);
}
}
private bool _voterCount1IsVisible;
public bool VoterCount1IsVisible
{
get
{
return this._voterCount1IsVisible;
}
set
{
this.SetProperty(ref this._voterCount1IsVisible, value);
}
}
private bool _voterProblem4IsVisible;
public bool VoterProblem4IsVisible
{
get
{
return this._voterProblem4IsVisible;
}
set
{
this.SetProperty(ref this._voterProblem4IsVisible, value);
}
}
private bool _voterProblem3IsVisible;
public bool VoterProblem3IsVisible
{
get
{
return this._voterProblem3IsVisible;
}
set
{
this.SetProperty(ref this._voterProblem3IsVisible, value);
}
}
private bool _voterProblem2IsVisible;
public bool VoterProblem2IsVisible
{
get
{
return this._voterProblem2IsVisible;
}
set
{
this.SetProperty(ref this._voterProblem2IsVisible, value);
}
}
private bool _voterProblem1IsVisible;
public bool VoterProblem1IsVisible
{
get
{
return this._voterProblem1IsVisible;
}
set
{
this.SetProperty(ref this._voterProblem1IsVisible, value);
}
}
private string _scoreDeltaTextBlockText;
public string ScoreDeltaTextBlockText
{
get
{
return this._scoreDeltaTextBlockText;
}
set
{
this.SetProperty(ref this._scoreDeltaTextBlockText, value);
}
}
private string _scoreTextBlockText;
public string ScoreTextBlockText
{
get
{
return this._scoreTextBlockText;
}
set
{
this.SetProperty(ref this._scoreTextBlockText, value);
}
}
private string _gameLevelTextBlockText;
public string GameLevelTextBlockText
{
get
{
return this._gameLevelTextBlockText;
}
set
{
this.SetProperty(ref this._gameLevelTextBlockText, value);
}
}
private string _cityClassTextBlockText;
public string CityClassTextBlockText
{
get
{
return this._cityClassTextBlockText;
}
set
{
this.SetProperty(ref this._cityClassTextBlockText, value);
}
}
private string _assessTextBlockText;
public string AssessTextBlockText
{
get
{
return this._assessTextBlockText;
}
set
{
this.SetProperty(ref this._assessTextBlockText, value);
}
}
private string _deltaTextBlockText;
public string DeltaTextBlockText
{
get
{
return this._deltaTextBlockText;
}
set
{
this.SetProperty(ref this._deltaTextBlockText, value);
}
}
private string _popTextBlockText;
public string PopTextBlockText
{
get
{
return this._popTextBlockText;
}
set
{
this.SetProperty(ref this._popTextBlockText, value);
}
}
/// <summary>
/// Gets the name of the city class.
/// </summary>
/// <param name="cityClass">The city class.</param>
/// <returns></returns>
private static String GetCityClassName(int cityClass)
{
return Strings.GetString("class." + cityClass);
}
/// <summary>
/// Gets the name of the game level.
/// </summary>
/// <param name="gameLevel">The game level.</param>
/// <returns></returns>
private static String GetGameLevelName(int gameLevel)
{
return Strings.GetString("level." + gameLevel);
}
public DelegateCommand DismissCommand { get; private set; }
private string _dismissButtonText;
private TelemetryClient _telemetry;
public string DismissButtonText
{
get
{
return this._dismissButtonText;
}
set
{
this.SetProperty(ref this._dismissButtonText, value);
}
}
internal void SetupAfterBasicInit(MainGamePageViewModel mainPageViewModel, Engine.Micropolis engine)
{
_mainPageViewModel = mainPageViewModel;
DismissButtonText = Strings.GetString("dismiss-evaluation");
MakePublicOpinionPane();
MakeStatisticsPane();
SetEngine(engine);
LoadEvaluation();
}
#region implements Micropolis.IListener
/// <summary>
/// Cities the message.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="loc">The loc.</param>
public void CityMessage(MicropolisMessage message, CityLocation loc)
{
}
/// <summary>
/// Cities the sound.
/// </summary>
/// <param name="sound">The sound.</param>
/// <param name="loc">The loc.</param>
public void CitySound(Sound sound, CityLocation loc)
{
}
/// <summary>
/// Fired whenever the "census" is taken, and the various historical counters have been updated. (Once a month in
/// game.)
/// </summary>
public void CensusChanged()
{
}
/// <summary>
/// Fired whenever resValve, comValve, or indValve changes. (Twice a month in game.)
/// </summary>
public void DemandChanged()
{
}
/// <summary>
/// Fired whenever the mayor's money changes.
/// </summary>
public void FundsChanged()
{
}
/// <summary>
/// Fired whenever autoBulldoze, autoBudget, noDisasters, or simSpeed change.
/// </summary>
public void OptionsChanged()
{
}
#endregion
#region implements Engine.IListener
/// <summary>
/// Fired whenever the city evaluation is recalculated. (Once a year.)
/// </summary>
public void EvaluationChanged()
{
LoadEvaluation();
}
#endregion
}
}
|
#region using directives
using System;
using PoGo.PokeMobBot.Logic.Event;
using PoGo.PokeMobBot.Logic.Event.Egg;
using PoGo.PokeMobBot.Logic.Event.Fort;
using PoGo.PokeMobBot.Logic.Event.Global;
using PoGo.PokeMobBot.Logic.Event.GUI;
using PoGo.PokeMobBot.Logic.Event.Item;
using PoGo.PokeMobBot.Logic.Event.Logic;
using PoGo.PokeMobBot.Logic.Event.Obsolete;
using PoGo.PokeMobBot.Logic.Event.Player;
using PoGo.PokeMobBot.Logic.Event.Pokemon;
using PoGo.PokeMobBot.Logic.State;
using PoGo.PokeMobBot.Logic.Utils;
using POGOProtos.Networking.Responses;
#endregion
namespace PoGo.PokeMobBot.Logic
{
public class StatisticsAggregator
{
public void HandleEvent(ProfileEvent evt, ISession session)
{
session.Stats.SetUsername(evt.Profile);
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(ErrorEvent evt, ISession session)
{
}
public void HandleEvent(NoticeEvent evt, ISession session)
{
}
public void HandleEvent(FortLureStartedEvent evt, ISession session)
{
}
public void HandleEvent(ItemUsedEvent evt, ISession session)
{
}
public void HandleEvent(WarnEvent evt, ISession session)
{
}
public void HandleEvent(UseLuckyEggEvent evt, ISession session)
{
}
public void HandleEvent(PokemonEvolveEvent evt, ISession session)
{
session.Stats.TotalExperience += evt.Exp;
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(TransferPokemonEvent evt, ISession session)
{
session.Stats.TotalPokemonsTransfered++;
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(EggHatchedEvent evt, ISession session)
{
session.Stats.TotalPokemons++;
session.Stats.HatchedNow++;
session.Stats.RefreshStatAndCheckLevelup(session);
session.Stats.RefreshPokeDex(session);
}
public void HandleEvent(VerifyChallengeEvent evt, ISession session)
{
}
public void HandleEvent(CheckChallengeEvent evt, ISession session)
{
}
public void HandleEvent(BuddySetEvent evt, ISession session)
{
}
public void HandleEvent(BuddyWalkedEvent evt, ISession session)
{
}
public void HandleEvent(ItemRecycledEvent evt, ISession session)
{
session.Stats.TotalItemsRemoved += evt.Count;
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(FortUsedEvent evt, ISession session)
{
session.Stats.TotalExperience += evt.Exp;
session.Stats.TotalPokestops++;
session.Stats.RefreshStatAndCheckLevelup(session);
}
public void HandleEvent(FortTargetEvent evt, ISession session)
{
}
public void HandleEvent(PokemonActionDoneEvent evt, ISession session)
{
}
public void HandleEvent(PokemonCaptureEvent evt, ISession session)
{
if (evt.Status == CatchPokemonResponse.Types.CatchStatus.CatchSuccess)
{
session.Stats.TotalExperience += evt.Exp;
session.Stats.TotalPokemons++;
session.Stats.TotalStardust = evt.Stardust;
session.Stats.RefreshStatAndCheckLevelup(session);
session.Stats.RefreshPokeDex(session);
}
session.Stats.PokeBalls++;
}
public void HandleEvent(NoPokeballEvent evt, ISession session)
{
}
public void HandleEvent(UseBerryEvent evt, ISession session)
{
}
public void HandleEvent(DisplayHighestsPokemonEvent evt, ISession session)
{
}
public void HandleEvent(UpdatePositionEvent evt, ISession session)
{
}
public void HandleEvent(NewVersionEvent evt, ISession session)
{
}
public void HandleEvent(UpdateEvent evt, ISession session)
{
}
public void HandleEvent(BotCompleteFailureEvent evt, ISession session)
{
}
public void HandleEvent(DebugEvent evt, ISession session)
{
}
public void HandleEvent(EggIncubatorStatusEvent evt, ISession session)
{
}
public void HandleEvent(EggsListEvent evt, ISession session)
{
}
public void HandleEvent(ForceMoveDoneEvent evt, ISession session)
{
}
public void HandleEvent(FortFailedEvent evt, ISession session)
{
}
public void HandleEvent(InvalidKeepAmountEvent evt, ISession session)
{
}
public void HandleEvent(InventoryListEvent evt, ISession session)
{
}
public void HandleEvent(InventoryNewItemsEvent evt, ISession session)
{
}
public void HandleEvent(EggFoundEvent evt, ISession session)
{
}
public void HandleEvent(NextRouteEvent evt, ISession session)
{
}
public void HandleEvent(PlayerLevelUpEvent evt, ISession session)
{
}
public void HandleEvent(PlayerStatsEvent evt, ISession session)
{
}
public void HandleEvent(PokemonDisappearEvent evt, ISession session)
{
session.Stats.EncountersNow++;
}
public void HandleEvent(PokemonEvolveDoneEvent evt, ISession session)
{
session.Stats.TotalEvolves++;
session.Stats.RefreshPokeDex(session);
}
public void HandleEvent(PokemonFavoriteEvent evt, ISession session)
{
}
public void HandleEvent(PokemonSettingsEvent evt, ISession session)
{
}
public void HandleEvent(PokemonsFoundEvent evt, ISession session)
{
}
public void HandleEvent(PokemonsWildFoundEvent evt, ISession session)
{
}
public void HandleEvent(PokemonStatsChangedEvent evt, ISession session)
{
}
public void HandleEvent(PokeStopListEvent evt, ISession session)
{
}
public void HandleEvent(SnipeEvent evt, ISession session)
{
}
public void HandleEvent(SnipeModeEvent evt, ISession session)
{
}
public void HandleEvent(UseLuckyEggMinPokemonEvent evt, ISession session)
{
}
public void HandleEvent(PokemonListEvent evt, ISession session)
{
}
public void HandleEvent(GymPokeEvent evt, ISession session)
{
}
public void HandleEvent(PokestopsOptimalPathEvent evt, ISession session)
{
}
public void HandleEvent(TeamSetEvent evt, ISession session)
{
}
public void HandleEvent(ItemLostEvent evt, ISession session)
{
}
public void Listen(IEvent evt, ISession session)
{
try
{
dynamic eve = evt;
HandleEvent(eve, session);
}
// ReSharper disable once EmptyGeneralCatchClause
catch (Exception)
{
}
}
}
} |
/*
Copyright 2011 MCForge
Dual-licensed under the Educational Community License, Version 2.0 and
the GNU General Public License, Version 3 (the "Licenses"); you may
not use this file except in compliance with the Licenses. You may
obtain a copy of the Licenses at
http://www.osedu.org/licenses/ECL-2.0
http://www.gnu.org/licenses/gpl-3.0.html
Unless required by applicable law or agreed to in writing,
software distributed under the Licenses are distributed on an "AS IS"
BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied. See the Licenses for the specific language governing
permissions and limitations under the Licenses.
*/
using System;
using System.IO;
namespace MCForge
{
public class CmdMap : Command
{
public override string name { get { return "map"; } }
public override string shortcut { get { return ""; } }
public override string type { get { return "mod"; } }
public override bool museumUsable { get { return true; } }
public override LevelPermission defaultRank { get { return LevelPermission.Guest; } }
public CmdMap() { }
public override void Use(Player p, string message)
{
if (message == "") message = p.level.name;
Level foundLevel;
if (message.IndexOf(' ') == -1)
{
foundLevel = Level.Find(message);
if (foundLevel == null)
{
if (p != null)
{
foundLevel = p.level;
}
}
else
{
Player.SendMessage(p, "MOTD: &b" + foundLevel.motd);
Player.SendMessage(p, "Finite mode: " + FoundCheck(foundLevel.finite));
Player.SendMessage(p, "Animal AI: " + FoundCheck(foundLevel.ai));
Player.SendMessage(p, "Edge water: " + FoundCheck(foundLevel.edgeWater));
Player.SendMessage(p, "Grass growing: " + FoundCheck(foundLevel.GrassGrow));
Player.SendMessage(p, "Physics speed: &b" + foundLevel.speedPhysics);
Player.SendMessage(p, "Physics overload: &b" + foundLevel.overload);
Player.SendMessage(p, "Survival death: " + FoundCheck(foundLevel.Death) + "(Fall: " + foundLevel.fall + ", Drown: " + foundLevel.drown + ")");
Player.SendMessage(p, "Killer blocks: " + FoundCheck(foundLevel.Killer));
Player.SendMessage(p, "Unload: " + FoundCheck(foundLevel.unload));
Player.SendMessage(p, "Auto physics: " + FoundCheck(foundLevel.rp));
Player.SendMessage(p, "Instant building: " + FoundCheck(foundLevel.Instant));
Player.SendMessage(p, "RP chat: " + FoundCheck(!foundLevel.worldChat));
return;
}
}
else
{
foundLevel = Level.Find(message.Split(' ')[0]);
if (foundLevel == null || message.Split(' ')[0].ToLower() == "ps" || message.Split(' ')[0].ToLower() == "rp") foundLevel = p.level;
else message = message.Substring(message.IndexOf(' ') + 1);
}
if (p != null)
if (p.group.Permission < LevelPermission.Operator) { Player.SendMessage(p, "Setting map options is reserved to OP+"); return; }
string foundStart;
if (message.IndexOf(' ') == -1) foundStart = message.ToLower();
else foundStart = message.Split(' ')[0].ToLower();
try
{
switch (foundStart)
{
case "theme": foundLevel.theme = message.Substring(message.IndexOf(' ') + 1); foundLevel.ChatLevel("Map theme: &b" + foundLevel.theme); break;
case "finite": foundLevel.finite = !foundLevel.finite; foundLevel.ChatLevel("Finite mode: " + FoundCheck(foundLevel.finite)); break;
case "ai": foundLevel.ai = !foundLevel.ai; foundLevel.ChatLevel("Animal AI: " + FoundCheck(foundLevel.ai)); break;
case "edge": foundLevel.edgeWater = !foundLevel.edgeWater; foundLevel.ChatLevel("Edge water: " + FoundCheck(foundLevel.edgeWater)); break;
case "grass": foundLevel.GrassGrow = !foundLevel.GrassGrow; foundLevel.ChatLevel("Growing grass: " + FoundCheck(foundLevel.GrassGrow)); break;
case "ps":
case "physicspeed":
if (int.Parse(message.Split(' ')[1]) < 10) { Player.SendMessage(p, "Cannot go below 10"); return; }
foundLevel.speedPhysics = int.Parse(message.Split(' ')[1]);
foundLevel.ChatLevel("Physics speed: &b" + foundLevel.speedPhysics);
break;
case "overload":
if (int.Parse(message.Split(' ')[1]) < 500) { Player.SendMessage(p, "Cannot go below 500 (default is 1500)"); return; }
if (p.group.Permission < LevelPermission.Admin && int.Parse(message.Split(' ')[1]) > 2500) { Player.SendMessage(p, "Only SuperOPs may set higher than 2500"); return; }
foundLevel.overload = int.Parse(message.Split(' ')[1]);
foundLevel.ChatLevel("Physics overload: &b" + foundLevel.overload);
break;
case "motd":
if (message.Split(' ').Length == 1) foundLevel.motd = "ignore";
else foundLevel.motd = message.Substring(message.IndexOf(' ') + 1);
foundLevel.ChatLevel("Map MOTD: &b" + foundLevel.motd);
break;
case "death": foundLevel.Death = !foundLevel.Death; foundLevel.ChatLevel("Survival death: " + FoundCheck(foundLevel.Death)); break;
case "killer": foundLevel.Killer = !foundLevel.Killer; foundLevel.ChatLevel("Killer blocks: " + FoundCheck(foundLevel.Killer)); break;
case "fall": foundLevel.fall = int.Parse(message.Split(' ')[1]); foundLevel.ChatLevel("Fall distance: &b" + foundLevel.fall); break;
case "drown": foundLevel.drown = int.Parse(message.Split(' ')[1]) * 10; foundLevel.ChatLevel("Drown time: &b" + (foundLevel.drown / 10)); break;
case "unload": foundLevel.unload = !foundLevel.unload; foundLevel.ChatLevel("Auto unload: " + FoundCheck(foundLevel.unload)); break;
case "rp":
case "restartphysics": foundLevel.rp = !foundLevel.rp; foundLevel.ChatLevel("Auto physics: " + FoundCheck(foundLevel.rp)); break;
case "instant":
if (p.group.Permission < LevelPermission.Admin) { Player.SendMessage(p, "This is reserved for Super+"); return; }
foundLevel.Instant = !foundLevel.Instant; foundLevel.ChatLevel("Instant building: " + FoundCheck(foundLevel.Instant)); break;
case "chat":
foundLevel.worldChat = !foundLevel.worldChat; foundLevel.ChatLevel("RP chat: " + FoundCheck(!foundLevel.worldChat)); break;
default:
Player.SendMessage(p, "Could not find option entered.");
return;
}
foundLevel.changed = true;
if (p.level != foundLevel) Player.SendMessage(p, "/map finished!");
}
catch { Player.SendMessage(p, "INVALID INPUT"); }
}
public string FoundCheck(bool check)
{
if (check) return "&aON";
else return "&cOFF";
}
public override void Help(Player p)
{
Player.SendMessage(p, "/map [level] [toggle] - Sets [toggle] on [map]");
Player.SendMessage(p, "Possible toggles: theme, finite, ai, edge, ps, overload, motd, death, fall, drown, unload, rp, instant, killer, chat");
Player.SendMessage(p, "Edge will cause edge water to flow.");
Player.SendMessage(p, "Grass will make grass not grow without physics");
Player.SendMessage(p, "Finite will cause all liquids to be finite.");
Player.SendMessage(p, "AI will make animals hunt or flee.");
Player.SendMessage(p, "PS will set the map's physics speed.");
Player.SendMessage(p, "Overload will change how easy/hard it is to kill physics.");
Player.SendMessage(p, "MOTD will set a custom motd for the map. (leave blank to reset)");
Player.SendMessage(p, "Death will allow survival-style dying (falling, drowning)");
Player.SendMessage(p, "Fall/drown set the distance/time before dying from each.");
Player.SendMessage(p, "Killer turns killer blocks on and off.");
Player.SendMessage(p, "Unload sets whether the map unloads when no one's there.");
Player.SendMessage(p, "RP sets whether the physics auto-start for the map");
Player.SendMessage(p, "Instant mode works by not updating everyone's screens");
Player.SendMessage(p, "Chat sets the map to recieve no messages from other maps");
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.