context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
namespace AngleSharp.Css.Tests.Declarations
{
using NUnit.Framework;
using static CssConstructionFunctions;
[TestFixture]
public class CssAnimationPropertyTests
{
[Test]
public void CssAnimationDurationMillisecondsLegal()
{
var snippet = "animation-duration : 60ms";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-duration", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("60ms", property.Value);
}
[Test]
public void CssAnimationDurationMultipleSecondsLegal()
{
var snippet = "animation-duration : 1s , 2s , 3s , 4s";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-duration", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("1s, 2s, 3s, 4s", property.Value);
}
[Test]
public void CssAnimationDelayMillisecondsLegal()
{
var snippet = "animation-delay : 0ms";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-delay", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("0ms", property.Value);
}
[Test]
public void CssAnimationDelayZeroIllegal()
{
var snippet = "animation-delay : 0";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-delay", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssAnimationDelayZeroZeroSecondMillisecondsLegal()
{
var snippet = "animation-delay : 0s , 0s , 1s , 20ms";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-delay", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("0s, 0s, 1s, 20ms", property.Value);
}
[Test]
public void CssAnimationNameDashSpecificLegal()
{
var snippet = "animation-name : -specific";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-name", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("-specific", property.Value);
}
[Test]
public void CssAnimationNameSlidingVerticallyLegal()
{
var snippet = "animation-name : sliding-vertically";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-name", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("sliding-vertically", property.Value);
}
[Test]
public void CssAnimationNameTest05Legal()
{
var snippet = "animation-name : test_05";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-name", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("test_05", property.Value);
}
[Test]
public void CssAnimationNameNumberIllegal()
{
var snippet = "animation-name : 42";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-name", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssAnimationNameMyAnimationOtherAnimationLegal()
{
var snippet = "animation-name : my-animation, other-animation";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-name", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("my-animation, other-animation", property.Value);
}
[Test]
public void CssAnimationIterationCountZeroLegal()
{
var snippet = "animation-iteration-count : 0";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-iteration-count", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("0", property.Value);
}
[Test]
public void CssAnimationIterationCountInfiniteLegal()
{
var snippet = "animation-iteration-count : infinite";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-iteration-count", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("infinite", property.Value);
}
[Test]
public void CssAnimationIterationCountInfiniteUppercaseLegal()
{
var snippet = "animation-iteration-count : INFINITE";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-iteration-count", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("infinite", property.Value);
}
[Test]
public void CssAnimationIterationCountFloatLegal()
{
var snippet = "animation-iteration-count : 2.3";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-iteration-count", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("2.3", property.Value);
}
[Test]
public void CssAnimationIterationCountTwoZeroInfiniteLegal()
{
var snippet = "animation-iteration-count : 2, 0, infinite";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-iteration-count", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("2, 0, infinite", property.Value);
}
[Test]
public void CssAnimationIterationCountNegativeIllegal()
{
var snippet = "animation-iteration-count : -1";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-iteration-count", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssAnimationTimingFunctionEaseUppercaseLegal()
{
var snippet = "animation-timing-function : EASE";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-timing-function", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("ease", property.Value);
}
[Test]
public void CssAnimationTimingFunctionNoneIllegal()
{
var snippet = "animation-timing-function : none";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-timing-function", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssAnimationTimingFunctionEaseInOutLegal()
{
var snippet = "animation-timing-function : ease-IN-out";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-timing-function", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("ease-in-out", property.Value);
}
[Test]
public void CssAnimationTimingFunctionStepEndLegal()
{
var snippet = "animation-timing-function : step-END";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-timing-function", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("step-end", property.Value);
}
[Test]
public void CssAnimationTimingFunctionStepStartLinearLegal()
{
var snippet = "animation-timing-function : step-start , LINeAr";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-timing-function", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("step-start, linear", property.Value);
}
[Test]
public void CssAnimationTimingFunctionStepStartCubicBezierLegal()
{
var snippet = "animation-timing-function : step-start , cubic-bezier(0,1,1,1)";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-timing-function", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("step-start, cubic-bezier(0, 1, 1, 1)", property.Value);
}
[Test]
public void CssAnimationPlayStateRunningLegal()
{
var snippet = "animation-play-state: running";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-play-state", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("running", property.Value);
}
[Test]
public void CssAnimationPlayStatePausedUppercaseLegal()
{
var snippet = "animation-play-state: PAUSED";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-play-state", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("paused", property.Value);
}
[Test]
public void CssAnimationPlayStatePausedRunningPausedLegal()
{
var snippet = "animation-play-state: paused, Running, paused";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-play-state", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("paused, running, paused", property.Value);
}
[Test]
public void CssAnimationFillModeNoneLegal()
{
var snippet = "animation-fill-mode: none";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-fill-mode", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("none", property.Value);
}
[Test]
public void CssAnimationFillModeZeroIllegal()
{
var snippet = "animation-fill-mode: 0";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-fill-mode", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssAnimationFillModeBackwardsLegal()
{
var snippet = "animation-fill-mode: backwards !important";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-fill-mode", property.Name);
Assert.IsTrue(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("backwards", property.Value);
}
[Test]
public void CssAnimationFillModeForwardsUppercaseLegal()
{
var snippet = "animation-fill-mode: FORWARDS";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-fill-mode", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("forwards", property.Value);
}
[Test]
public void CssAnimationFillModeBothBackwardsForwardsNoneLegal()
{
var snippet = "animation-fill-mode: both , backwards , forwards ,NONE";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-fill-mode", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("both, backwards, forwards, none", property.Value);
}
[Test]
public void CssAnimationDirectionNormalLegal()
{
var snippet = "animation-direction: normal";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-direction", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("normal", property.Value);
}
[Test]
public void CssAnimationDirectionReverseLegal()
{
var snippet = "animation-direction : reverse";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-direction", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("reverse", property.Value);
}
[Test]
public void CssAnimationDirectionNoneIllegal()
{
var snippet = "animation-direction : none";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-direction", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssAnimationDirectionAlternateReverseUppercaseLegal()
{
var snippet = "animation-direction : alternate-REVERSE";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-direction", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("alternate-reverse", property.Value);
}
[Test]
public void CssAnimationDirectionNormalAlternateReverseAlternateReverseLegal()
{
var snippet = "animation-direction: normal,alternate , reverse ,ALTERNATE-reverse !important";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation-direction", property.Name);
Assert.IsTrue(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("normal, alternate, reverse, alternate-reverse", property.Value);
}
[Test]
public void CssAnimationIterationCountLegal()
{
var snippet = "animation : 5";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("5", property.Value);
}
[Test]
public void CssAnimationNameLegal()
{
var snippet = "animation : my-animation";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("my-animation", property.Value);
}
[Test]
public void CssAnimationNameDurationDelayLegal()
{
var snippet = "animation : my-animation 2s 0.5s";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("2s 0.5s my-animation", property.Value);
}
[Test]
public void CssAnimationNameDurationDelayEaseLegal()
{
var snippet = "animation : my-animation 200ms 0.5s ease";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("200ms ease 0.5s my-animation", property.Value);
}
[Test]
public void CssAnimationCountDoubleIllegal()
{
var snippet = "animation : 10 20";
var property = ParseDeclaration(snippet);
Assert.IsFalse(property.HasValue);
}
[Test]
public void CssAnimationNameDurationCountEaseInOutLegal()
{
var snippet = "animation : my-animation 200ms 2.5 ease-in-out";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation", property.Name);
Assert.IsFalse(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("200ms ease-in-out 2.5 my-animation", property.Value);
}
[Test]
public void CssAnimationMultipleLegal()
{
var snippet = "animation : my-animation 0s 10 ease, other-animation 5 linear,yet-another 0s 1s 10 step-start !important";
var property = ParseDeclaration(snippet);
Assert.AreEqual("animation", property.Name);
Assert.IsTrue(property.IsImportant);
Assert.IsFalse(property.IsInherited);
Assert.IsTrue(property.HasValue);
Assert.AreEqual("0s ease 10 my-animation, linear 5 other-animation, 0s step-start 1s 10 yet-another", property.Value);
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Vevo;
using Vevo.DataAccessLib;
using Vevo.DataAccessLib.Cart;
using Vevo.Domain;
using Vevo.Domain.DataInterfaces;
using Vevo.Domain.Shipping;
using Vevo.Shared.Utilities;
using Vevo.WebUI.Ajax;
using Vevo.Base.Domain;
public partial class AdminAdvanced_MainControls_ShippingWeightRate : AdminAdvancedBaseUserControl
{
private string ShippingID
{
get
{
if (!String.IsNullOrEmpty( MainContext.QueryString["ShippingID"] ))
return MainContext.QueryString["ShippingID"];
else
return "0";
}
}
private GridViewHelper GridHelper
{
get
{
if (ViewState["GridHelper"] == null)
ViewState["GridHelper"] = new GridViewHelper( uxGrid, "ToWeight" );
return (GridViewHelper) ViewState["GridHelper"];
}
}
private void RefreshGrid()
{
int totalItems = 0;
IList<ShippingWeightRate> shippingWeightRateList = DataAccessContext.ShippingWeightRateRepository.SearchShippingWeightRateItem(
ShippingID,
GridHelper.GetFullSortText(),
uxSearchFilter.SearchFilterObj, uxPagingControl.StartIndex,
uxPagingControl.EndIndex,
out totalItems );
if (shippingWeightRateList == null || shippingWeightRateList.Count == 0)
{
shippingWeightRateList = new List<ShippingWeightRate>();
CreateDummyRow( shippingWeightRateList );
}
uxGrid.DataSource = shippingWeightRateList;
uxGrid.DataBind();
uxPagingControl.NumberOfPages = (int) Math.Ceiling( (double) totalItems / uxPagingControl.ItemsPerPages );
}
private void PopulateControls()
{
if (ShippingID == "0")
MainContext.RedirectMainControl( "ShippingList.ascx" );
if (!MainContext.IsPostBack)
{
RefreshGrid();
}
}
private void ApplyPermissions()
{
if (!IsAdminModifiable())
{
uxAddButton.Visible = false;
DeleteVisible( false );
}
else
DeleteVisible( true );
}
private void DeleteVisible( bool value )
{
uxDeleteButton.Visible = value;
if (value)
{
if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal)
{
uxDeleteConfirmButton.TargetControlID = "uxDeleteButton";
uxConfirmModalPopup.TargetControlID = "uxDeleteButton";
}
else
{
uxDeleteConfirmButton.TargetControlID = "uxDummyButton";
uxConfirmModalPopup.TargetControlID = "uxDummyButton";
}
}
else
{
uxDeleteConfirmButton.TargetControlID = "uxDummyButton";
uxConfirmModalPopup.TargetControlID = "uxDummyButton";
}
}
private void CreateDummyRow( IList<ShippingWeightRate> list )
{
ShippingWeightRate shippingWeightRate = new ShippingWeightRate();
shippingWeightRate.ShippingWeightRateID = "-1";
shippingWeightRate.ShippingID = ShippingID;
shippingWeightRate.ToWeight = 0;
shippingWeightRate.WeightRate = 0;
list.Add( shippingWeightRate );
}
private bool IsContainingOnlyEmptyRow()
{
if (uxGrid.Rows.Count == 1 &&
ConvertUtilities.ToInt32( uxGrid.DataKeys[0]["ShippingWeightRateID"] ) == -1)
return true;
else
return false;
}
protected void Page_Load( object sender, EventArgs e )
{
uxSearchFilter.BubbleEvent += new EventHandler( uxGrid_ResetHandler );
uxPagingControl.BubbleEvent += new EventHandler( uxPagingControl_RefreshHandler );
if (!MainContext.IsPostBack)
{
SetUpSearchFilter();
}
}
protected void Page_PreRender( object sender, EventArgs e )
{
PopulateControls();
ApplyPermissions();
}
private void uxGrid_ResetHandler( object sender, EventArgs e )
{
uxPagingControl.CurrentPage = 1;
RefreshGrid();
}
private void uxPagingControl_RefreshHandler( object sender, EventArgs e )
{
RefreshGrid();
}
private void SetFooterRowFocus()
{
Control textBox = uxGrid.FooterRow.FindControl( "uxToWeightText" );
AjaxUtilities.GetScriptManager( this ).SetFocus( textBox );
}
protected void uxEditLinkButton_PreRender( object sender, EventArgs e )
{
if (!IsAdminModifiable())
{
LinkButton linkButton = (LinkButton) sender;
linkButton.Visible = false;
}
}
protected void uxGrid_DataBound( object sender, EventArgs e )
{
if (IsContainingOnlyEmptyRow())
{
uxGrid.Rows[0].Visible = false;
}
}
protected void uxAddButton_Click( object sender, EventArgs e )
{
uxGrid.EditIndex = -1;
uxGrid.ShowFooter = true;
RefreshGrid();
uxAddButton.Visible = false;
SetFooterRowFocus();
uxStatusHidden.Value = "FooterShown";
}
private void ClearData( GridViewRow row )
{
((TextBox) row.FindControl( "uxToWeightText" )).Text = "";
((TextBox) row.FindControl( "uxShippingWeightRate" )).Text = "";
}
private ShippingWeightRate GetDetailsFromGrid( GridViewRow row, ShippingWeightRate shippingWeightRate )
{
shippingWeightRate.ShippingID = ShippingID;
string toWeightText = ((TextBox) row.FindControl( "uxToWeightText" )).Text;
shippingWeightRate.ToWeight = ConvertUtilities.ToDouble( toWeightText );
string shippingWeightRateText = ((TextBox) row.FindControl( "uxShippingWeightRate" )).Text;
shippingWeightRate.WeightRate = ConvertUtilities.ToDecimal( shippingWeightRateText );
return shippingWeightRate;
}
private bool IsCorrectFormatForShippingByWeight( GridViewRow row )
{
string toOrderTotalText = ((TextBox) row.FindControl( "uxToWeightText" )).Text;
Decimal ToOrderTotal = ConvertUtilities.ToDecimal( toOrderTotalText );
if (ToOrderTotal < 0) return false;
string shippingOrderTotalRateText = ((TextBox) row.FindControl( "uxShippingWeightRate" )).Text;
Decimal OrderTotalRate = ConvertUtilities.ToDecimal( shippingOrderTotalRateText );
if (OrderTotalRate < 0) return false;
return true;
}
private bool IsExisted( object addToWeight )
{
bool isExisted = false;
IList<ShippingWeightRate> shippingWeightRateList =
DataAccessContext.ShippingWeightRateRepository.GetAllByShippingID( ShippingID, "ToWeight" );
for (int i = 0; i < shippingWeightRateList.Count; i++)
{
if (shippingWeightRateList[i].ToWeight == ConvertUtilities.ToDouble( addToWeight ))
isExisted = true;
}
return isExisted;
}
protected void uxGrid_RowCommand( object sender, GridViewCommandEventArgs e )
{
if (e.CommandName == "Add")
{
GridViewRow rowAdd = uxGrid.FooterRow;
if (IsCorrectFormatForShippingByWeight( rowAdd ) == false)
{
uxStatusHidden.Value = "Error";
uxMessage.DisplayError( Resources.ShippingWeightRateMessage.TofewError );
return;
}
ShippingWeightRate shippingWeightRate = new ShippingWeightRate();
shippingWeightRate = GetDetailsFromGrid( rowAdd, shippingWeightRate );
if (!IsExisted( shippingWeightRate.ToWeight ))
{
if (shippingWeightRate.ToWeight <= SystemConst.UnlimitedNumber)
{
DataAccessContext.ShippingWeightRateRepository.Save( shippingWeightRate );
ClearData( rowAdd );
RefreshGrid();
uxStatusHidden.Value = "Added";
uxMessage.DisplayMessage( Resources.ShippingWeightRateMessage.ItemAddSuccess );
}
else
uxMessage.DisplayError( Resources.ShippingWeightRateMessage.TomuchItemError );
}
else
{
uxStatusHidden.Value = "Error";
uxMessage.DisplayError( Resources.ShippingWeightRateMessage.ToWeightError );
}
}
else if (e.CommandName == "Edit")
{
uxGrid.ShowFooter = false;
uxAddButton.Visible = true;
}
}
protected void uxGrid_RowEditing( object sender, GridViewEditEventArgs e )
{
uxGrid.EditIndex = e.NewEditIndex;
RefreshGrid();
}
protected void uxGrid_CancelingEdit( object sender, GridViewCancelEditEventArgs e )
{
uxGrid.EditIndex = -1;
RefreshGrid();
}
protected void uxDeleteButton_Click( object sender, EventArgs e )
{
try
{
bool deleted = false;
foreach (GridViewRow row in uxGrid.Rows)
{
CheckBox deleteCheck = (CheckBox) row.FindControl( "uxCheck" );
if (deleteCheck != null &&
deleteCheck.Checked)
{
string shippingWeightRateID =
uxGrid.DataKeys[row.RowIndex]["ShippingWeightRateID"].ToString();
DataAccessContext.ShippingWeightRateRepository.Delete( shippingWeightRateID );
deleted = true;
}
}
uxGrid.EditIndex = -1;
if (deleted)
uxMessage.DisplayMessage( Resources.ShippingWeightRateMessage.ItemDeleteSuccess );
uxStatusHidden.Value = "Deleted";
}
catch (Exception ex)
{
uxMessage.DisplayException( ex );
}
RefreshGrid();
if (uxGrid.Rows.Count == 0 && uxPagingControl.CurrentPage >= uxPagingControl.NumberOfPages)
{
uxPagingControl.CurrentPage = uxPagingControl.NumberOfPages;
RefreshGrid();
}
}
protected void uxGrid_RowUpdating( object sender, GridViewUpdateEventArgs e )
{
try
{
GridViewRow rowGrid = uxGrid.Rows[e.RowIndex];
if (IsCorrectFormatForShippingByWeight( rowGrid ) == false)
{
uxStatusHidden.Value = "Error";
uxMessage.DisplayError( Resources.ShippingWeightRateMessage.TofewError );
return;
}
string shippingWeightRateID = uxGrid.DataKeys[e.RowIndex]["ShippingWeightRateID"].ToString();
ShippingWeightRate shippingWeightRate = DataAccessContext.ShippingWeightRateRepository.GetOne( shippingWeightRateID );
shippingWeightRate = GetDetailsFromGrid( rowGrid, shippingWeightRate );
DataAccessContext.ShippingWeightRateRepository.Save( shippingWeightRate );
uxGrid.EditIndex = -1;
RefreshGrid();
uxStatusHidden.Value = "Updated";
uxMessage.DisplayMessage( Resources.ShippingWeightRateMessage.ItemUpdateSuccess );
}
finally
{
e.Cancel = true;
}
}
private void SetUpSearchFilter()
{
IList<TableSchemaItem> list = DataAccessContext.ShippingWeightRateRepository.GetTableSchema();
uxSearchFilter.SetUpSchema( list, "ShippingWeightRateID", "ShippingID", "ToWeight" );
}
public string ShowFromWeight( object toWeight )
{
double fromWeight = 0;
IList<ShippingWeightRate> shippingWeightRateList =
DataAccessContext.ShippingWeightRateRepository.GetAllByShippingID( ShippingID, "ToWeight" );
for (int i = 0; i < shippingWeightRateList.Count; i++)
{
if (shippingWeightRateList[i].ToWeight == ConvertUtilities.ToDouble( toWeight ))
break;
else
fromWeight = shippingWeightRateList[i].ToWeight;
}
if (fromWeight == 0)
return String.Format( "{0}", fromWeight );
else
return String.Format( "> {0}", fromWeight );
}
public bool CheckVisibleFromToWeight( string toWeight )
{
if (toWeight == SystemConst.UnlimitedNumber.ToString())
return false;
else
return true;
}
public string LastToWeight( string toWeight )
{
if (toWeight == SystemConst.UnlimitedNumber.ToString())
return "Above";
else
return toWeight;
}
protected void uxGrid_Sorting( object sender, GridViewSortEventArgs e )
{
GridHelper.SelectSorting( e.SortExpression );
RefreshGrid();
}
}
| |
/*(c) Copyright 2012, VersionOne, Inc. All rights reserved. (c)*/
using System;
using System.Collections;
using System.IO;
using System.Text;
using System.Xml;
namespace VersionOne.Profile
{
public class XmlProfileStore : IProfileStore
{
private IDictionary _values;
private IDictionary _newvalues;
private object _lock;
private string _filename;
private Stream _stream;
private XmlProfileStore()
{
_values = new Hashtable();
_newvalues = new Hashtable();
_lock = new object();
}
public XmlProfileStore(string filename) : this()
{
_filename = filename;
if ( !File.Exists(_filename) )
throw new InvalidOperationException("Cannot find XML Profile File at " + _filename);
XmlDocument doc = new XmlDocument();
doc.Load(filename);
LoadXml(doc.DocumentElement, ProfilePath.RootPath);
}
public XmlProfileStore(Stream xmlstream) : this()
{
_stream = xmlstream;
xmlstream.Seek(0, SeekOrigin.Begin);
XmlDocument doc = new XmlDocument();
doc.Load(xmlstream);
LoadXml(doc.DocumentElement, ProfilePath.RootPath);
}
private void LoadXml(XmlElement element, ProfilePath path)
{
if ( element.HasAttribute("value") )
{
string value = element.GetAttribute("value");
LoadValue(path, value);
}
foreach (XmlNode xmlnode in element.ChildNodes)
{
XmlElement child = xmlnode as XmlElement;
if ( child != null )
LoadXml(child, new ProfilePath(path, XmlNormalizer.TagDecode(child.LocalName)));
}
}
public IProfile this[string profilepath]
{
get
{
ProfilePath path = ProfilePath.RootPath.ResolvePath(profilepath);
ProfileNode node = new ProfileNode(this, path);
return node.IsRoot ? (IProfile) node : (IProfile) new VirtualNode(node);
}
}
public void Flush()
{
lock (_lock)
{
if ( _newvalues.Count == 0 ) return;
IDictionary result = new Hashtable(_values);
IUpdate batch = CreateNewUpdate();
foreach (DictionaryEntry newvalue in _newvalues)
{
ProfilePath path = (ProfilePath) newvalue.Key;
string value = (string) newvalue.Value;
if ( value == null )
{
if ( _values.Contains(path) )
{
batch.DeleteValue(path);
result.Remove(path);
}
}
else
{
if ( _values.Contains(path) )
{
batch.SaveValue(path, value);
result[path] = value;
}
else
{
batch.AddValue(path, value);
result.Add(path, value);
}
}
}
try
{
batch.Execute();
_values = result;
_newvalues.Clear();
batch.AcceptChanges();
}
catch
#if DEBUG
(Exception)
#endif
{
batch.DiscardChanges();
throw;
}
}
}
public void DiscardChanges()
{
lock (_lock)
_newvalues.Clear();
}
private string this[ProfilePath path]
{
get
{
lock (_lock)
{
if ( _newvalues.Contains(path) )
return (string) _newvalues[path];
return (string) _values[path];
}
}
set
{
lock (_lock)
{
if ( value != (string) _values[path] )
_newvalues[path] = value;
else
_newvalues.Remove(path);
}
}
}
private void LoadValue(ProfilePath path, string value)
{
_values[path] = value;
}
private interface IUpdate
{
void Execute();
void AcceptChanges();
void DiscardChanges();
void SaveValue(ProfilePath path, string value);
void AddValue(ProfilePath path, string value);
void DeleteValue(ProfilePath path);
}
private IUpdate CreateNewUpdate ()
{
return new UpdateBatch(this);
}
private class UpdateBatch : IUpdate
{
private XmlProfileStore _store;
private XmlProfileStore Store { get { return _store; } }
private XmlDocument _document;
public UpdateBatch(XmlProfileStore store)
{
_store = store;
_document = new XmlDocument();
if ( store._filename != null )
_document.Load(store._filename);
else
{
if ( !store._stream.CanWrite )
throw new InvalidOperationException("Stream cannot be written to.");
if ( !store._stream.CanSeek )
throw new InvalidOperationException("Stream cannot seek.");
store._stream.Seek(0, SeekOrigin.Begin);
_document.Load(store._stream);
store._stream.Seek(0, SeekOrigin.Begin);
}
}
public void Execute()
{
}
public void AcceptChanges()
{
XmlTextWriter writer = null;
if ( Store._filename != null )
writer = new XmlTextWriter(Store._filename, Encoding.UTF8);
else
writer = new XmlTextWriter(Store._stream, Encoding.UTF8);
writer.Formatting = Formatting.Indented;
XmlNodeReader reader = new XmlNodeReader(_document);
writer.WriteNode(reader, true);
writer.Flush();
writer.BaseStream.SetLength(writer.BaseStream.Position);
if ( Store._filename != null )
writer.Close();
}
public void DiscardChanges()
{
}
public void SaveValue(ProfilePath path, string value)
{
string name = EncodedPath(path);
XmlNode node = _document.DocumentElement.SelectSingleNode(name);
node.Attributes["value"].Value = value;
}
private static string EncodedPath(ProfilePath path)
{
string[] paths = new string[path.Length];
for (int i = 0; i < path.Length; i++)
paths[i] = XmlNormalizer.TagEncode(path[i]);
return string.Join("/", paths);
}
public void AddValue(ProfilePath path, string value)
{
XmlNode rootnode = _document.DocumentElement;
foreach (string name in path)
{
XmlNode node = null;
string n = XmlNormalizer.TagEncode(name);
node = rootnode.SelectSingleNode(n);
if ( node == null )
{
node = _document.CreateElement(n);
rootnode.AppendChild(node);
}
rootnode = node;
}
XmlAttribute attrib = _document.CreateAttribute("value");
rootnode.Attributes.Append(attrib);
attrib.Value = value;
}
public void DeleteValue(ProfilePath path)
{
string name = EncodedPath(path);
XmlElement lastone = _document.DocumentElement.SelectSingleNode(name) as XmlElement;
lastone.Attributes.RemoveNamedItem("value");
XmlElement node = lastone.ParentNode as XmlElement;
while (node != _document.DocumentElement)
{
if ( !node.HasAttribute("value") )
lastone = node;
node = node.ParentNode as XmlElement;
}
node.RemoveChild(lastone);
}
}
private class ProfilePath : IEnumerable
{
private readonly string[] _path;
private ProfilePath()
{
_path = new string[0];
}
public ProfilePath(string[] path)
{
if ( path == null || path.Length == 0 )
throw new ArgumentNullException("path");
for (int i = 0; i < path.Length; ++i)
{
string p = path[i];
if ( p == null || p.Length == 0 )
throw new ArgumentNullException(string.Format("path[{0}]", i));
}
_path = path;
}
public ProfilePath(ProfilePath parent, string child)
{
if ( child == null || child.Length == 0 )
throw new ArgumentNullException("child");
string[] parentpath = parent._path;
int length = parentpath.Length;
_path = new string[length + 1];
Array.Copy(parentpath, _path, length);
_path[length] = child;
}
internal ProfilePath(ProfilePath path)
{
_path = path._path;
}
protected ProfilePath(ProfilePath path, int start, int length)
{
_path = new string[length];
Array.Copy(path._path, start, _path, 0, length);
}
public static readonly ProfilePath RootPath = new ProfilePath();
public ProfilePath ParentPath
{
get
{
if ( IsRoot )
throw new InvalidOperationException();
if ( _path.Length > 1 ) return new ProfilePath(this, 0, _path.Length - 1);
return RootPath;
}
}
public string LastTerm
{
get
{
if ( IsRoot ) return string.Empty;
return _path[_path.Length - 1];
}
}
public int Length { get { return _path.Length; } }
public string this[int index] { get { return _path[index]; } }
public bool IsRoot { get { return _path.Length == 0; } }
public ProfilePath ResolvePath(string childpath)
{
if ( childpath.Length == 0 )
return this;
Stack currentpath = new Stack();
if ( childpath.StartsWith("//") )
childpath = childpath.Substring(2);
else if ( childpath[0] == '/' )
childpath = childpath.Substring(1);
else
{
foreach (string term in _path)
currentpath.Push(term);
}
while (childpath.Length > 0)
{
string currentterm;
int firstslash = childpath.IndexOf('/');
if ( firstslash == 0 )
throw new InvalidOperationException();
else if ( firstslash == -1 )
{
currentterm = childpath;
childpath = string.Empty;
}
else
{
currentterm = childpath.Substring(0, firstslash);
childpath = childpath.Substring(firstslash + 1);
}
if ( currentterm == ".." )
{
if ( currentpath.Count > 0 )
currentpath.Pop();
}
else if ( currentterm == "." )
{
}
else
currentpath.Push(currentterm);
}
if ( currentpath.Count == 0 )
return RootPath;
string[] terms = new string[currentpath.Count];
for (int i = terms.Length; i > 0;)
terms[--i] = (string) currentpath.Pop();
return new ProfilePath(terms);
}
public override string ToString()
{
return string.Join("/", _path);
}
public override bool Equals(object obj)
{
if ( ReferenceEquals(obj, null) || GetType() != obj.GetType() )
return false;
ProfilePath other = (ProfilePath) obj;
if ( ReferenceEquals(_path, other._path) ) return true;
if ( _path.Length != other._path.Length ) return false;
for (int i = 0; i < _path.Length; ++i)
if ( !_path[i].Equals(other._path[i]) )
return false;
return true;
}
public override int GetHashCode()
{
return HashCode.Hash(_path);
}
public IEnumerator GetEnumerator()
{
return _path.GetEnumerator();
}
}
private class ProfileNode : ProfilePath, IProfile
{
private XmlProfileStore _store;
public ProfileNode(XmlProfileStore store, ProfilePath path)
: base(path)
{
_store = store;
}
protected ProfileNode(XmlProfileStore store, ProfileNode parent, string child)
: base(parent, child)
{
_store = store;
}
public string Path { get { return '/' + ToString(); } }
public string Name { get { return LastTerm; } }
public string Token { get { return Path; } }
public string Value { get { return _store[new ProfilePath(this)]; } set { _store[new ProfilePath(this)] = value; } }
public IProfile Parent
{
get
{
if ( IsRoot ) return null;
return new ProfileNode(_store, ParentPath);
}
}
IProfile IProfile.this[string childpath] { get { return this[childpath]; } }
public ProfileNode this[string childpath]
{
get
{
if ( childpath.Length == 0 ) return this;
return new ProfileNode(_store, ResolvePath(childpath));
}
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lucene.Net.Analysis.Tokenattributes;
using Lucene.Net.Util;
namespace Lucene.Net.Analysis.Shingle
{
/*
* <p>A ShingleFilter constructs shingles (token n-grams) from a token stream.
* In other words, it creates combinations of tokens as a single token.
*
* <p>For example, the sentence "please divide this sentence into shingles"
* might be tokenized into shingles "please divide", "divide this",
* "this sentence", "sentence into", and "into shingles".
*
* <p>This filter handles position increments > 1 by inserting filler tokens
* (tokens with termtext "_"). It does not handle a position increment of 0.
*/
public sealed class ShingleFilter : TokenFilter
{
private LinkedList<State> shingleBuf = new LinkedList<State>();
private StringBuilder[] shingles;
private String tokenType = "shingle";
/*
* filler token for when positionIncrement is more than 1
*/
public static readonly char[] FILLER_TOKEN = { '_' };
/*
* default maximum shingle size is 2.
*/
public const int DEFAULT_MAX_SHINGLE_SIZE = 2;
/*
* The string to use when joining adjacent tokens to form a shingle
*/
public const String TOKEN_SEPARATOR = " ";
/*
* By default, we output unigrams (individual tokens) as well as shingles
* (token n-grams).
*/
private bool outputUnigrams = true;
/*
* maximum shingle size (number of tokens)
*/
private int maxShingleSize;
/*
* Constructs a ShingleFilter with the specified single size from the
* {@link TokenStream} <c>input</c>
*
* @param input input stream
* @param maxShingleSize maximum shingle size produced by the filter.
*/
public ShingleFilter(TokenStream input, int maxShingleSize)
: base(input)
{
SetMaxShingleSize(maxShingleSize);
this.termAtt = AddAttribute<ITermAttribute>(); ;
this.offsetAtt = AddAttribute<IOffsetAttribute>(); ;
this.posIncrAtt = AddAttribute<IPositionIncrementAttribute>(); ;
this.typeAtt = AddAttribute<ITypeAttribute>(); ;
}
/*
* Construct a ShingleFilter with default shingle size.
*
* @param input input stream
*/
public ShingleFilter(TokenStream input)
: this(input, DEFAULT_MAX_SHINGLE_SIZE)
{
}
/*
* Construct a ShingleFilter with the specified token type for shingle tokens.
*
* @param input input stream
* @param tokenType token type for shingle tokens
*/
public ShingleFilter(TokenStream input, String tokenType)
: this(input, DEFAULT_MAX_SHINGLE_SIZE)
{
setTokenType(tokenType);
}
/*
* Set the type of the shingle tokens produced by this filter.
* (default: "shingle")
*
* @param tokenType token tokenType
*/
public void setTokenType(String tokenType)
{
this.tokenType = tokenType;
}
/*
* Shall the output stream contain the input tokens (unigrams) as well as
* shingles? (default: true.)
*
* @param outputUnigrams Whether or not the output stream shall contain
* the input tokens (unigrams)
*/
public void SetOutputUnigrams(bool outputUnigrams)
{
this.outputUnigrams = outputUnigrams;
}
/*
* Set the max shingle size (default: 2)
*
* @param maxShingleSize max size of output shingles
*/
public void SetMaxShingleSize(int maxShingleSize)
{
if (maxShingleSize < 2)
{
throw new ArgumentException("Max shingle size must be >= 2");
}
shingles = new StringBuilder[maxShingleSize];
for (int i = 0; i < shingles.Length; i++)
{
shingles[i] = new StringBuilder();
}
this.maxShingleSize = maxShingleSize;
}
/*
* Clear the StringBuilders that are used for storing the output shingles.
*/
private void ClearShingles()
{
for (int i = 0; i < shingles.Length; i++)
{
shingles[i].Length = 0;
}
}
private AttributeSource.State nextToken;
private int shingleBufferPosition;
private int[] endOffsets;
/* (non-Javadoc)
* @see org.apache.lucene.analysis.TokenStream#next()
*/
public sealed override bool IncrementToken()
{
while (true)
{
if (nextToken == null)
{
if (!FillShingleBuffer())
{
return false;
}
}
nextToken = shingleBuf.First.Value;
if (outputUnigrams)
{
if (shingleBufferPosition == 0)
{
RestoreState(nextToken);
posIncrAtt.PositionIncrement = 1;
shingleBufferPosition++;
return true;
}
}
else if (shingleBufferPosition % this.maxShingleSize == 0)
{
shingleBufferPosition++;
}
if (shingleBufferPosition < shingleBuf.Count)
{
RestoreState(nextToken);
typeAtt.Type = tokenType;
offsetAtt.SetOffset(offsetAtt.StartOffset, endOffsets[shingleBufferPosition]);
StringBuilder buf = shingles[shingleBufferPosition];
int termLength = buf.Length;
char[] TermBuffer = termAtt.TermBuffer();
if (TermBuffer.Length < termLength)
TermBuffer = termAtt.ResizeTermBuffer(termLength);
buf.CopyTo(0, TermBuffer, 0, termLength);
termAtt.SetTermLength(termLength);
if ((!outputUnigrams) && shingleBufferPosition % this.maxShingleSize == 1)
{
posIncrAtt.PositionIncrement = 1;
}
else
{
posIncrAtt.PositionIncrement = 0;
}
shingleBufferPosition++;
if (shingleBufferPosition == shingleBuf.Count)
{
nextToken = null;
shingleBufferPosition = 0;
}
return true;
}
else
{
nextToken = null;
shingleBufferPosition = 0;
}
}
}
private int numFillerTokensToInsert;
private AttributeSource.State currentToken;
private bool hasCurrentToken;
private ITermAttribute termAtt;
private IOffsetAttribute offsetAtt;
private IPositionIncrementAttribute posIncrAtt;
private ITypeAttribute typeAtt;
/*
* Get the next token from the input stream and push it on the token buffer.
* If we encounter a token with position increment > 1, we put filler tokens
* on the token buffer.
* <p/>
* Returns null when the end of the input stream is reached.
* @return the next token, or null if at end of input stream
* @throws IOException if the input stream has a problem
*/
private bool GetNextToken()
{
while (true)
{
if (numFillerTokensToInsert > 0)
{
if (currentToken == null)
{
currentToken = CaptureState();
}
else
{
RestoreState(currentToken);
}
numFillerTokensToInsert--;
// A filler token occupies no space
offsetAtt.SetOffset(offsetAtt.StartOffset, offsetAtt.StartOffset);
termAtt.SetTermBuffer(FILLER_TOKEN, 0, FILLER_TOKEN.Length);
return true;
}
if (hasCurrentToken)
{
if (currentToken != null)
{
RestoreState(currentToken);
currentToken = null;
}
hasCurrentToken = false;
return true;
}
if (!input.IncrementToken()) return false;
hasCurrentToken = true;
if (posIncrAtt.PositionIncrement > 1)
{
numFillerTokensToInsert = posIncrAtt.PositionIncrement - 1;
}
}
}
/*
* Fill the output buffer with new shingles.
*
* @throws IOException if there's a problem getting the next token
*/
private bool FillShingleBuffer()
{
bool addedToken = false;
/*
* Try to fill the shingle buffer.
*/
do
{
if (GetNextToken())
{
shingleBuf.AddLast(CaptureState());
if (shingleBuf.Count > maxShingleSize)
{
shingleBuf.RemoveFirst();
}
addedToken = true;
}
else
{
break;
}
} while (shingleBuf.Count < maxShingleSize);
if (shingleBuf.Count == 0)
{
return false;
}
/*
* If no new token could be added to the shingle buffer, we have reached
* the end of the input stream and have to discard the least recent token.
*/
if (!addedToken)
{
shingleBuf.RemoveFirst();
}
if (shingleBuf.Count == 0)
{
return false;
}
ClearShingles();
endOffsets = new int[shingleBuf.Count];
// Set all offsets to 0
endOffsets.Initialize();
int i = 0;
for (IEnumerator<State> it = shingleBuf.GetEnumerator(); it.MoveNext(); )
{
RestoreState(it.Current);
for (int j = i; j < shingles.Length; j++)
{
if (shingles[j].Length != 0)
{
shingles[j].Append(TOKEN_SEPARATOR);
}
shingles[j].Append(termAtt.TermBuffer().Take(termAtt.TermLength()).ToArray());
}
endOffsets[i] = offsetAtt.EndOffset;
i++;
}
return true;
}
public override void Reset()
{
base.Reset();
nextToken = null;
shingleBufferPosition = 0;
shingleBuf.Clear();
numFillerTokensToInsert = 0;
currentToken = null;
hasCurrentToken = false;
}
}
}
| |
// 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.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http.Headers;
using System.Net.Test.Common;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class HttpRequestMessageTest : HttpClientHandlerTestBase
{
Version _expectedRequestMessageVersion = !PlatformDetection.IsFullFramework ? new Version(2,0) : new Version(1, 1);
[Fact]
public void Ctor_Default_CorrectDefaults()
{
var rm = new HttpRequestMessage();
Assert.Equal(HttpMethod.Get, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(null, rm.Content);
Assert.Equal(null, rm.RequestUri);
}
[Fact]
public void Ctor_RelativeStringUri_CorrectValues()
{
var rm = new HttpRequestMessage(HttpMethod.Post, "/relative");
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(null, rm.Content);
Assert.Equal(new Uri("/relative", UriKind.Relative), rm.RequestUri);
}
[Fact]
public void Ctor_AbsoluteStringUri_CorrectValues()
{
var rm = new HttpRequestMessage(HttpMethod.Post, "http://host/absolute/");
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(null, rm.Content);
Assert.Equal(new Uri("http://host/absolute/"), rm.RequestUri);
}
[Fact]
public void Ctor_NullStringUri_Accepted()
{
var rm = new HttpRequestMessage(HttpMethod.Put, (string)null);
Assert.Equal(null, rm.RequestUri);
Assert.Equal(HttpMethod.Put, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(null, rm.Content);
}
[Fact]
public void Ctor_RelativeUri_CorrectValues()
{
var uri = new Uri("/relative", UriKind.Relative);
var rm = new HttpRequestMessage(HttpMethod.Post, uri);
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(null, rm.Content);
Assert.Equal(uri, rm.RequestUri);
}
[Fact]
public void Ctor_AbsoluteUri_CorrectValues()
{
var uri = new Uri("http://host/absolute/");
var rm = new HttpRequestMessage(HttpMethod.Post, uri);
Assert.Equal(HttpMethod.Post, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(null, rm.Content);
Assert.Equal(uri, rm.RequestUri);
}
[Fact]
public void Ctor_NullUri_Accepted()
{
var rm = new HttpRequestMessage(HttpMethod.Put, (Uri)null);
Assert.Equal(null, rm.RequestUri);
Assert.Equal(HttpMethod.Put, rm.Method);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(null, rm.Content);
}
[Fact]
public void Ctor_NullMethod_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => new HttpRequestMessage(null, "http://example.com"));
}
[Fact]
public void Ctor_NonHttpUri_ThrowsArgumentException()
{
AssertExtensions.Throws<ArgumentException>("requestUri", () => new HttpRequestMessage(HttpMethod.Put, "ftp://example.com"));
}
[Fact]
public void Dispose_DisposeObject_ContentGetsDisposedAndSettersWillThrowButGettersStillWork()
{
var rm = new HttpRequestMessage(HttpMethod.Get, "http://example.com");
var content = new MockContent();
rm.Content = content;
Assert.False(content.IsDisposed);
rm.Dispose();
rm.Dispose(); // Multiple calls don't throw.
Assert.True(content.IsDisposed);
Assert.Throws<ObjectDisposedException>(() => { rm.Method = HttpMethod.Put; });
Assert.Throws<ObjectDisposedException>(() => { rm.RequestUri = null; });
Assert.Throws<ObjectDisposedException>(() => { rm.Version = new Version(1, 0); });
Assert.Throws<ObjectDisposedException>(() => { rm.Content = null; });
// Property getters should still work after disposing.
Assert.Equal(HttpMethod.Get, rm.Method);
Assert.Equal(new Uri("http://example.com"), rm.RequestUri);
Assert.Equal(_expectedRequestMessageVersion, rm.Version);
Assert.Equal(content, rm.Content);
}
[Fact]
public void Properties_SetPropertiesAndGetTheirValue_MatchingValues()
{
var rm = new HttpRequestMessage();
var content = new MockContent();
var uri = new Uri("https://example.com");
var version = new Version(1, 0);
var method = new HttpMethod("custom");
rm.Content = content;
rm.Method = method;
rm.RequestUri = uri;
rm.Version = version;
Assert.Equal(content, rm.Content);
Assert.Equal(uri, rm.RequestUri);
Assert.Equal(method, rm.Method);
Assert.Equal(version, rm.Version);
Assert.NotNull(rm.Headers);
Assert.NotNull(rm.Properties);
}
[Fact]
public void RequestUri_SetNonHttpUri_ThrowsArgumentException()
{
var rm = new HttpRequestMessage();
AssertExtensions.Throws<ArgumentException>("value", () => { rm.RequestUri = new Uri("ftp://example.com"); });
}
[Fact]
public void Version_SetToNull_ThrowsArgumentNullException()
{
var rm = new HttpRequestMessage();
Assert.Throws<ArgumentNullException>(() => { rm.Version = null; });
}
[Fact]
public void Method_SetToNull_ThrowsArgumentNullException()
{
var rm = new HttpRequestMessage();
Assert.Throws<ArgumentNullException>(() => { rm.Method = null; });
}
[Fact]
public void ToString_DefaultAndNonDefaultInstance_DumpAllFields()
{
var rm = new HttpRequestMessage();
string expected =
"Method: GET, RequestUri: '<null>', Version: " +
_expectedRequestMessageVersion.ToString(2) +
", Content: <null>, Headers:\r\n{\r\n}";
Assert.Equal(expected, rm.ToString());
rm.Method = HttpMethod.Put;
rm.RequestUri = new Uri("http://a.com/");
rm.Version = new Version(1, 0);
rm.Content = new StringContent("content");
// Note that there is no Content-Length header: The reason is that the value for Content-Length header
// doesn't get set by StringContent..ctor, but only if someone actually accesses the ContentLength property.
Assert.Equal(
"Method: PUT, RequestUri: 'http://a.com/', Version: 1.0, Content: " + typeof(StringContent).ToString() + ", Headers:\r\n" +
"{\r\n" +
" Content-Type: text/plain; charset=utf-8\r\n" +
"}", rm.ToString());
rm.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain", 0.2));
rm.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml", 0.1));
rm.Headers.Add("Custom-Request-Header", "value1");
rm.Content.Headers.Add("Custom-Content-Header", "value2");
Assert.Equal(
"Method: PUT, RequestUri: 'http://a.com/', Version: 1.0, Content: " + typeof(StringContent).ToString() + ", Headers:\r\n" +
"{\r\n" +
" Accept: text/plain; q=0.2\r\n" +
" Accept: text/xml; q=0.1\r\n" +
" Custom-Request-Header: value1\r\n" +
" Content-Type: text/plain; charset=utf-8\r\n" +
" Custom-Content-Header: value2\r\n" +
"}", rm.ToString());
}
[Theory]
[InlineData("DELETE")]
[InlineData("OPTIONS")]
[InlineData("HEAD")]
public async Task HttpRequest_BodylessMethod_NoContentLength(string method)
{
if (IsWinHttpHandler || IsNetfxHandler || IsUapHandler)
{
// Some platform handlers differ but we don't take it as failure.
return;
}
using (HttpClient client = new HttpClient())
{
await LoopbackServer.CreateServerAsync(async (server, uri) =>
{
var request = new HttpRequestMessage();
request.RequestUri = uri;
request.Method = new HttpMethod(method);
Task<HttpResponseMessage> requestTask = client.SendAsync(request);
await server.AcceptConnectionAsync(async connection =>
{
List<string> headers = await connection.ReadRequestHeaderAsync();
Assert.DoesNotContain(headers, line => line.StartsWith("Content-length"));
await connection.SendResponseAsync();
await requestTask;
});
});
}
}
#region Helper methods
private class MockContent : HttpContent
{
public bool IsDisposed { get; private set; }
protected override bool TryComputeLength(out long length)
{
throw new NotImplementedException();
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
throw new NotImplementedException();
}
protected override void Dispose(bool disposing)
{
IsDisposed = true;
base.Dispose(disposing);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using DarkMultiPlayerCommon;
using DarkMultiPlayer.Utilities;
namespace DarkMultiPlayer
{
[KSPAddon(KSPAddon.Startup.Instantly, true)]
public class Client : MonoBehaviour
{
private bool showGUI = true;
public static bool toolbarShowGUI = true;
public static bool modDisabled = false;
private bool dmpSaveChecked = false;
//Disconnect message
public static bool displayDisconnectMessage;
public static ScreenMessage disconnectMessage;
public static float lastDisconnectMessageCheck;
//Chosen by a 2147483647 sided dice roll. Guaranteed to be random.
public const int WINDOW_OFFSET = 1664952404;
//Hack gravity fix.
private Dictionary<CelestialBody, double> bodiesGees = new Dictionary<CelestialBody, double>();
//Command line connect
private static ServerEntry commandLineConnect;
//Thread safe RealTimeSinceStartup
private static float lastRealTimeSinceStartup;
private static long lastClockTicks;
//This singleton is only for other mod access to the following services.
public static Client dmpClient;
//Services
public Settings dmpSettings;
public ToolbarSupport toolbarSupport;
public UniverseSyncCache universeSyncCache;
public ModWorker modWorker;
public ModWindow modWindow;
public ConnectionWindow connectionWindow;
public OptionsWindow optionsWindow;
public UniverseConverter universeConverter;
public UniverseConverterWindow universeConverterWindow;
public DisclaimerWindow disclaimerWindow;
public DMPModInterface dmpModInterface;
public DMPGame dmpGame;
public Client()
{
//Fix DarkLog time/thread marker in the log during init.
DarkLog.SetMainThread();
lastClockTicks = DateTime.UtcNow.Ticks;
lastRealTimeSinceStartup = Time.realtimeSinceStartup;
dmpClient = this;
dmpSettings = new Settings();
toolbarSupport = new ToolbarSupport(dmpSettings);
universeSyncCache = new UniverseSyncCache(dmpSettings);
modWindow = new ModWindow();
modWorker = new ModWorker(modWindow);
modWindow.SetDependenices(modWorker);
universeConverter = new UniverseConverter(dmpSettings);
universeConverterWindow = new UniverseConverterWindow(universeConverter);
optionsWindow = new OptionsWindow(dmpSettings, universeSyncCache, modWorker, universeConverterWindow, toolbarSupport);
connectionWindow = new ConnectionWindow(dmpSettings, optionsWindow);
disclaimerWindow = new DisclaimerWindow(dmpSettings);
dmpModInterface = new DMPModInterface();
}
public Client fetch
{
get
{
return dmpClient;
}
}
public DMPGame fetchGame
{
get
{
return dmpGame;
}
}
public static float realtimeSinceStartup
{
get
{
long ticksDiff = DateTime.UtcNow.Ticks - lastClockTicks;
double secondsSinceUpdate = ticksDiff / 10000000d;
return lastRealTimeSinceStartup + (float)secondsSinceUpdate;
}
}
public void Start()
{
if (!CompatibilityChecker.IsCompatible() || !InstallChecker.IsCorrectlyInstalled())
modDisabled = true;
if (dmpSettings.disclaimerAccepted != 1)
{
modDisabled = true;
disclaimerWindow.SpawnDialog();
}
Profiler.DMPReferenceTime.Start();
DontDestroyOnLoad(this);
// Prevents symlink warning for development.
SetupDirectoriesIfNeeded();
// UniverseSyncCache needs to run expiry here
universeSyncCache.ExpireCache();
GameEvents.onHideUI.Add(() =>
{
showGUI = false;
});
GameEvents.onShowUI.Add(() =>
{
showGUI = true;
});
HandleCommandLineArgs();
long testTime = Compression.TestSysIOCompression();
DarkLog.Debug("System.IO compression works: " + Compression.sysIOCompressionWorks + ", test time: " + testTime + " ms.");
DarkLog.Debug("DarkMultiPlayer " + Common.PROGRAM_VERSION + ", protocol " + Common.PROTOCOL_VERSION + " Initialized!");
}
private void HandleCommandLineArgs()
{
bool nextLineIsAddress = false;
bool valid = false;
string address = null;
int port = 6702;
foreach (string commandLineArg in Environment.GetCommandLineArgs())
{
//Supporting IPv6 is FUN!
if (nextLineIsAddress)
{
valid = true;
nextLineIsAddress = false;
if (commandLineArg.Contains("dmp://"))
{
if (commandLineArg.Contains("[") && commandLineArg.Contains("]"))
{
//IPv6 literal
address = commandLineArg.Substring("dmp://[".Length);
address = address.Substring(0, address.LastIndexOf("]"));
if (commandLineArg.Contains("]:"))
{
//With port
string portString = commandLineArg.Substring(commandLineArg.LastIndexOf("]:") + 1);
if (!Int32.TryParse(portString, out port))
{
valid = false;
}
}
}
else
{
//IPv4 literal or hostname
if (commandLineArg.Substring("dmp://".Length).Contains(":"))
{
//With port
address = commandLineArg.Substring("dmp://".Length);
address = address.Substring(0, address.LastIndexOf(":"));
string portString = commandLineArg.Substring(commandLineArg.LastIndexOf(":") + 1);
if (!Int32.TryParse(portString, out port))
{
valid = false;
}
}
else
{
//Without port
address = commandLineArg.Substring("dmp://".Length);
}
}
}
else
{
valid = false;
}
}
if (commandLineArg == "-dmp")
{
nextLineIsAddress = true;
}
}
if (valid)
{
commandLineConnect = new ServerEntry();
commandLineConnect.address = address;
commandLineConnect.port = port;
DarkLog.Debug("Connecting via command line to: " + address + ", port: " + port);
}
else
{
DarkLog.Debug("Command line address is invalid: " + address + ", port: " + port);
}
}
public void Update()
{
long startClock = Profiler.DMPReferenceTime.ElapsedTicks;
lastClockTicks = DateTime.UtcNow.Ticks;
lastRealTimeSinceStartup = Time.realtimeSinceStartup;
DarkLog.Update();
if (modDisabled)
{
return;
}
try
{
if (HighLogic.LoadedScene == GameScenes.MAINMENU)
{
if (!modWorker.dllListBuilt)
{
modWorker.dllListBuilt = true;
modWorker.BuildDllFileList();
}
if (!dmpSaveChecked)
{
dmpSaveChecked = true;
SetupBlankGameIfNeeded();
}
}
//Handle GUI events
if (!connectionWindow.renameEventHandled)
{
dmpSettings.SaveSettings();
connectionWindow.renameEventHandled = true;
}
if (!connectionWindow.addEventHandled)
{
dmpSettings.servers.Add(connectionWindow.addEntry);
connectionWindow.addEntry = null;
dmpSettings.SaveSettings();
connectionWindow.addingServer = false;
connectionWindow.addEventHandled = true;
}
if (!connectionWindow.editEventHandled)
{
dmpSettings.servers[connectionWindow.selected].name = connectionWindow.editEntry.name;
dmpSettings.servers[connectionWindow.selected].address = connectionWindow.editEntry.address;
dmpSettings.servers[connectionWindow.selected].port = connectionWindow.editEntry.port;
connectionWindow.editEntry = null;
dmpSettings.SaveSettings();
connectionWindow.addingServer = false;
connectionWindow.editEventHandled = true;
}
if (!connectionWindow.removeEventHandled)
{
dmpSettings.servers.RemoveAt(connectionWindow.selected);
connectionWindow.selected = -1;
dmpSettings.SaveSettings();
connectionWindow.removeEventHandled = true;
}
if (!connectionWindow.connectEventHandled)
{
connectionWindow.connectEventHandled = true;
dmpGame = new DMPGame(dmpSettings, universeSyncCache, modWorker, connectionWindow, dmpModInterface, toolbarSupport, optionsWindow);
dmpGame.networkWorker.ConnectToServer(dmpSettings.servers[connectionWindow.selected].address, dmpSettings.servers[connectionWindow.selected].port);
}
if (commandLineConnect != null && HighLogic.LoadedScene == GameScenes.MAINMENU && Time.timeSinceLevelLoad > 1f)
{
dmpGame = new DMPGame(dmpSettings, universeSyncCache, modWorker, connectionWindow, dmpModInterface, toolbarSupport, optionsWindow);
dmpGame.networkWorker.ConnectToServer(commandLineConnect.address, commandLineConnect.port);
commandLineConnect = null;
}
if (!connectionWindow.disconnectEventHandled)
{
connectionWindow.disconnectEventHandled = true;
if (dmpGame != null)
{
if (dmpGame.networkWorker.state == ClientState.CONNECTING)
{
dmpGame.networkWorker.Disconnect("Cancelled connection to server");
}
else
{
dmpGame.networkWorker.SendDisconnect("Quit during initial sync");
}
dmpGame.Stop();
dmpGame = null;
}
}
connectionWindow.Update();
optionsWindow.Update();
universeConverterWindow.Update();
dmpModInterface.Update();
if (dmpGame != null)
{
foreach (Action updateAction in dmpGame.updateEvent)
{
try
{
updateAction();
}
catch (Exception e)
{
DarkLog.Debug("Threw in UpdateEvent, exception: " + e);
if (dmpGame.networkWorker.state != ClientState.RUNNING)
{
if (dmpGame.networkWorker.state != ClientState.DISCONNECTED)
{
dmpGame.networkWorker.SendDisconnect("Unhandled error while syncing!");
}
else
{
dmpGame.networkWorker.Disconnect("Unhandled error while syncing!");
}
}
}
}
}
//Force quit
if (dmpGame != null && dmpGame.forceQuit)
{
dmpGame.forceQuit = false;
dmpGame.Stop();
dmpGame = null;
StopGame();
}
if (displayDisconnectMessage)
{
if (HighLogic.LoadedScene != GameScenes.MAINMENU)
{
if ((Client.realtimeSinceStartup - lastDisconnectMessageCheck) > 1f)
{
lastDisconnectMessageCheck = Client.realtimeSinceStartup;
if (disconnectMessage != null)
{
disconnectMessage.duration = 0;
}
disconnectMessage = ScreenMessages.PostScreenMessage("You have been disconnected!", 2f, ScreenMessageStyle.UPPER_CENTER);
}
}
else
{
displayDisconnectMessage = false;
}
}
//Normal quit
if (dmpGame != null && dmpGame.running)
{
if (!dmpGame.playerStatusWindow.disconnectEventHandled)
{
dmpGame.playerStatusWindow.disconnectEventHandled = true;
dmpGame.forceQuit = true;
dmpGame.scenarioWorker.SendScenarioModules(true); // Send scenario modules before disconnecting
dmpGame.networkWorker.SendDisconnect("Quit");
}
if (dmpGame.screenshotWorker.uploadScreenshot)
{
dmpGame.screenshotWorker.uploadScreenshot = false;
StartCoroutine(UploadScreenshot());
}
if (HighLogic.CurrentGame.flagURL != dmpSettings.selectedFlag)
{
DarkLog.Debug("Saving selected flag");
dmpSettings.selectedFlag = HighLogic.CurrentGame.flagURL;
dmpSettings.SaveSettings();
dmpGame.flagSyncer.flagChangeEvent = true;
}
// save every GeeASL from each body in FlightGlobals
if (HighLogic.LoadedScene == GameScenes.FLIGHT && bodiesGees.Count == 0)
{
foreach (CelestialBody body in FlightGlobals.fetch.bodies)
{
bodiesGees.Add(body, body.GeeASL);
}
}
//handle use of cheats
if (!dmpGame.serverAllowCheats)
{
CheatOptions.InfinitePropellant = false;
CheatOptions.NoCrashDamage = false;
CheatOptions.IgnoreAgencyMindsetOnContracts = false;
CheatOptions.IgnoreMaxTemperature = false;
CheatOptions.InfiniteElectricity = false;
CheatOptions.NoCrashDamage = false;
CheatOptions.UnbreakableJoints = false;
foreach (KeyValuePair<CelestialBody, double> gravityEntry in bodiesGees)
{
gravityEntry.Key.GeeASL = gravityEntry.Value;
}
}
if (HighLogic.LoadedScene == GameScenes.FLIGHT && FlightGlobals.ready)
{
HighLogic.CurrentGame.Parameters.Flight.CanLeaveToSpaceCenter = !dmpGame.vesselWorker.isSpectating && dmpSettings.revertEnabled || (PauseMenu.canSaveAndExit == ClearToSaveStatus.CLEAR);
}
else
{
HighLogic.CurrentGame.Parameters.Flight.CanLeaveToSpaceCenter = true;
}
if (HighLogic.LoadedScene == GameScenes.MAINMENU)
{
dmpGame.networkWorker.SendDisconnect("Quit to main menu");
dmpGame.Stop();
dmpGame = null;
}
}
if (dmpGame != null && dmpGame.startGame)
{
dmpGame.startGame = false;
StartGame();
}
}
catch (Exception e)
{
if (dmpGame != null)
{
DarkLog.Debug("Threw in Update, state " + dmpGame.networkWorker.state.ToString() + ", exception: " + e);
if (dmpGame.networkWorker.state != ClientState.RUNNING)
{
if (dmpGame.networkWorker.state != ClientState.DISCONNECTED)
{
dmpGame.networkWorker.SendDisconnect("Unhandled error while syncing!");
}
else
{
dmpGame.networkWorker.Disconnect("Unhandled error while syncing!");
}
}
}
else
{
DarkLog.Debug("Threw in Update, state NO_NETWORKWORKER, exception: " + e);
}
}
Profiler.updateData.ReportTime(startClock);
}
public IEnumerator<WaitForEndOfFrame> UploadScreenshot()
{
yield return new WaitForEndOfFrame();
if (dmpGame != null)
{
dmpGame.screenshotWorker.SendScreenshot();
dmpGame.screenshotWorker.screenshotTaken = true;
}
}
public void FixedUpdate()
{
long startClock = Profiler.DMPReferenceTime.ElapsedTicks;
if (modDisabled)
{
return;
}
dmpModInterface.FixedUpdate();
if (dmpGame != null)
{
foreach (Action fixedUpdateAction in dmpGame.fixedUpdateEvent)
{
try
{
fixedUpdateAction();
}
catch (Exception e)
{
DarkLog.Debug("Threw in FixedUpdate event, exception: " + e);
if (dmpGame.networkWorker != null)
{
if (dmpGame.networkWorker.state != ClientState.RUNNING)
{
if (dmpGame.networkWorker.state != ClientState.DISCONNECTED)
{
dmpGame.networkWorker.SendDisconnect("Unhandled error while syncing!");
}
else
{
dmpGame.networkWorker.Disconnect("Unhandled error while syncing!");
}
}
}
}
}
}
Profiler.fixedUpdateData.ReportTime(startClock);
}
public void OnGUI()
{
//Window ID's - Doesn't include "random" offset.
//Connection window: 6702
//Status window: 6703
//Chat window: 6704
//Debug window: 6705
//Mod windw: 6706
//Craft library window: 6707
//Craft upload window: 6708
//Screenshot window: 6710
//Options window: 6711
//Converter window: 6712
//Disclaimer window: 6713
long startClock = Profiler.DMPReferenceTime.ElapsedTicks;
if (showGUI)
{
connectionWindow.Draw();
optionsWindow.Draw();
universeConverterWindow.Draw();
if (dmpGame != null)
{
foreach (Action drawAction in dmpGame.drawEvent)
{
try
{
// Don't hide the connectionWindow if we disabled DMP GUI
if (toolbarShowGUI || (!toolbarShowGUI && drawAction.Target.ToString() == "DarkMultiPlayer.connectionWindow"))
drawAction();
}
catch (Exception e)
{
DarkLog.Debug("Threw in OnGUI event, exception: " + e);
}
}
}
}
Profiler.guiData.ReportTime(startClock);
}
private void StartGame()
{
//Create new game object for our DMP session.
HighLogic.CurrentGame = CreateBlankGame();
//Set the game mode
HighLogic.CurrentGame.Mode = ConvertGameMode(dmpGame.gameMode);
//Set difficulty
HighLogic.CurrentGame.Parameters = dmpGame.serverParameters;
//Set universe time
HighLogic.CurrentGame.flightState.universalTime = dmpGame.timeSyncer.GetUniverseTime();
//Load DMP stuff
dmpGame.vesselWorker.LoadKerbalsIntoGame();
dmpGame.vesselWorker.LoadVesselsIntoGame();
//Load the scenarios from the server
dmpGame.scenarioWorker.LoadScenarioDataIntoGame();
//Load the missing scenarios as well (Eg, Contracts and stuff for career mode
dmpGame.scenarioWorker.LoadMissingScenarioDataIntoGame();
//This only makes KSP complain
HighLogic.CurrentGame.CrewRoster.ValidateAssignments(HighLogic.CurrentGame);
DarkLog.Debug("Starting " + dmpGame.gameMode + " game...");
//.Start() seems to stupidly .Load() somewhere - Let's overwrite it so it loads correctly.
GamePersistence.SaveGame(HighLogic.CurrentGame, "persistent", HighLogic.SaveFolder, SaveMode.OVERWRITE);
HighLogic.CurrentGame.Start();
dmpGame.chatWorker.display = true;
DarkLog.Debug("Started!");
}
private void StopGame()
{
HighLogic.SaveFolder = "DarkMultiPlayer";
if (HighLogic.LoadedScene != GameScenes.MAINMENU)
{
HighLogic.LoadScene(GameScenes.MAINMENU);
}
//HighLogic.CurrentGame = null; This is no bueno
bodiesGees.Clear();
}
public static Game.Modes ConvertGameMode(GameMode inputMode)
{
if (inputMode == GameMode.SANDBOX)
{
return Game.Modes.SANDBOX;
}
if (inputMode == GameMode.SCIENCE)
{
return Game.Modes.SCIENCE_SANDBOX;
}
if (inputMode == GameMode.CAREER)
{
return Game.Modes.CAREER;
}
return Game.Modes.SANDBOX;
}
private void OnApplicationQuit()
{
if (dmpGame != null && dmpGame.networkWorker.state == ClientState.RUNNING)
{
Application.CancelQuit();
dmpGame.scenarioWorker.SendScenarioModules(true);
HighLogic.LoadScene(GameScenes.MAINMENU);
}
}
private void SetupDirectoriesIfNeeded()
{
string darkMultiPlayerSavesDirectory = Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "saves"), "DarkMultiPlayer");
CreateIfNeeded(darkMultiPlayerSavesDirectory);
CreateIfNeeded(Path.Combine(darkMultiPlayerSavesDirectory, "Ships"));
CreateIfNeeded(Path.Combine(darkMultiPlayerSavesDirectory, Path.Combine("Ships", "VAB")));
CreateIfNeeded(Path.Combine(darkMultiPlayerSavesDirectory, Path.Combine("Ships", "SPH")));
CreateIfNeeded(Path.Combine(darkMultiPlayerSavesDirectory, "Subassemblies"));
string darkMultiPlayerCacheDirectory = Path.Combine(Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), "DarkMultiPlayer"), "Cache");
CreateIfNeeded(darkMultiPlayerCacheDirectory);
string darkMultiPlayerIncomingCacheDirectory = Path.Combine(Path.Combine(Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), "DarkMultiPlayer"), "Cache"), "Incoming");
CreateIfNeeded(darkMultiPlayerIncomingCacheDirectory);
string darkMultiPlayerFlagsDirectory = Path.Combine(Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "GameData"), "DarkMultiPlayer"), "Flags");
CreateIfNeeded(darkMultiPlayerFlagsDirectory);
}
private void SetupBlankGameIfNeeded()
{
string persistentFile = Path.Combine(Path.Combine(Path.Combine(KSPUtil.ApplicationRootPath, "saves"), "DarkMultiPlayer"), "persistent.sfs");
if (!File.Exists(persistentFile))
{
DarkLog.Debug("Creating new blank persistent.sfs file");
Game blankGame = CreateBlankGame();
HighLogic.SaveFolder = "DarkMultiPlayer";
GamePersistence.SaveGame(blankGame, "persistent", HighLogic.SaveFolder, SaveMode.OVERWRITE);
}
}
private Game CreateBlankGame()
{
Game returnGame = new Game();
//KSP complains about a missing message system if we don't do this.
returnGame.additionalSystems = new ConfigNode();
returnGame.additionalSystems.AddNode("MESSAGESYSTEM");
//Flightstate is null on new Game();
returnGame.flightState = new FlightState();
if (returnGame.flightState.mapViewFilterState == 0)
{
returnGame.flightState.mapViewFilterState = -1026;
}
//DMP stuff
returnGame.startScene = GameScenes.SPACECENTER;
returnGame.flagURL = dmpSettings.selectedFlag;
returnGame.Title = "DarkMultiPlayer";
if (dmpGame.warpWorker.warpMode == WarpMode.SUBSPACE)
{
returnGame.Parameters.Flight.CanQuickLoad = true;
returnGame.Parameters.Flight.CanRestart = true;
returnGame.Parameters.Flight.CanLeaveToEditor = true;
}
else
{
returnGame.Parameters.Flight.CanQuickLoad = false;
returnGame.Parameters.Flight.CanRestart = false;
returnGame.Parameters.Flight.CanLeaveToEditor = false;
}
HighLogic.SaveFolder = "DarkMultiPlayer";
return returnGame;
}
private void CreateIfNeeded(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Achartengine.Model {
// Metadata.xml XPath class reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']"
[global::Android.Runtime.Register ("org/achartengine/model/XYSeries", DoNotGenerateAcw=true)]
public partial class XYSeries : global::Java.Lang.Object, global::Java.IO.ISerializable {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/achartengine/model/XYSeries", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (XYSeries); }
}
protected XYSeries (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_Ljava_lang_String_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/constructor[@name='XYSeries' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register (".ctor", "(Ljava/lang/String;)V", "")]
public XYSeries (string p0) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
IntPtr native_p0 = JNIEnv.NewString (p0);;
if (GetType () != typeof (XYSeries)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Ljava/lang/String;)V", new JValue (native_p0)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Ljava/lang/String;)V", new JValue (native_p0));
JNIEnv.DeleteLocalRef (native_p0);
return;
}
if (id_ctor_Ljava_lang_String_ == IntPtr.Zero)
id_ctor_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/String;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_String_, new JValue (native_p0)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Ljava_lang_String_, new JValue (native_p0));
JNIEnv.DeleteLocalRef (native_p0);
}
static IntPtr id_ctor_Ljava_lang_String_I;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/constructor[@name='XYSeries' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='int']]"
[Register (".ctor", "(Ljava/lang/String;I)V", "")]
public XYSeries (string p0, int p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
IntPtr native_p0 = JNIEnv.NewString (p0);;
if (GetType () != typeof (XYSeries)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Ljava/lang/String;I)V", new JValue (native_p0), new JValue (p1)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Ljava/lang/String;I)V", new JValue (native_p0), new JValue (p1));
JNIEnv.DeleteLocalRef (native_p0);
return;
}
if (id_ctor_Ljava_lang_String_I == IntPtr.Zero)
id_ctor_Ljava_lang_String_I = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/String;I)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_String_I, new JValue (native_p0), new JValue (p1)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Ljava_lang_String_I, new JValue (native_p0), new JValue (p1));
JNIEnv.DeleteLocalRef (native_p0);
}
static Delegate cb_getAnnotationCount;
#pragma warning disable 0169
static Delegate GetGetAnnotationCountHandler ()
{
if (cb_getAnnotationCount == null)
cb_getAnnotationCount = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetAnnotationCount);
return cb_getAnnotationCount;
}
static int n_GetAnnotationCount (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.AnnotationCount;
}
#pragma warning restore 0169
static IntPtr id_getAnnotationCount;
public virtual int AnnotationCount {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getAnnotationCount' and count(parameter)=0]"
[Register ("getAnnotationCount", "()I", "GetGetAnnotationCountHandler")]
get {
if (id_getAnnotationCount == IntPtr.Zero)
id_getAnnotationCount = JNIEnv.GetMethodID (class_ref, "getAnnotationCount", "()I");
if (GetType () == ThresholdType)
return JNIEnv.CallIntMethod (Handle, id_getAnnotationCount);
else
return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, id_getAnnotationCount);
}
}
static Delegate cb_getItemCount;
#pragma warning disable 0169
static Delegate GetGetItemCountHandler ()
{
if (cb_getItemCount == null)
cb_getItemCount = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetItemCount);
return cb_getItemCount;
}
static int n_GetItemCount (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.ItemCount;
}
#pragma warning restore 0169
static IntPtr id_getItemCount;
public virtual int ItemCount {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getItemCount' and count(parameter)=0]"
[Register ("getItemCount", "()I", "GetGetItemCountHandler")]
get {
if (id_getItemCount == IntPtr.Zero)
id_getItemCount = JNIEnv.GetMethodID (class_ref, "getItemCount", "()I");
if (GetType () == ThresholdType)
return JNIEnv.CallIntMethod (Handle, id_getItemCount);
else
return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, id_getItemCount);
}
}
static Delegate cb_getMaxX;
#pragma warning disable 0169
static Delegate GetGetMaxXHandler ()
{
if (cb_getMaxX == null)
cb_getMaxX = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, double>) n_GetMaxX);
return cb_getMaxX;
}
static double n_GetMaxX (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.MaxX;
}
#pragma warning restore 0169
static IntPtr id_getMaxX;
public virtual double MaxX {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getMaxX' and count(parameter)=0]"
[Register ("getMaxX", "()D", "GetGetMaxXHandler")]
get {
if (id_getMaxX == IntPtr.Zero)
id_getMaxX = JNIEnv.GetMethodID (class_ref, "getMaxX", "()D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getMaxX);
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getMaxX);
}
}
static Delegate cb_getMaxY;
#pragma warning disable 0169
static Delegate GetGetMaxYHandler ()
{
if (cb_getMaxY == null)
cb_getMaxY = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, double>) n_GetMaxY);
return cb_getMaxY;
}
static double n_GetMaxY (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.MaxY;
}
#pragma warning restore 0169
static IntPtr id_getMaxY;
public virtual double MaxY {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getMaxY' and count(parameter)=0]"
[Register ("getMaxY", "()D", "GetGetMaxYHandler")]
get {
if (id_getMaxY == IntPtr.Zero)
id_getMaxY = JNIEnv.GetMethodID (class_ref, "getMaxY", "()D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getMaxY);
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getMaxY);
}
}
static Delegate cb_getMinX;
#pragma warning disable 0169
static Delegate GetGetMinXHandler ()
{
if (cb_getMinX == null)
cb_getMinX = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, double>) n_GetMinX);
return cb_getMinX;
}
static double n_GetMinX (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.MinX;
}
#pragma warning restore 0169
static IntPtr id_getMinX;
public virtual double MinX {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getMinX' and count(parameter)=0]"
[Register ("getMinX", "()D", "GetGetMinXHandler")]
get {
if (id_getMinX == IntPtr.Zero)
id_getMinX = JNIEnv.GetMethodID (class_ref, "getMinX", "()D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getMinX);
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getMinX);
}
}
static Delegate cb_getMinY;
#pragma warning disable 0169
static Delegate GetGetMinYHandler ()
{
if (cb_getMinY == null)
cb_getMinY = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, double>) n_GetMinY);
return cb_getMinY;
}
static double n_GetMinY (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.MinY;
}
#pragma warning restore 0169
static IntPtr id_getMinY;
public virtual double MinY {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getMinY' and count(parameter)=0]"
[Register ("getMinY", "()D", "GetGetMinYHandler")]
get {
if (id_getMinY == IntPtr.Zero)
id_getMinY = JNIEnv.GetMethodID (class_ref, "getMinY", "()D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getMinY);
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getMinY);
}
}
static Delegate cb_getPadding;
#pragma warning disable 0169
static Delegate GetGetPaddingHandler ()
{
if (cb_getPadding == null)
cb_getPadding = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, double>) n_GetPadding);
return cb_getPadding;
}
static double n_GetPadding (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.Padding;
}
#pragma warning restore 0169
static IntPtr id_getPadding;
protected virtual double Padding {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getPadding' and count(parameter)=0]"
[Register ("getPadding", "()D", "GetGetPaddingHandler")]
get {
if (id_getPadding == IntPtr.Zero)
id_getPadding = JNIEnv.GetMethodID (class_ref, "getPadding", "()D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getPadding);
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getPadding);
}
}
static Delegate cb_getScaleNumber;
#pragma warning disable 0169
static Delegate GetGetScaleNumberHandler ()
{
if (cb_getScaleNumber == null)
cb_getScaleNumber = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int>) n_GetScaleNumber);
return cb_getScaleNumber;
}
static int n_GetScaleNumber (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.ScaleNumber;
}
#pragma warning restore 0169
static IntPtr id_getScaleNumber;
public virtual int ScaleNumber {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getScaleNumber' and count(parameter)=0]"
[Register ("getScaleNumber", "()I", "GetGetScaleNumberHandler")]
get {
if (id_getScaleNumber == IntPtr.Zero)
id_getScaleNumber = JNIEnv.GetMethodID (class_ref, "getScaleNumber", "()I");
if (GetType () == ThresholdType)
return JNIEnv.CallIntMethod (Handle, id_getScaleNumber);
else
return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, id_getScaleNumber);
}
}
static Delegate cb_getTitle;
#pragma warning disable 0169
static Delegate GetGetTitleHandler ()
{
if (cb_getTitle == null)
cb_getTitle = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetTitle);
return cb_getTitle;
}
static IntPtr n_GetTitle (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.NewString (__this.Title);
}
#pragma warning restore 0169
static Delegate cb_setTitle_Ljava_lang_String_;
#pragma warning disable 0169
static Delegate GetSetTitle_Ljava_lang_String_Handler ()
{
if (cb_setTitle_Ljava_lang_String_ == null)
cb_setTitle_Ljava_lang_String_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr>) n_SetTitle_Ljava_lang_String_);
return cb_setTitle_Ljava_lang_String_;
}
static void n_SetTitle_Ljava_lang_String_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
__this.Title = p0;
}
#pragma warning restore 0169
static IntPtr id_getTitle;
static IntPtr id_setTitle_Ljava_lang_String_;
public virtual string Title {
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getTitle' and count(parameter)=0]"
[Register ("getTitle", "()Ljava/lang/String;", "GetGetTitleHandler")]
get {
if (id_getTitle == IntPtr.Zero)
id_getTitle = JNIEnv.GetMethodID (class_ref, "getTitle", "()Ljava/lang/String;");
if (GetType () == ThresholdType)
return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getTitle), JniHandleOwnership.TransferLocalRef);
else
return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_getTitle), JniHandleOwnership.TransferLocalRef);
}
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='setTitle' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("setTitle", "(Ljava/lang/String;)V", "GetSetTitle_Ljava_lang_String_Handler")]
set {
if (id_setTitle_Ljava_lang_String_ == IntPtr.Zero)
id_setTitle_Ljava_lang_String_ = JNIEnv.GetMethodID (class_ref, "setTitle", "(Ljava/lang/String;)V");
IntPtr native_value = JNIEnv.NewString (value);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_setTitle_Ljava_lang_String_, new JValue (native_value));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_setTitle_Ljava_lang_String_, new JValue (native_value));
JNIEnv.DeleteLocalRef (native_value);
}
}
static Delegate cb_add_DD;
#pragma warning disable 0169
static Delegate GetAdd_DDHandler ()
{
if (cb_add_DD == null)
cb_add_DD = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, double, double>) n_Add_DD);
return cb_add_DD;
}
static void n_Add_DD (IntPtr jnienv, IntPtr native__this, double p0, double p1)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Add (p0, p1);
}
#pragma warning restore 0169
static IntPtr id_add_DD;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='add' and count(parameter)=2 and parameter[1][@type='double'] and parameter[2][@type='double']]"
[Register ("add", "(DD)V", "GetAdd_DDHandler")]
public virtual void Add (double p0, double p1)
{
if (id_add_DD == IntPtr.Zero)
id_add_DD = JNIEnv.GetMethodID (class_ref, "add", "(DD)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_add_DD, new JValue (p0), new JValue (p1));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_add_DD, new JValue (p0), new JValue (p1));
}
static Delegate cb_add_IDD;
#pragma warning disable 0169
static Delegate GetAdd_IDDHandler ()
{
if (cb_add_IDD == null)
cb_add_IDD = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int, double, double>) n_Add_IDD);
return cb_add_IDD;
}
static void n_Add_IDD (IntPtr jnienv, IntPtr native__this, int p0, double p1, double p2)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Add (p0, p1, p2);
}
#pragma warning restore 0169
static IntPtr id_add_IDD;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='add' and count(parameter)=3 and parameter[1][@type='int'] and parameter[2][@type='double'] and parameter[3][@type='double']]"
[Register ("add", "(IDD)V", "GetAdd_IDDHandler")]
public virtual void Add (int p0, double p1, double p2)
{
if (id_add_IDD == IntPtr.Zero)
id_add_IDD = JNIEnv.GetMethodID (class_ref, "add", "(IDD)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_add_IDD, new JValue (p0), new JValue (p1), new JValue (p2));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_add_IDD, new JValue (p0), new JValue (p1), new JValue (p2));
}
static Delegate cb_addAnnotation_Ljava_lang_String_DD;
#pragma warning disable 0169
static Delegate GetAddAnnotation_Ljava_lang_String_DDHandler ()
{
if (cb_addAnnotation_Ljava_lang_String_DD == null)
cb_addAnnotation_Ljava_lang_String_DD = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, double, double>) n_AddAnnotation_Ljava_lang_String_DD);
return cb_addAnnotation_Ljava_lang_String_DD;
}
static void n_AddAnnotation_Ljava_lang_String_DD (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, double p1, double p2)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
string p0 = JNIEnv.GetString (native_p0, JniHandleOwnership.DoNotTransfer);
__this.AddAnnotation (p0, p1, p2);
}
#pragma warning restore 0169
static IntPtr id_addAnnotation_Ljava_lang_String_DD;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='addAnnotation' and count(parameter)=3 and parameter[1][@type='java.lang.String'] and parameter[2][@type='double'] and parameter[3][@type='double']]"
[Register ("addAnnotation", "(Ljava/lang/String;DD)V", "GetAddAnnotation_Ljava_lang_String_DDHandler")]
public virtual void AddAnnotation (string p0, double p1, double p2)
{
if (id_addAnnotation_Ljava_lang_String_DD == IntPtr.Zero)
id_addAnnotation_Ljava_lang_String_DD = JNIEnv.GetMethodID (class_ref, "addAnnotation", "(Ljava/lang/String;DD)V");
IntPtr native_p0 = JNIEnv.NewString (p0);
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_addAnnotation_Ljava_lang_String_DD, new JValue (native_p0), new JValue (p1), new JValue (p2));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_addAnnotation_Ljava_lang_String_DD, new JValue (native_p0), new JValue (p1), new JValue (p2));
JNIEnv.DeleteLocalRef (native_p0);
}
static Delegate cb_clear;
#pragma warning disable 0169
static Delegate GetClearHandler ()
{
if (cb_clear == null)
cb_clear = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr>) n_Clear);
return cb_clear;
}
static void n_Clear (IntPtr jnienv, IntPtr native__this)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Clear ();
}
#pragma warning restore 0169
static IntPtr id_clear;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='clear' and count(parameter)=0]"
[Register ("clear", "()V", "GetClearHandler")]
public virtual void Clear ()
{
if (id_clear == IntPtr.Zero)
id_clear = JNIEnv.GetMethodID (class_ref, "clear", "()V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_clear);
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_clear);
}
static Delegate cb_getAnnotationAt_I;
#pragma warning disable 0169
static Delegate GetGetAnnotationAt_IHandler ()
{
if (cb_getAnnotationAt_I == null)
cb_getAnnotationAt_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, IntPtr>) n_GetAnnotationAt_I);
return cb_getAnnotationAt_I;
}
static IntPtr n_GetAnnotationAt_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.NewString (__this.GetAnnotationAt (p0));
}
#pragma warning restore 0169
static IntPtr id_getAnnotationAt_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getAnnotationAt' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getAnnotationAt", "(I)Ljava/lang/String;", "GetGetAnnotationAt_IHandler")]
public virtual string GetAnnotationAt (int p0)
{
if (id_getAnnotationAt_I == IntPtr.Zero)
id_getAnnotationAt_I = JNIEnv.GetMethodID (class_ref, "getAnnotationAt", "(I)Ljava/lang/String;");
if (GetType () == ThresholdType)
return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getAnnotationAt_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
else
return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_getAnnotationAt_I, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_getAnnotationX_I;
#pragma warning disable 0169
static Delegate GetGetAnnotationX_IHandler ()
{
if (cb_getAnnotationX_I == null)
cb_getAnnotationX_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, double>) n_GetAnnotationX_I);
return cb_getAnnotationX_I;
}
static double n_GetAnnotationX_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.GetAnnotationX (p0);
}
#pragma warning restore 0169
static IntPtr id_getAnnotationX_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getAnnotationX' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getAnnotationX", "(I)D", "GetGetAnnotationX_IHandler")]
public virtual double GetAnnotationX (int p0)
{
if (id_getAnnotationX_I == IntPtr.Zero)
id_getAnnotationX_I = JNIEnv.GetMethodID (class_ref, "getAnnotationX", "(I)D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getAnnotationX_I, new JValue (p0));
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getAnnotationX_I, new JValue (p0));
}
static Delegate cb_getAnnotationY_I;
#pragma warning disable 0169
static Delegate GetGetAnnotationY_IHandler ()
{
if (cb_getAnnotationY_I == null)
cb_getAnnotationY_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, double>) n_GetAnnotationY_I);
return cb_getAnnotationY_I;
}
static double n_GetAnnotationY_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.GetAnnotationY (p0);
}
#pragma warning restore 0169
static IntPtr id_getAnnotationY_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getAnnotationY' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getAnnotationY", "(I)D", "GetGetAnnotationY_IHandler")]
public virtual double GetAnnotationY (int p0)
{
if (id_getAnnotationY_I == IntPtr.Zero)
id_getAnnotationY_I = JNIEnv.GetMethodID (class_ref, "getAnnotationY", "(I)D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getAnnotationY_I, new JValue (p0));
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getAnnotationY_I, new JValue (p0));
}
static Delegate cb_getIndexForKey_D;
#pragma warning disable 0169
static Delegate GetGetIndexForKey_DHandler ()
{
if (cb_getIndexForKey_D == null)
cb_getIndexForKey_D = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, double, int>) n_GetIndexForKey_D);
return cb_getIndexForKey_D;
}
static int n_GetIndexForKey_D (IntPtr jnienv, IntPtr native__this, double p0)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.GetIndexForKey (p0);
}
#pragma warning restore 0169
static IntPtr id_getIndexForKey_D;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getIndexForKey' and count(parameter)=1 and parameter[1][@type='double']]"
[Register ("getIndexForKey", "(D)I", "GetGetIndexForKey_DHandler")]
public virtual int GetIndexForKey (double p0)
{
if (id_getIndexForKey_D == IntPtr.Zero)
id_getIndexForKey_D = JNIEnv.GetMethodID (class_ref, "getIndexForKey", "(D)I");
if (GetType () == ThresholdType)
return JNIEnv.CallIntMethod (Handle, id_getIndexForKey_D, new JValue (p0));
else
return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, id_getIndexForKey_D, new JValue (p0));
}
static Delegate cb_getRange_DDZ;
#pragma warning disable 0169
static Delegate GetGetRange_DDZHandler ()
{
if (cb_getRange_DDZ == null)
cb_getRange_DDZ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, double, double, bool, IntPtr>) n_GetRange_DDZ);
return cb_getRange_DDZ;
}
static IntPtr n_GetRange_DDZ (IntPtr jnienv, IntPtr native__this, double p0, double p1, bool p2)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return global::Android.Runtime.JavaDictionary<global::Java.Lang.Double, global::Java.Lang.Double>.ToLocalJniHandle (__this.GetRange (p0, p1, p2));
}
#pragma warning restore 0169
static IntPtr id_getRange_DDZ;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getRange' and count(parameter)=3 and parameter[1][@type='double'] and parameter[2][@type='double'] and parameter[3][@type='boolean']]"
[Register ("getRange", "(DDZ)Ljava/util/SortedMap;", "GetGetRange_DDZHandler")]
public virtual global::System.Collections.Generic.IDictionary<global::Java.Lang.Double, global::Java.Lang.Double> GetRange (double p0, double p1, bool p2)
{
if (id_getRange_DDZ == IntPtr.Zero)
id_getRange_DDZ = JNIEnv.GetMethodID (class_ref, "getRange", "(DDZ)Ljava/util/SortedMap;");
if (GetType () == ThresholdType)
return global::Android.Runtime.JavaDictionary<global::Java.Lang.Double, global::Java.Lang.Double>.FromJniHandle (JNIEnv.CallObjectMethod (Handle, id_getRange_DDZ, new JValue (p0), new JValue (p1), new JValue (p2)), JniHandleOwnership.TransferLocalRef);
else
return global::Android.Runtime.JavaDictionary<global::Java.Lang.Double, global::Java.Lang.Double>.FromJniHandle (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_getRange_DDZ, new JValue (p0), new JValue (p1), new JValue (p2)), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_getX_I;
#pragma warning disable 0169
static Delegate GetGetX_IHandler ()
{
if (cb_getX_I == null)
cb_getX_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, double>) n_GetX_I);
return cb_getX_I;
}
static double n_GetX_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.GetX (p0);
}
#pragma warning restore 0169
static IntPtr id_getX_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getX' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getX", "(I)D", "GetGetX_IHandler")]
public virtual double GetX (int p0)
{
if (id_getX_I == IntPtr.Zero)
id_getX_I = JNIEnv.GetMethodID (class_ref, "getX", "(I)D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getX_I, new JValue (p0));
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getX_I, new JValue (p0));
}
static Delegate cb_getY_I;
#pragma warning disable 0169
static Delegate GetGetY_IHandler ()
{
if (cb_getY_I == null)
cb_getY_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, double>) n_GetY_I);
return cb_getY_I;
}
static double n_GetY_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return __this.GetY (p0);
}
#pragma warning restore 0169
static IntPtr id_getY_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='getY' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("getY", "(I)D", "GetGetY_IHandler")]
public virtual double GetY (int p0)
{
if (id_getY_I == IntPtr.Zero)
id_getY_I = JNIEnv.GetMethodID (class_ref, "getY", "(I)D");
if (GetType () == ThresholdType)
return JNIEnv.CallDoubleMethod (Handle, id_getY_I, new JValue (p0));
else
return JNIEnv.CallNonvirtualDoubleMethod (Handle, ThresholdClass, id_getY_I, new JValue (p0));
}
static Delegate cb_remove_I;
#pragma warning disable 0169
static Delegate GetRemove_IHandler ()
{
if (cb_remove_I == null)
cb_remove_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int>) n_Remove_I);
return cb_remove_I;
}
static void n_Remove_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.Remove (p0);
}
#pragma warning restore 0169
static IntPtr id_remove_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='remove' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("remove", "(I)V", "GetRemove_IHandler")]
public virtual void Remove (int p0)
{
if (id_remove_I == IntPtr.Zero)
id_remove_I = JNIEnv.GetMethodID (class_ref, "remove", "(I)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_remove_I, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_remove_I, new JValue (p0));
}
static Delegate cb_removeAnnotation_I;
#pragma warning disable 0169
static Delegate GetRemoveAnnotation_IHandler ()
{
if (cb_removeAnnotation_I == null)
cb_removeAnnotation_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int>) n_RemoveAnnotation_I);
return cb_removeAnnotation_I;
}
static void n_RemoveAnnotation_I (IntPtr jnienv, IntPtr native__this, int p0)
{
global::Org.Achartengine.Model.XYSeries __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Model.XYSeries> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
__this.RemoveAnnotation (p0);
}
#pragma warning restore 0169
static IntPtr id_removeAnnotation_I;
// Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.model']/class[@name='XYSeries']/method[@name='removeAnnotation' and count(parameter)=1 and parameter[1][@type='int']]"
[Register ("removeAnnotation", "(I)V", "GetRemoveAnnotation_IHandler")]
public virtual void RemoveAnnotation (int p0)
{
if (id_removeAnnotation_I == IntPtr.Zero)
id_removeAnnotation_I = JNIEnv.GetMethodID (class_ref, "removeAnnotation", "(I)V");
if (GetType () == ThresholdType)
JNIEnv.CallVoidMethod (Handle, id_removeAnnotation_I, new JValue (p0));
else
JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_removeAnnotation_I, new JValue (p0));
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="Registry.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright>
//-----------------------------------------------------------------------
namespace MSBuild.ExtensionPack.Computer
{
using System;
using System.Globalization;
using System.Text;
using Microsoft.Build.Framework;
using Microsoft.Win32;
/// <summary>
/// <b>Valid TaskActions are:</b>
/// <para><i>CheckEmpty</i> (<b>Required: </b> RegistryHive, Key <b>Optional:</b> RegistryView <b>Output: </b>Empty)</para>
/// <para><i>CheckValueExists</i> (<b>Required: </b> RegistryHive, Key, Value <b>Optional:</b> RegistryView <b>Output: </b>Empty (true iff the value does not exist))</para>
/// <para><i>CreateKey</i> (<b>Required: </b> RegistryHive, Key <b>Optional:</b> RegistryView)</para>
/// <para><i>DeleteKey</i> (<b>Required: </b> RegistryHive, Key <b>Optional:</b> RegistryView)</para>
/// <para><i>DeleteKeyTree</i> (<b>Required: </b> RegistryHive, Key <b>Optional:</b> RegistryView )</para>
/// <para><i>DeleteValue</i> (<b>Required: </b> RegistryHive, Key, Value <b>Optional:</b> RegistryView<b>Output: </b>Empty (true iff the Delete was redundant))</para>
/// <para><i>Get</i> (<b>Required: </b> RegistryHive, Key, Value <b>Optional:</b> RegistryView <b>Output: </b>Data)</para>
/// <para><i>Set</i> (<b>Required: </b> RegistryHive, Key, Value <b>Optional:</b> DataType, RegistryView)</para>
/// <para><b>Remote Execution Support:</b> Yes</para>
/// </summary>
/// <example>
/// <code lang="xml"><![CDATA[
/// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
/// <PropertyGroup>
/// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath>
/// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath>
/// </PropertyGroup>
/// <Import Project="$(TPath)"/>
/// <Target Name="Default">
/// <!-- Create a key -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="CreateKey" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp"/>
/// <!-- Check if a key is empty -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="CheckEmpty" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp">
/// <Output PropertyName="REmpty" TaskParameter="Empty"/>
/// </MSBuild.ExtensionPack.Computer.Registry>
/// <Message Text="SOFTWARE\ANewTemp is empty: $(REmpty)"/>
/// <!-- Set a value -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="Set" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp" Value="MySetting" Data="21"/>
/// <!-- Check if the value exists -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="CheckValueExists" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp" Value="MySetting">
/// <Output PropertyName="RExists" TaskParameter="Exists"/>
/// </MSBuild.ExtensionPack.Computer.Registry>
/// <Message Text="SOFTWARE\ANewTemp\@MySetting exists: $(RExists)"/>
/// <!-- Get the value out -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="Get" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp" Value="MySetting">
/// <Output PropertyName="RData" TaskParameter="Data"/>
/// </MSBuild.ExtensionPack.Computer.Registry>
/// <Message Text="Registry Value: $(RData)"/>
/// <!-- Check if a key is empty again -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="CheckEmpty" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp">
/// <Output PropertyName="REmpty" TaskParameter="Empty"/>
/// </MSBuild.ExtensionPack.Computer.Registry>
/// <Message Text="SOFTWARE\ANewTemp is empty: $(REmpty)"/>
/// <!-- Set some Binary Data -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="Set" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp" DataType="Binary" Value="binval" Data="10, 43, 44, 45, 14, 255" />
/// <!--Get some Binary Data-->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="Get" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp" Value="binval">
/// <Output PropertyName="RData" TaskParameter="Data"/>
/// </MSBuild.ExtensionPack.Computer.Registry>
/// <Message Text="Registry Value: $(RData)"/>
/// <!-- Delete a value -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="DeleteValue" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp" Value="MySetting" />
/// <!-- Delete a key -->
/// <MSBuild.ExtensionPack.Computer.Registry TaskAction="DeleteKey" RegistryHive="LocalMachine" Key="SOFTWARE\ANewTemp"/>
/// </Target>
/// </Project>
/// ]]></code>
/// </example>
public class Registry : BaseTask
{
private const string CheckEmptyTaskAction = "CheckEmpty";
private const string CheckValueExistsTaskAction = "CheckValueExists";
private const string CreateKeyTaskAction = "CreateKey";
private const string DeleteKeyTaskAction = "DeleteKey";
private const string DeleteKeyTreeTaskAction = "DeleteKeyTree";
private const string DeleteValueTaskAction = "DeleteValue";
private const string GetTaskAction = "Get";
private const string SetTaskAction = "Set";
private RegistryKey registryKey;
private RegistryHive hive;
private RegistryView view = Microsoft.Win32.RegistryView.Default;
/// <summary>
/// Sets the type of the data. RegistryValueKind Enumeration. Support for Binary, DWord, MultiString, QWord, ExpandString
/// </summary>
public string DataType { get; set; }
/// <summary>
/// Gets the data.
/// </summary>
[Output]
public string Data { get; set; }
/// <summary>
/// Sets the value. If Value is not provided, an attempt will be made to read the Default Value.
/// </summary>
public string Value { get; set; }
/// <summary>
/// Sets the Registry Hive. Supports ClassesRoot, CurrentUser, LocalMachine, Users, PerformanceData, CurrentConfig, DynData
/// </summary>
[Required]
public string RegistryHive
{
get
{
return this.hive.ToString();
}
set
{
this.hive = (RegistryHive)Enum.Parse(typeof(RegistryHive), value);
}
}
/// <summary>
/// Sets the Registry View. Supports Registry32, Registry64 and Default. Defaults to Default
/// </summary>
public string RegistryView
{
get
{
return this.view.ToString();
}
set
{
this.view = (RegistryView)Enum.Parse(typeof(RegistryView), value);
}
}
/// <summary>
/// Sets the key.
/// </summary>
[Required]
public string Key { get; set; }
/// <summary>
/// Indicates whether the Registry Key is empty or not
/// </summary>
[Output]
public bool Empty { get; set; }
/// <summary>
/// Indicates whether the Registry value exists
/// </summary>
[Output]
public bool Exists { get; set; }
/// <summary>
/// Performs the action of this task.
/// </summary>
protected override void InternalExecute()
{
try
{
this.registryKey = RegistryKey.OpenRemoteBaseKey(this.hive, this.MachineName, this.view);
}
catch (System.ArgumentException)
{
Log.LogError(string.Format(CultureInfo.CurrentCulture, "The Registry Hive provided is not valid: {0}", this.RegistryHive));
return;
}
switch (this.TaskAction)
{
case CreateKeyTaskAction:
this.CreateKey();
break;
case DeleteKeyTaskAction:
this.DeleteKey();
break;
case DeleteKeyTreeTaskAction:
this.DeleteKeyTree();
break;
case GetTaskAction:
this.Get();
break;
case SetTaskAction:
this.Set();
break;
case CheckEmptyTaskAction:
this.CheckEmpty();
break;
case DeleteValueTaskAction:
this.DeleteValue();
break;
case CheckValueExistsTaskAction:
this.CheckValueExists();
break;
default:
Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction));
return;
}
}
private static string GetRegistryKeyValue(RegistryKey subkey, string value)
{
var v = subkey.GetValue(value);
if (v == null)
{
return null;
}
RegistryValueKind valueKind = subkey.GetValueKind(value);
if (valueKind == RegistryValueKind.Binary && v is byte[])
{
byte[] valueBytes = (byte[])v;
StringBuilder bytes = new StringBuilder(valueBytes.Length * 2);
foreach (byte b in valueBytes)
{
bytes.Append(b.ToString(CultureInfo.InvariantCulture));
bytes.Append(',');
}
return bytes.ToString(0, bytes.Length - 1);
}
if (valueKind == RegistryValueKind.MultiString && v is string[])
{
var itemList = new StringBuilder();
foreach (string item in (string[])v)
{
itemList.Append(item);
itemList.Append(',');
}
return itemList.ToString(0, itemList.Length - 1);
}
return v.ToString();
}
/// <summary>
/// Checks if a Registry Key contains values or subkeys.
/// </summary>
private void CheckEmpty()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking if Registry Key: {0} is empty in Hive: {1}, View: {2} on: {3}", this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
RegistryKey subKey = this.registryKey.OpenSubKey(this.Key, true);
if (subKey != null)
{
if (subKey.SubKeyCount <= 0)
{
this.Empty = subKey.ValueCount <= 0;
}
else
{
this.Empty = false;
}
}
else
{
Log.LogError(string.Format(CultureInfo.CurrentCulture, "Registry Key: {0} not found in Hive: {1}, View: {2} on: {3}", this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
}
}
private void Set()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Registry Value: {0} for Key: {1} in Hive: {2}, View: {3} on: {4}", this.Value, this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
bool changed = false;
RegistryKey subKey = this.registryKey.OpenSubKey(this.Key, true);
if (subKey != null)
{
string oldData = GetRegistryKeyValue(subKey, this.Value);
if (oldData == null || oldData != this.Data)
{
if (string.IsNullOrEmpty(this.DataType))
{
subKey.SetValue(this.Value, this.Data);
}
else
{
// assumption that ',' is separator for binary and multistring value types.
char[] separator = { ',' };
object registryValue;
RegistryValueKind valueKind = (Microsoft.Win32.RegistryValueKind)Enum.Parse(typeof(RegistryValueKind), this.DataType, true);
switch (valueKind)
{
case RegistryValueKind.Binary:
string[] parts = this.Data.Split(separator);
byte[] val = new byte[parts.Length];
for (int i = 0; i < parts.Length; i++)
{
val[i] = byte.Parse(parts[i], CultureInfo.CurrentCulture);
}
registryValue = val;
break;
case RegistryValueKind.DWord:
registryValue = uint.Parse(this.Data, CultureInfo.CurrentCulture);
break;
case RegistryValueKind.MultiString:
string[] parts1 = this.Data.Split(separator);
registryValue = parts1;
break;
case RegistryValueKind.QWord:
registryValue = ulong.Parse(this.Data, CultureInfo.CurrentCulture);
break;
default:
registryValue = this.Data;
break;
}
subKey.SetValue(this.Value, registryValue, valueKind);
}
changed = true;
}
subKey.Close();
}
else
{
Log.LogError(string.Format(CultureInfo.CurrentCulture, "Registry Key: {0} not found in Hive: {1}, View: {2} on: {3}", this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
}
if (changed)
{
// Broadcast config change
if (0 == NativeMethods.SendMessageTimeout(NativeMethods.HWND_BROADCAST, NativeMethods.WM_SETTINGCHANGE, 0, "Environment", NativeMethods.SMTO_ABORTIFHUNG, NativeMethods.SENDMESSAGE_TIMEOUT, 0))
{
this.LogTaskWarning("NativeMethods.SendMessageTimeout returned 0");
}
}
this.registryKey.Close();
}
private void Get()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Getting Registry value: {0} from Key: {1} in Hive: {2}, View: {3} on: {4}", this.Value, this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
RegistryKey subKey = this.registryKey.OpenSubKey(this.Key, false);
if (subKey == null)
{
Log.LogError(string.Format(CultureInfo.CurrentCulture, "The Registry Key provided is not valid: {0}", this.Key));
return;
}
if (subKey.GetValue(this.Value) == null)
{
this.LogTaskMessage(string.IsNullOrEmpty(this.Value) ? string.Format(CultureInfo.CurrentCulture, "A Default value was not found for the Registry Key: {0}", this.Key) : string.Format(CultureInfo.CurrentCulture, "The Registry value provided is not valid: {0}", this.Value));
return;
}
this.Data = GetRegistryKeyValue(subKey, this.Value);
subKey.Close();
this.registryKey.Close();
}
private void DeleteKeyTree()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting Key Tree: {0} in Hive: {1}, View: {2} on: {3}", this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
using (RegistryKey r = RegistryKey.OpenRemoteBaseKey(this.hive, this.MachineName, this.view))
{
r.DeleteSubKeyTree(this.Key);
}
}
private void DeleteKey()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting Registry Key: {0} in Hive: {1}, View: {2} on: {3}", this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
using (RegistryKey r = RegistryKey.OpenRemoteBaseKey(this.hive, this.MachineName, this.view))
{
r.DeleteSubKey(this.Key, false);
}
}
private void CreateKey()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Creating Registry Key: {0} in Hive: {1}, View: {2} on: {3}", this.Key, this.RegistryHive, this.RegistryView, this.MachineName));
using (RegistryKey r = RegistryKey.OpenRemoteBaseKey(this.hive, this.MachineName, this.view))
using (RegistryKey r2 = r.CreateSubKey(this.Key))
{
}
}
private void DeleteValue()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting Registry value: {0} from Key: {1} in Hive: {2} on: {3}", this.Value, this.Key, this.RegistryHive, this.MachineName));
RegistryKey subKey = this.registryKey.OpenSubKey(this.Key, true);
if (subKey != null)
{
var val = subKey.GetValue(this.Value);
if (val != null)
{
subKey.DeleteValue(this.Value);
}
}
}
private void CheckValueExists()
{
this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Checking if Registry Value: {0} for Key {1} exists in Hive: {2} on: {3}", this.Value, this.Key, this.RegistryHive, this.MachineName));
RegistryKey subKey = this.registryKey.OpenSubKey(this.Key, false);
this.Exists = !((subKey == null) || (subKey.GetValue(this.Value) == null));
}
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// BulkEnvelopesResponse
/// </summary>
[DataContract]
public partial class BulkEnvelopesResponse : IEquatable<BulkEnvelopesResponse>, IValidatableObject
{
public BulkEnvelopesResponse()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="BulkEnvelopesResponse" /> class.
/// </summary>
/// <param name="BulkEnvelopeStatuses">Reserved: TBD.</param>
/// <param name="EndPosition">The last position in the result set. .</param>
/// <param name="NextUri">The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. .</param>
/// <param name="PreviousUri">The postal code for the billing address..</param>
/// <param name="ResultSetSize">The number of results returned in this response. .</param>
/// <param name="StartPosition">Starting position of the current result set..</param>
/// <param name="TotalSetSize">The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response..</param>
public BulkEnvelopesResponse(List<BulkEnvelopeStatus> BulkEnvelopeStatuses = default(List<BulkEnvelopeStatus>), string EndPosition = default(string), string NextUri = default(string), string PreviousUri = default(string), string ResultSetSize = default(string), string StartPosition = default(string), string TotalSetSize = default(string))
{
this.BulkEnvelopeStatuses = BulkEnvelopeStatuses;
this.EndPosition = EndPosition;
this.NextUri = NextUri;
this.PreviousUri = PreviousUri;
this.ResultSetSize = ResultSetSize;
this.StartPosition = StartPosition;
this.TotalSetSize = TotalSetSize;
}
/// <summary>
/// Reserved: TBD
/// </summary>
/// <value>Reserved: TBD</value>
[DataMember(Name="bulkEnvelopeStatuses", EmitDefaultValue=false)]
public List<BulkEnvelopeStatus> BulkEnvelopeStatuses { get; set; }
/// <summary>
/// The last position in the result set.
/// </summary>
/// <value>The last position in the result set. </value>
[DataMember(Name="endPosition", EmitDefaultValue=false)]
public string EndPosition { get; set; }
/// <summary>
/// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.
/// </summary>
/// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. </value>
[DataMember(Name="nextUri", EmitDefaultValue=false)]
public string NextUri { get; set; }
/// <summary>
/// The postal code for the billing address.
/// </summary>
/// <value>The postal code for the billing address.</value>
[DataMember(Name="previousUri", EmitDefaultValue=false)]
public string PreviousUri { get; set; }
/// <summary>
/// The number of results returned in this response.
/// </summary>
/// <value>The number of results returned in this response. </value>
[DataMember(Name="resultSetSize", EmitDefaultValue=false)]
public string ResultSetSize { get; set; }
/// <summary>
/// Starting position of the current result set.
/// </summary>
/// <value>Starting position of the current result set.</value>
[DataMember(Name="startPosition", EmitDefaultValue=false)]
public string StartPosition { get; set; }
/// <summary>
/// The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.
/// </summary>
/// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.</value>
[DataMember(Name="totalSetSize", EmitDefaultValue=false)]
public string TotalSetSize { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class BulkEnvelopesResponse {\n");
sb.Append(" BulkEnvelopeStatuses: ").Append(BulkEnvelopeStatuses).Append("\n");
sb.Append(" EndPosition: ").Append(EndPosition).Append("\n");
sb.Append(" NextUri: ").Append(NextUri).Append("\n");
sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n");
sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n");
sb.Append(" StartPosition: ").Append(StartPosition).Append("\n");
sb.Append(" TotalSetSize: ").Append(TotalSetSize).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as BulkEnvelopesResponse);
}
/// <summary>
/// Returns true if BulkEnvelopesResponse instances are equal
/// </summary>
/// <param name="other">Instance of BulkEnvelopesResponse to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BulkEnvelopesResponse other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.BulkEnvelopeStatuses == other.BulkEnvelopeStatuses ||
this.BulkEnvelopeStatuses != null &&
this.BulkEnvelopeStatuses.SequenceEqual(other.BulkEnvelopeStatuses)
) &&
(
this.EndPosition == other.EndPosition ||
this.EndPosition != null &&
this.EndPosition.Equals(other.EndPosition)
) &&
(
this.NextUri == other.NextUri ||
this.NextUri != null &&
this.NextUri.Equals(other.NextUri)
) &&
(
this.PreviousUri == other.PreviousUri ||
this.PreviousUri != null &&
this.PreviousUri.Equals(other.PreviousUri)
) &&
(
this.ResultSetSize == other.ResultSetSize ||
this.ResultSetSize != null &&
this.ResultSetSize.Equals(other.ResultSetSize)
) &&
(
this.StartPosition == other.StartPosition ||
this.StartPosition != null &&
this.StartPosition.Equals(other.StartPosition)
) &&
(
this.TotalSetSize == other.TotalSetSize ||
this.TotalSetSize != null &&
this.TotalSetSize.Equals(other.TotalSetSize)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.BulkEnvelopeStatuses != null)
hash = hash * 59 + this.BulkEnvelopeStatuses.GetHashCode();
if (this.EndPosition != null)
hash = hash * 59 + this.EndPosition.GetHashCode();
if (this.NextUri != null)
hash = hash * 59 + this.NextUri.GetHashCode();
if (this.PreviousUri != null)
hash = hash * 59 + this.PreviousUri.GetHashCode();
if (this.ResultSetSize != null)
hash = hash * 59 + this.ResultSetSize.GetHashCode();
if (this.StartPosition != null)
hash = hash * 59 + this.StartPosition.GetHashCode();
if (this.TotalSetSize != null)
hash = hash * 59 + this.TotalSetSize.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
using System;
using System.Text;
using System.Collections.Generic;
namespace Google.GData.Client {
/// <summary>
/// Stores the parameters used to make OAuth requests
/// </summary>
public class OAuthParameters {
public readonly SortedDictionary<string, string> BaseProperties = new SortedDictionary<string, string>();
public readonly Dictionary<string, string> ExtraProperties = new Dictionary<string, string>();
public string Callback {
get {
return safeGet(ExtraProperties, OAuthBase.OAuthCallbackKey);
}
set {
addOrUpdate(ExtraProperties, OAuthBase.OAuthCallbackKey, value);
}
}
public string ConsumerKey {
get {
return safeGet(BaseProperties, OAuthBase.OAuthConsumerKeyKey);
}
set {
addOrUpdate(BaseProperties, OAuthBase.OAuthConsumerKeyKey, value);
}
}
public string ConsumerSecret {
get {
return safeGet(ExtraProperties, OAuthBase.OAuthConsumerSecretKey);
}
set {
addOrUpdate(ExtraProperties, OAuthBase.OAuthConsumerSecretKey, value);
}
}
public string Nonce {
get {
return safeGet(BaseProperties, OAuthBase.OAuthNonceKey);
}
set {
addOrUpdate(BaseProperties, OAuthBase.OAuthNonceKey, value);
}
}
public string Scope {
get {
return safeGet(ExtraProperties, OAuthBase.OAuthScopeKey);
}
set {
addOrUpdate(ExtraProperties, OAuthBase.OAuthScopeKey, value);
}
}
public string Signature {
get {
return safeGet(ExtraProperties, OAuthBase.OAuthSignatureKey);
}
set {
addOrUpdate(ExtraProperties, OAuthBase.OAuthSignatureKey, value);
}
}
public string SignatureMethod {
get {
return safeGet(BaseProperties, OAuthBase.OAuthSignatureMethodKey);
}
set {
addOrUpdate(BaseProperties, OAuthBase.OAuthSignatureMethodKey, value);
}
}
public string Timestamp {
get {
return safeGet(BaseProperties, OAuthBase.OAuthTimestampKey);
}
set {
addOrUpdate(BaseProperties, OAuthBase.OAuthTimestampKey, value);
}
}
public string Token {
get {
return safeGet(BaseProperties, OAuthBase.OAuthTokenKey);
}
set {
addOrUpdate(BaseProperties, OAuthBase.OAuthTokenKey, value);
}
}
public string TokenSecret {
get {
return safeGet(ExtraProperties, OAuthBase.OAuthTokenSecretKey);
}
set {
addOrUpdate(ExtraProperties, OAuthBase.OAuthTokenSecretKey, value);
}
}
public string Verifier {
get {
return safeGet(BaseProperties, OAuthBase.OAuthVerifierKey);
}
set {
addOrUpdate(BaseProperties, OAuthBase.OAuthVerifierKey, value);
}
}
/// <summary>
/// Adds a new key-value pair to the dictionary or updates the value if the key is already present
/// </summary>
protected void addOrUpdate(IDictionary<string, string> dictionary, string key, string value) {
if (dictionary.ContainsKey(key)) {
if (value == null) {
dictionary.Remove(key);
} else {
dictionary[key] = value;
}
} else if (value != null) {
dictionary.Add(key, value);
}
}
/// <summary>
/// Returns the value corresponding to the key in the dictionary or null if the key is not present
/// </summary>
protected string safeGet(IDictionary<string, string> dictionary, string key) {
if (dictionary.ContainsKey(key)) {
return dictionary[key];
} else {
return null;
}
}
}
/// <summary>
/// Stores the parameters used to make OAuth 2.0 requests
/// </summary>
public class OAuth2Parameters {
public static string GoogleAuthUri = "https://accounts.google.com/o/oauth2/auth";
public static string GoogleTokenUri = "https://accounts.google.com/o/oauth2/token";
public OAuth2Parameters() {
TokenUri = GoogleTokenUri;
AuthUri = GoogleAuthUri;
AccessType = "offline";
ResponseType = "code";
TokenType = "Bearer";
ApprovalPrompt = "auto";
}
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string RedirectUri { get; set; }
/// <summary>
/// Valid values are:
/// * "offline" (default): token endpoint returns both an access and refresh token.
/// * "online": only an access token is returned by the token endpoint.
/// </summary>
public string AccessType { get; set; }
/// <summary>
/// Valid values are:
/// * "code" (default): retrieve a code to be exchanged for an acces token.
/// * "token": directly retrieve an access token from the auth endpoint.
/// </summary>
public string ResponseType { get; set; }
/// <summary>
/// Valid values are:
/// * "auto" (default): only show the approval prompt if the user never approved.
/// * "force": always show the approval prompt.
/// </summary>
public String ApprovalPrompt { get; set; }
public String State { get; set; }
public String Scope { get; set; }
public string TokenUri { get; set; }
public string AuthUri { get; set; }
public string AccessCode { get; set; }
public string AccessToken { get; set; }
public string TokenType { get; set; }
public string RefreshToken { get; set; }
public DateTime TokenExpiry { get; set; }
}
}
| |
namespace WindowsApplication1
{
partial class frmBlackJackSim
{
/// <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(frmBlackJackSim));
this.cmdDeal = new System.Windows.Forms.Button();
this.rtbHandOutcome = new System.Windows.Forms.RichTextBox();
this.label1 = new System.Windows.Forms.Label();
this.lblDealerWins = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.lblPlayerWins = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.lblPushes = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.lblShoes = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.lblPlayerBankroll = new System.Windows.Forms.Label();
this.Label12 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.txtHandsToSim = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.label10 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.rbFalse = new System.Windows.Forms.RadioButton();
this.rbTrue = new System.Windows.Forms.RadioButton();
this.label11 = new System.Windows.Forms.Label();
this.lblSplits = new System.Windows.Forms.Label();
this.lblTotalRounds = new System.Windows.Forms.Label();
this.lblTotalHands = new System.Windows.Forms.Label();
this.label17 = new System.Windows.Forms.Label();
this.lblPlayerBlackjacks = new System.Windows.Forms.Label();
this.label21 = new System.Windows.Forms.Label();
this.lblWinningDoubles = new System.Windows.Forms.Label();
this.label22 = new System.Windows.Forms.Label();
this.lblLosingDoubles = new System.Windows.Forms.Label();
this.label23 = new System.Windows.Forms.Label();
this.lblPushingDoubles = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.checkBox2 = new System.Windows.Forms.CheckBox();
this.label7 = new System.Windows.Forms.Label();
this.checkBox3 = new System.Windows.Forms.CheckBox();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.cmdDetails = new System.Windows.Forms.Button();
this.txtTableMax = new System.Windows.Forms.TextBox();
this.txtTableMin = new System.Windows.Forms.TextBox();
this.label35 = new System.Windows.Forms.Label();
this.label34 = new System.Windows.Forms.Label();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.rbCountFalse = new System.Windows.Forms.RadioButton();
this.rbCountTrue = new System.Windows.Forms.RadioButton();
this.chkGUIUpdate = new System.Windows.Forms.CheckBox();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.label41 = new System.Windows.Forms.Label();
this.lblHouseAdvantage = new System.Windows.Forms.Label();
this.label28 = new System.Windows.Forms.Label();
this.lblPlayerCostWin = new System.Windows.Forms.Label();
this.lblDealerCostWin = new System.Windows.Forms.Label();
this.label20 = new System.Windows.Forms.Label();
this.label18 = new System.Windows.Forms.Label();
this.lblDealerWinTotal = new System.Windows.Forms.Label();
this.label26 = new System.Windows.Forms.Label();
this.lblDealerStraightWin = new System.Windows.Forms.Label();
this.lblDealerWinOnDouble = new System.Windows.Forms.Label();
this.label24 = new System.Windows.Forms.Label();
this.label25 = new System.Windows.Forms.Label();
this.lblPlayerStraightWin = new System.Windows.Forms.Label();
this.label16 = new System.Windows.Forms.Label();
this.lblUnweightedAdv = new System.Windows.Forms.Label();
this.label19 = new System.Windows.Forms.Label();
this.lblWinOnBJ = new System.Windows.Forms.Label();
this.lblWinOnDouble = new System.Windows.Forms.Label();
this.lblNonPushingTotal = new System.Windows.Forms.Label();
this.label15 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label();
this.lblPlayerWinTotal = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.groupBox6 = new System.Windows.Forms.GroupBox();
this.lblInsuranceBetsLost = new System.Windows.Forms.Label();
this.lblInsuranceBetsWon = new System.Windows.Forms.Label();
this.label43 = new System.Windows.Forms.Label();
this.label42 = new System.Windows.Forms.Label();
this.lblTCAdjustment = new System.Windows.Forms.Label();
this.label40 = new System.Windows.Forms.Label();
this.label39 = new System.Windows.Forms.Label();
this.label38 = new System.Windows.Forms.Label();
this.label37 = new System.Windows.Forms.Label();
this.lblBettingUnit = new System.Windows.Forms.Label();
this.label36 = new System.Windows.Forms.Label();
this.tbAgression = new System.Windows.Forms.TrackBar();
this.label33 = new System.Windows.Forms.Label();
this.txtStartingBankRoll = new System.Windows.Forms.TextBox();
this.lblHighestBankroll = new System.Windows.Forms.Label();
this.lblHighestBet = new System.Windows.Forms.Label();
this.lblLowestBankroll = new System.Windows.Forms.Label();
this.lblLowestCount = new System.Windows.Forms.Label();
this.lblHighestCount = new System.Windows.Forms.Label();
this.label32 = new System.Windows.Forms.Label();
this.label31 = new System.Windows.Forms.Label();
this.label30 = new System.Windows.Forms.Label();
this.label29 = new System.Windows.Forms.Label();
this.label27 = new System.Windows.Forms.Label();
this.groupBox7 = new System.Windows.Forms.GroupBox();
this.lblErrors = new System.Windows.Forms.Label();
this.label52 = new System.Windows.Forms.Label();
this.gbError = new System.Windows.Forms.GroupBox();
this.lblErrorsPer100Hands = new System.Windows.Forms.Label();
this.label50 = new System.Windows.Forms.Label();
this.label49 = new System.Windows.Forms.Label();
this.label48 = new System.Windows.Forms.Label();
this.label46 = new System.Windows.Forms.Label();
this.label47 = new System.Windows.Forms.Label();
this.label45 = new System.Windows.Forms.Label();
this.label44 = new System.Windows.Forms.Label();
this.tbErrorRate = new System.Windows.Forms.TrackBar();
this.groupBox8 = new System.Windows.Forms.GroupBox();
this.rbErrorsOff = new System.Windows.Forms.RadioButton();
this.rbErrorsOn = new System.Windows.Forms.RadioButton();
this.cmdMultiSim = new System.Windows.Forms.Button();
this.numericUpDown1 = new System.Windows.Forms.NumericUpDown();
this.label51 = new System.Windows.Forms.Label();
this.txtPath = new System.Windows.Forms.TextBox();
this.groupBox9 = new System.Windows.Forms.GroupBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.groupBox5.SuspendLayout();
this.groupBox4.SuspendLayout();
this.groupBox6.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.tbAgression)).BeginInit();
this.groupBox7.SuspendLayout();
this.gbError.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.tbErrorRate)).BeginInit();
this.groupBox8.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
this.groupBox9.SuspendLayout();
this.SuspendLayout();
//
// cmdDeal
//
this.cmdDeal.BackColor = System.Drawing.SystemColors.Control;
this.cmdDeal.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("cmdDeal.BackgroundImage")));
this.cmdDeal.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmdDeal.Location = new System.Drawing.Point(277, 288);
this.cmdDeal.Name = "cmdDeal";
this.cmdDeal.Size = new System.Drawing.Size(277, 45);
this.cmdDeal.TabIndex = 2;
this.cmdDeal.Text = "START ONE SIM";
this.cmdDeal.UseVisualStyleBackColor = false;
this.cmdDeal.Click += new System.EventHandler(this.cmdDeal_Click);
//
// rtbHandOutcome
//
this.rtbHandOutcome.Location = new System.Drawing.Point(277, 526);
this.rtbHandOutcome.Name = "rtbHandOutcome";
this.rtbHandOutcome.Size = new System.Drawing.Size(277, 48);
this.rtbHandOutcome.TabIndex = 3;
this.rtbHandOutcome.Text = "";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(6, 23);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(68, 13);
this.label1.TabIndex = 5;
this.label1.Text = "Dealer Wins:";
//
// lblDealerWins
//
this.lblDealerWins.AutoSize = true;
this.lblDealerWins.Location = new System.Drawing.Point(99, 23);
this.lblDealerWins.Name = "lblDealerWins";
this.lblDealerWins.Size = new System.Drawing.Size(13, 13);
this.lblDealerWins.TabIndex = 6;
this.lblDealerWins.Text = "0";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 36);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(66, 13);
this.label2.TabIndex = 7;
this.label2.Text = "Player Wins:";
//
// lblPlayerWins
//
this.lblPlayerWins.AutoSize = true;
this.lblPlayerWins.Location = new System.Drawing.Point(99, 36);
this.lblPlayerWins.Name = "lblPlayerWins";
this.lblPlayerWins.Size = new System.Drawing.Size(13, 13);
this.lblPlayerWins.TabIndex = 8;
this.lblPlayerWins.Text = "0";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 49);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(45, 13);
this.label3.TabIndex = 9;
this.label3.Text = "Pushes:";
//
// lblPushes
//
this.lblPushes.AutoSize = true;
this.lblPushes.Location = new System.Drawing.Point(99, 49);
this.lblPushes.Name = "lblPushes";
this.lblPushes.Size = new System.Drawing.Size(13, 13);
this.lblPushes.TabIndex = 10;
this.lblPushes.Text = "0";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(6, 138);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(106, 13);
this.label4.TabIndex = 11;
this.label4.Text = "8-Deck Shoes Used:";
//
// lblShoes
//
this.lblShoes.AutoSize = true;
this.lblShoes.Location = new System.Drawing.Point(133, 138);
this.lblShoes.Name = "lblShoes";
this.lblShoes.Size = new System.Drawing.Size(13, 13);
this.lblShoes.TabIndex = 12;
this.lblShoes.Text = "0";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.Location = new System.Drawing.Point(4, 200);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(145, 24);
this.label6.TabIndex = 15;
this.label6.Text = "Player Net Gain:";
//
// lblPlayerBankroll
//
this.lblPlayerBankroll.AutoSize = true;
this.lblPlayerBankroll.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblPlayerBankroll.ForeColor = System.Drawing.Color.Blue;
this.lblPlayerBankroll.Location = new System.Drawing.Point(142, 200);
this.lblPlayerBankroll.Name = "lblPlayerBankroll";
this.lblPlayerBankroll.Size = new System.Drawing.Size(21, 24);
this.lblPlayerBankroll.TabIndex = 17;
this.lblPlayerBankroll.Text = "0";
//
// Label12
//
this.Label12.AutoSize = true;
this.Label12.Location = new System.Drawing.Point(6, 162);
this.Label12.Name = "Label12";
this.Label12.Size = new System.Drawing.Size(112, 13);
this.Label12.TabIndex = 19;
this.Label12.Text = "Total Rounds Played: ";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(6, 62);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(35, 13);
this.label8.TabIndex = 20;
this.label8.Text = "Splits:";
//
// txtHandsToSim
//
this.txtHandsToSim.Location = new System.Drawing.Point(171, 25);
this.txtHandsToSim.Name = "txtHandsToSim";
this.txtHandsToSim.Size = new System.Drawing.Size(88, 20);
this.txtHandsToSim.TabIndex = 21;
this.txtHandsToSim.Text = "1000000";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(17, 28);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(148, 13);
this.label9.TabIndex = 22;
this.label9.Text = "Number of Hands to Simulate:";
//
// progressBar1
//
this.progressBar1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.progressBar1.ForeColor = System.Drawing.Color.Yellow;
this.progressBar1.Location = new System.Drawing.Point(0, 590);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(873, 23);
this.progressBar1.TabIndex = 23;
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(277, 510);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(155, 13);
this.label10.TabIndex = 24;
this.label10.Text = "First 10 Hands (For Reference):";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.rbFalse);
this.groupBox1.Controls.Add(this.rbTrue);
this.groupBox1.Location = new System.Drawing.Point(152, 151);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(118, 60);
this.groupBox1.TabIndex = 25;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Dealer Hits Soft 17";
//
// rbFalse
//
this.rbFalse.AutoSize = true;
this.rbFalse.Checked = true;
this.rbFalse.Location = new System.Drawing.Point(32, 36);
this.rbFalse.Name = "rbFalse";
this.rbFalse.Size = new System.Drawing.Size(58, 17);
this.rbFalse.TabIndex = 1;
this.rbFalse.TabStop = true;
this.rbFalse.Text = "FALSE";
this.rbFalse.UseVisualStyleBackColor = true;
this.rbFalse.CheckedChanged += new System.EventHandler(this.rbFalse_CheckedChanged);
//
// rbTrue
//
this.rbTrue.AutoSize = true;
this.rbTrue.Location = new System.Drawing.Point(32, 18);
this.rbTrue.Name = "rbTrue";
this.rbTrue.Size = new System.Drawing.Size(55, 17);
this.rbTrue.TabIndex = 0;
this.rbTrue.Text = "TRUE";
this.rbTrue.UseVisualStyleBackColor = true;
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(6, 175);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(103, 13);
this.label11.TabIndex = 26;
this.label11.Text = "Total Hands Played:";
//
// lblSplits
//
this.lblSplits.AutoSize = true;
this.lblSplits.Location = new System.Drawing.Point(99, 62);
this.lblSplits.Name = "lblSplits";
this.lblSplits.Size = new System.Drawing.Size(13, 13);
this.lblSplits.TabIndex = 27;
this.lblSplits.Text = "0";
//
// lblTotalRounds
//
this.lblTotalRounds.AutoSize = true;
this.lblTotalRounds.Location = new System.Drawing.Point(133, 162);
this.lblTotalRounds.Name = "lblTotalRounds";
this.lblTotalRounds.Size = new System.Drawing.Size(13, 13);
this.lblTotalRounds.TabIndex = 28;
this.lblTotalRounds.Text = "0";
//
// lblTotalHands
//
this.lblTotalHands.AutoSize = true;
this.lblTotalHands.Location = new System.Drawing.Point(133, 175);
this.lblTotalHands.Name = "lblTotalHands";
this.lblTotalHands.Size = new System.Drawing.Size(13, 13);
this.lblTotalHands.TabIndex = 29;
this.lblTotalHands.Text = "0";
//
// label17
//
this.label17.AutoSize = true;
this.label17.Location = new System.Drawing.Point(6, 75);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(94, 13);
this.label17.TabIndex = 36;
this.label17.Text = "Player Blackjacks:";
//
// lblPlayerBlackjacks
//
this.lblPlayerBlackjacks.AutoSize = true;
this.lblPlayerBlackjacks.Location = new System.Drawing.Point(99, 75);
this.lblPlayerBlackjacks.Name = "lblPlayerBlackjacks";
this.lblPlayerBlackjacks.Size = new System.Drawing.Size(13, 13);
this.lblPlayerBlackjacks.TabIndex = 37;
this.lblPlayerBlackjacks.Text = "0";
//
// label21
//
this.label21.AutoSize = true;
this.label21.Location = new System.Drawing.Point(6, 89);
this.label21.Name = "label21";
this.label21.Size = new System.Drawing.Size(85, 13);
this.label21.TabIndex = 45;
this.label21.Text = "Wining Doubles:";
//
// lblWinningDoubles
//
this.lblWinningDoubles.AutoSize = true;
this.lblWinningDoubles.Location = new System.Drawing.Point(99, 89);
this.lblWinningDoubles.Name = "lblWinningDoubles";
this.lblWinningDoubles.Size = new System.Drawing.Size(13, 13);
this.lblWinningDoubles.TabIndex = 46;
this.lblWinningDoubles.Text = "0";
//
// label22
//
this.label22.AutoSize = true;
this.label22.Location = new System.Drawing.Point(6, 102);
this.label22.Name = "label22";
this.label22.Size = new System.Drawing.Size(83, 13);
this.label22.TabIndex = 47;
this.label22.Text = "Losing Doubles:";
//
// lblLosingDoubles
//
this.lblLosingDoubles.AutoSize = true;
this.lblLosingDoubles.Location = new System.Drawing.Point(99, 102);
this.lblLosingDoubles.Name = "lblLosingDoubles";
this.lblLosingDoubles.Size = new System.Drawing.Size(13, 13);
this.lblLosingDoubles.TabIndex = 48;
this.lblLosingDoubles.Text = "0";
//
// label23
//
this.label23.AutoSize = true;
this.label23.Location = new System.Drawing.Point(6, 115);
this.label23.Name = "label23";
this.label23.Size = new System.Drawing.Size(90, 13);
this.label23.TabIndex = 49;
this.label23.Text = "Pushing Doubles:";
//
// lblPushingDoubles
//
this.lblPushingDoubles.AutoSize = true;
this.lblPushingDoubles.Location = new System.Drawing.Point(99, 115);
this.lblPushingDoubles.Name = "lblPushingDoubles";
this.lblPushingDoubles.Size = new System.Drawing.Size(13, 13);
this.lblPushingDoubles.TabIndex = 50;
this.lblPushingDoubles.Text = "0";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.lblPushingDoubles);
this.groupBox2.Controls.Add(this.label23);
this.groupBox2.Controls.Add(this.lblLosingDoubles);
this.groupBox2.Controls.Add(this.label22);
this.groupBox2.Controls.Add(this.lblWinningDoubles);
this.groupBox2.Controls.Add(this.label21);
this.groupBox2.Controls.Add(this.lblPlayerBlackjacks);
this.groupBox2.Controls.Add(this.label17);
this.groupBox2.Controls.Add(this.lblTotalHands);
this.groupBox2.Controls.Add(this.lblTotalRounds);
this.groupBox2.Controls.Add(this.lblSplits);
this.groupBox2.Controls.Add(this.label11);
this.groupBox2.Controls.Add(this.label8);
this.groupBox2.Controls.Add(this.Label12);
this.groupBox2.Controls.Add(this.lblPlayerBankroll);
this.groupBox2.Controls.Add(this.label6);
this.groupBox2.Controls.Add(this.lblShoes);
this.groupBox2.Controls.Add(this.label4);
this.groupBox2.Controls.Add(this.lblPushes);
this.groupBox2.Controls.Add(this.label3);
this.groupBox2.Controls.Add(this.lblPlayerWins);
this.groupBox2.Controls.Add(this.label2);
this.groupBox2.Controls.Add(this.lblDealerWins);
this.groupBox2.Controls.Add(this.label1);
this.groupBox2.Location = new System.Drawing.Point(6, 3);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(266, 240);
this.groupBox2.TabIndex = 52;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "STATS";
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Checked = true;
this.checkBox1.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBox1.Enabled = false;
this.checkBox1.Location = new System.Drawing.Point(15, 194);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(108, 17);
this.checkBox1.TabIndex = 53;
this.checkBox1.Text = "Double After Split";
this.checkBox1.UseVisualStyleBackColor = true;
//
// checkBox2
//
this.checkBox2.AutoSize = true;
this.checkBox2.Checked = true;
this.checkBox2.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBox2.Enabled = false;
this.checkBox2.Location = new System.Drawing.Point(15, 148);
this.checkBox2.Name = "checkBox2";
this.checkBox2.Size = new System.Drawing.Size(120, 17);
this.checkBox2.TabIndex = 54;
this.checkBox2.Text = "BlackJack Pays 2:1";
this.checkBox2.UseVisualStyleBackColor = true;
//
// label7
//
this.label7.AutoSize = true;
this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label7.Location = new System.Drawing.Point(90, 109);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(113, 13);
this.label7.TabIndex = 56;
this.label7.Text = "Basic Betting Unit:";
//
// checkBox3
//
this.checkBox3.AutoSize = true;
this.checkBox3.Checked = true;
this.checkBox3.CheckState = System.Windows.Forms.CheckState.Checked;
this.checkBox3.Enabled = false;
this.checkBox3.Location = new System.Drawing.Point(15, 171);
this.checkBox3.Name = "checkBox3";
this.checkBox3.Size = new System.Drawing.Size(83, 17);
this.checkBox3.TabIndex = 57;
this.checkBox3.Text = "No Re-splits";
this.checkBox3.UseVisualStyleBackColor = true;
//
// groupBox3
//
this.groupBox3.Controls.Add(this.txtTableMax);
this.groupBox3.Controls.Add(this.txtTableMin);
this.groupBox3.Controls.Add(this.label35);
this.groupBox3.Controls.Add(this.label34);
this.groupBox3.Controls.Add(this.groupBox5);
this.groupBox3.Controls.Add(this.checkBox3);
this.groupBox3.Controls.Add(this.checkBox2);
this.groupBox3.Controls.Add(this.checkBox1);
this.groupBox3.Controls.Add(this.chkGUIUpdate);
this.groupBox3.Controls.Add(this.groupBox1);
this.groupBox3.Controls.Add(this.label9);
this.groupBox3.Controls.Add(this.txtHandsToSim);
this.groupBox3.Location = new System.Drawing.Point(278, 3);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(276, 280);
this.groupBox3.TabIndex = 58;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "OPTIONS";
//
// cmdDetails
//
this.cmdDetails.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("cmdDetails.BackgroundImage")));
this.cmdDetails.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmdDetails.Location = new System.Drawing.Point(359, 450);
this.cmdDetails.Name = "cmdDetails";
this.cmdDetails.Size = new System.Drawing.Size(135, 46);
this.cmdDetails.TabIndex = 62;
this.cmdDetails.Text = "Show/Hide Detals";
this.cmdDetails.UseVisualStyleBackColor = true;
this.cmdDetails.Click += new System.EventHandler(this.cmdDetails_Click);
//
// txtTableMax
//
this.txtTableMax.Location = new System.Drawing.Point(171, 73);
this.txtTableMax.Name = "txtTableMax";
this.txtTableMax.Size = new System.Drawing.Size(88, 20);
this.txtTableMax.TabIndex = 62;
this.txtTableMax.Text = "5000";
//
// txtTableMin
//
this.txtTableMin.Location = new System.Drawing.Point(171, 49);
this.txtTableMin.Name = "txtTableMin";
this.txtTableMin.Size = new System.Drawing.Size(88, 20);
this.txtTableMin.TabIndex = 61;
this.txtTableMin.Text = "10";
//
// label35
//
this.label35.AutoSize = true;
this.label35.Location = new System.Drawing.Point(78, 76);
this.label35.Name = "label35";
this.label35.Size = new System.Drawing.Size(84, 13);
this.label35.TabIndex = 60;
this.label35.Text = "Table Maximum:";
//
// label34
//
this.label34.AutoSize = true;
this.label34.Location = new System.Drawing.Point(78, 52);
this.label34.Name = "label34";
this.label34.Size = new System.Drawing.Size(81, 13);
this.label34.TabIndex = 59;
this.label34.Text = "Table Minimum:";
//
// groupBox5
//
this.groupBox5.Controls.Add(this.rbCountFalse);
this.groupBox5.Controls.Add(this.rbCountTrue);
this.groupBox5.Location = new System.Drawing.Point(15, 220);
this.groupBox5.Name = "groupBox5";
this.groupBox5.Size = new System.Drawing.Size(255, 53);
this.groupBox5.TabIndex = 58;
this.groupBox5.TabStop = false;
this.groupBox5.Text = "Player Counts Cards";
//
// rbCountFalse
//
this.rbCountFalse.AutoSize = true;
this.rbCountFalse.Location = new System.Drawing.Point(144, 23);
this.rbCountFalse.Name = "rbCountFalse";
this.rbCountFalse.Size = new System.Drawing.Size(58, 17);
this.rbCountFalse.TabIndex = 1;
this.rbCountFalse.Text = "FALSE";
this.rbCountFalse.UseVisualStyleBackColor = true;
this.rbCountFalse.CheckedChanged += new System.EventHandler(this.rbCountFalse_CheckedChanged);
//
// rbCountTrue
//
this.rbCountTrue.AutoSize = true;
this.rbCountTrue.Checked = true;
this.rbCountTrue.Location = new System.Drawing.Point(66, 23);
this.rbCountTrue.Name = "rbCountTrue";
this.rbCountTrue.Size = new System.Drawing.Size(55, 17);
this.rbCountTrue.TabIndex = 0;
this.rbCountTrue.TabStop = true;
this.rbCountTrue.Text = "TRUE";
this.rbCountTrue.UseVisualStyleBackColor = true;
//
// chkGUIUpdate
//
this.chkGUIUpdate.AutoSize = true;
this.chkGUIUpdate.Location = new System.Drawing.Point(66, 115);
this.chkGUIUpdate.Name = "chkGUIUpdate";
this.chkGUIUpdate.Size = new System.Drawing.Size(151, 17);
this.chkGUIUpdate.TabIndex = 51;
this.chkGUIUpdate.Text = "GUI Updates Continuously";
this.chkGUIUpdate.UseVisualStyleBackColor = true;
//
// groupBox4
//
this.groupBox4.Controls.Add(this.label41);
this.groupBox4.Controls.Add(this.lblHouseAdvantage);
this.groupBox4.Controls.Add(this.label28);
this.groupBox4.Controls.Add(this.lblPlayerCostWin);
this.groupBox4.Controls.Add(this.lblDealerCostWin);
this.groupBox4.Controls.Add(this.label20);
this.groupBox4.Controls.Add(this.label18);
this.groupBox4.Controls.Add(this.lblDealerWinTotal);
this.groupBox4.Controls.Add(this.label26);
this.groupBox4.Controls.Add(this.lblDealerStraightWin);
this.groupBox4.Controls.Add(this.lblDealerWinOnDouble);
this.groupBox4.Controls.Add(this.label24);
this.groupBox4.Controls.Add(this.label25);
this.groupBox4.Controls.Add(this.lblPlayerStraightWin);
this.groupBox4.Controls.Add(this.label16);
this.groupBox4.Controls.Add(this.lblUnweightedAdv);
this.groupBox4.Controls.Add(this.label19);
this.groupBox4.Controls.Add(this.lblWinOnBJ);
this.groupBox4.Controls.Add(this.lblWinOnDouble);
this.groupBox4.Controls.Add(this.lblNonPushingTotal);
this.groupBox4.Controls.Add(this.label15);
this.groupBox4.Controls.Add(this.label14);
this.groupBox4.Controls.Add(this.label13);
this.groupBox4.Controls.Add(this.lblPlayerWinTotal);
this.groupBox4.Controls.Add(this.label5);
this.groupBox4.Location = new System.Drawing.Point(6, 249);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(265, 326);
this.groupBox4.TabIndex = 59;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "HOUSE ADVANTAGE";
//
// label41
//
this.label41.AutoSize = true;
this.label41.Location = new System.Drawing.Point(24, 270);
this.label41.Name = "label41";
this.label41.Size = new System.Drawing.Size(183, 13);
this.label41.TabIndex = 68;
this.label41.Text = "[Playing Basic Strategy, No Counting]";
//
// lblHouseAdvantage
//
this.lblHouseAdvantage.AutoSize = true;
this.lblHouseAdvantage.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblHouseAdvantage.ForeColor = System.Drawing.Color.Blue;
this.lblHouseAdvantage.Location = new System.Drawing.Point(166, 246);
this.lblHouseAdvantage.Name = "lblHouseAdvantage";
this.lblHouseAdvantage.Size = new System.Drawing.Size(21, 24);
this.lblHouseAdvantage.TabIndex = 67;
this.lblHouseAdvantage.Text = "0";
//
// label28
//
this.label28.AutoSize = true;
this.label28.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label28.Location = new System.Drawing.Point(7, 246);
this.label28.Name = "label28";
this.label28.Size = new System.Drawing.Size(166, 24);
this.label28.TabIndex = 66;
this.label28.Text = "House Advantage:";
//
// lblPlayerCostWin
//
this.lblPlayerCostWin.AutoSize = true;
this.lblPlayerCostWin.Location = new System.Drawing.Point(167, 112);
this.lblPlayerCostWin.Name = "lblPlayerCostWin";
this.lblPlayerCostWin.Size = new System.Drawing.Size(13, 13);
this.lblPlayerCostWin.TabIndex = 64;
this.lblPlayerCostWin.Text = "0";
//
// lblDealerCostWin
//
this.lblDealerCostWin.AutoSize = true;
this.lblDealerCostWin.Location = new System.Drawing.Point(167, 187);
this.lblDealerCostWin.Name = "lblDealerCostWin";
this.lblDealerCostWin.Size = new System.Drawing.Size(13, 13);
this.lblDealerCostWin.TabIndex = 63;
this.lblDealerCostWin.Text = "0";
//
// label20
//
this.label20.AutoSize = true;
this.label20.Location = new System.Drawing.Point(7, 187);
this.label20.Name = "label20";
this.label20.Size = new System.Drawing.Size(146, 13);
this.label20.TabIndex = 62;
this.label20.Text = "P (Cost Weigted Dealer Win):";
//
// label18
//
this.label18.AutoSize = true;
this.label18.Location = new System.Drawing.Point(7, 112);
this.label18.Name = "label18";
this.label18.Size = new System.Drawing.Size(144, 13);
this.label18.TabIndex = 61;
this.label18.Text = "P (Cost Weigted Player Win):";
//
// lblDealerWinTotal
//
this.lblDealerWinTotal.AutoSize = true;
this.lblDealerWinTotal.Location = new System.Drawing.Point(167, 174);
this.lblDealerWinTotal.Name = "lblDealerWinTotal";
this.lblDealerWinTotal.Size = new System.Drawing.Size(13, 13);
this.lblDealerWinTotal.TabIndex = 60;
this.lblDealerWinTotal.Text = "0";
//
// label26
//
this.label26.AutoSize = true;
this.label26.Location = new System.Drawing.Point(7, 174);
this.label26.Name = "label26";
this.label26.Size = new System.Drawing.Size(100, 13);
this.label26.TabIndex = 59;
this.label26.Text = "P (Any Dealer Win):";
//
// lblDealerStraightWin
//
this.lblDealerStraightWin.AutoSize = true;
this.lblDealerStraightWin.Location = new System.Drawing.Point(167, 160);
this.lblDealerStraightWin.Name = "lblDealerStraightWin";
this.lblDealerStraightWin.Size = new System.Drawing.Size(13, 13);
this.lblDealerStraightWin.TabIndex = 58;
this.lblDealerStraightWin.Text = "0";
//
// lblDealerWinOnDouble
//
this.lblDealerWinOnDouble.AutoSize = true;
this.lblDealerWinOnDouble.Location = new System.Drawing.Point(167, 145);
this.lblDealerWinOnDouble.Name = "lblDealerWinOnDouble";
this.lblDealerWinOnDouble.Size = new System.Drawing.Size(13, 13);
this.lblDealerWinOnDouble.TabIndex = 57;
this.lblDealerWinOnDouble.Text = "0";
//
// label24
//
this.label24.AutoSize = true;
this.label24.Location = new System.Drawing.Point(7, 145);
this.label24.Name = "label24";
this.label24.Size = new System.Drawing.Size(131, 13);
this.label24.TabIndex = 56;
this.label24.Text = "P (Dealer Win on Double):";
//
// label25
//
this.label25.AutoSize = true;
this.label25.Location = new System.Drawing.Point(7, 160);
this.label25.Name = "label25";
this.label25.Size = new System.Drawing.Size(118, 13);
this.label25.TabIndex = 55;
this.label25.Text = "P (Dealer Straight Win):";
//
// lblPlayerStraightWin
//
this.lblPlayerStraightWin.AutoSize = true;
this.lblPlayerStraightWin.Location = new System.Drawing.Point(167, 81);
this.lblPlayerStraightWin.Name = "lblPlayerStraightWin";
this.lblPlayerStraightWin.Size = new System.Drawing.Size(13, 13);
this.lblPlayerStraightWin.TabIndex = 54;
this.lblPlayerStraightWin.Text = "0";
//
// label16
//
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(7, 81);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(116, 13);
this.label16.TabIndex = 53;
this.label16.Text = "P (Player Straight Win):";
//
// lblUnweightedAdv
//
this.lblUnweightedAdv.AutoSize = true;
this.lblUnweightedAdv.Location = new System.Drawing.Point(169, 224);
this.lblUnweightedAdv.Name = "lblUnweightedAdv";
this.lblUnweightedAdv.Size = new System.Drawing.Size(13, 13);
this.lblUnweightedAdv.TabIndex = 52;
this.lblUnweightedAdv.Text = "0";
//
// label19
//
this.label19.AutoSize = true;
this.label19.Location = new System.Drawing.Point(7, 224);
this.label19.Name = "label19";
this.label19.Size = new System.Drawing.Size(156, 13);
this.label19.TabIndex = 51;
this.label19.Text = "Unweighted House Advantage:";
//
// lblWinOnBJ
//
this.lblWinOnBJ.AutoSize = true;
this.lblWinOnBJ.Location = new System.Drawing.Point(167, 66);
this.lblWinOnBJ.Name = "lblWinOnBJ";
this.lblWinOnBJ.Size = new System.Drawing.Size(13, 13);
this.lblWinOnBJ.TabIndex = 50;
this.lblWinOnBJ.Text = "0";
//
// lblWinOnDouble
//
this.lblWinOnDouble.AutoSize = true;
this.lblWinOnDouble.Location = new System.Drawing.Point(167, 51);
this.lblWinOnDouble.Name = "lblWinOnDouble";
this.lblWinOnDouble.Size = new System.Drawing.Size(13, 13);
this.lblWinOnDouble.TabIndex = 49;
this.lblWinOnDouble.Text = "0";
//
// lblNonPushingTotal
//
this.lblNonPushingTotal.AutoSize = true;
this.lblNonPushingTotal.Location = new System.Drawing.Point(167, 20);
this.lblNonPushingTotal.Name = "lblNonPushingTotal";
this.lblNonPushingTotal.Size = new System.Drawing.Size(13, 13);
this.lblNonPushingTotal.TabIndex = 48;
this.lblNonPushingTotal.Text = "0";
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(7, 97);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(98, 13);
this.label15.TabIndex = 47;
this.label15.Text = "P (Any Player Win):";
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(7, 20);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(129, 13);
this.label14.TabIndex = 45;
this.label14.Text = "Total Non-Pushing Hands";
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(7, 51);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(129, 13);
this.label13.TabIndex = 46;
this.label13.Text = "P (Player Win on Double):";
//
// lblPlayerWinTotal
//
this.lblPlayerWinTotal.AutoSize = true;
this.lblPlayerWinTotal.Location = new System.Drawing.Point(167, 97);
this.lblPlayerWinTotal.Name = "lblPlayerWinTotal";
this.lblPlayerWinTotal.Size = new System.Drawing.Size(13, 13);
this.lblPlayerWinTotal.TabIndex = 44;
this.lblPlayerWinTotal.Text = "0";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(7, 66);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(127, 13);
this.label5.TabIndex = 43;
this.label5.Text = "P (Player Win Blackjack);";
//
// groupBox6
//
this.groupBox6.Controls.Add(this.lblInsuranceBetsLost);
this.groupBox6.Controls.Add(this.lblInsuranceBetsWon);
this.groupBox6.Controls.Add(this.label43);
this.groupBox6.Controls.Add(this.label42);
this.groupBox6.Controls.Add(this.lblTCAdjustment);
this.groupBox6.Controls.Add(this.label40);
this.groupBox6.Controls.Add(this.label39);
this.groupBox6.Controls.Add(this.label38);
this.groupBox6.Controls.Add(this.label37);
this.groupBox6.Controls.Add(this.lblBettingUnit);
this.groupBox6.Controls.Add(this.label36);
this.groupBox6.Controls.Add(this.tbAgression);
this.groupBox6.Controls.Add(this.label33);
this.groupBox6.Controls.Add(this.txtStartingBankRoll);
this.groupBox6.Controls.Add(this.lblHighestBankroll);
this.groupBox6.Controls.Add(this.lblHighestBet);
this.groupBox6.Controls.Add(this.label7);
this.groupBox6.Controls.Add(this.lblLowestBankroll);
this.groupBox6.Controls.Add(this.lblLowestCount);
this.groupBox6.Controls.Add(this.lblHighestCount);
this.groupBox6.Controls.Add(this.label32);
this.groupBox6.Controls.Add(this.label31);
this.groupBox6.Controls.Add(this.label30);
this.groupBox6.Controls.Add(this.label29);
this.groupBox6.Controls.Add(this.label27);
this.groupBox6.Location = new System.Drawing.Point(562, 3);
this.groupBox6.Name = "groupBox6";
this.groupBox6.Size = new System.Drawing.Size(305, 310);
this.groupBox6.TabIndex = 60;
this.groupBox6.TabStop = false;
this.groupBox6.Text = "HI/LOW SYSTEM TRACKING";
this.groupBox6.Enter += new System.EventHandler(this.groupBox6_Enter);
//
// lblInsuranceBetsLost
//
this.lblInsuranceBetsLost.AutoSize = true;
this.lblInsuranceBetsLost.Location = new System.Drawing.Point(202, 284);
this.lblInsuranceBetsLost.Name = "lblInsuranceBetsLost";
this.lblInsuranceBetsLost.Size = new System.Drawing.Size(13, 13);
this.lblInsuranceBetsLost.TabIndex = 70;
this.lblInsuranceBetsLost.Text = "0";
//
// lblInsuranceBetsWon
//
this.lblInsuranceBetsWon.AutoSize = true;
this.lblInsuranceBetsWon.Location = new System.Drawing.Point(202, 267);
this.lblInsuranceBetsWon.Name = "lblInsuranceBetsWon";
this.lblInsuranceBetsWon.Size = new System.Drawing.Size(13, 13);
this.lblInsuranceBetsWon.TabIndex = 69;
this.lblInsuranceBetsWon.Text = "0";
//
// label43
//
this.label43.AutoSize = true;
this.label43.Location = new System.Drawing.Point(48, 284);
this.label43.Name = "label43";
this.label43.Size = new System.Drawing.Size(144, 13);
this.label43.TabIndex = 68;
this.label43.Text = "Num. of Insurance Bets Lost:";
//
// label42
//
this.label42.AutoSize = true;
this.label42.Location = new System.Drawing.Point(48, 267);
this.label42.Name = "label42";
this.label42.Size = new System.Drawing.Size(147, 13);
this.label42.TabIndex = 67;
this.label42.Text = "Num. of Insurance Bets Won:";
//
// lblTCAdjustment
//
this.lblTCAdjustment.AutoSize = true;
this.lblTCAdjustment.Location = new System.Drawing.Point(202, 220);
this.lblTCAdjustment.Name = "lblTCAdjustment";
this.lblTCAdjustment.Size = new System.Drawing.Size(13, 13);
this.lblTCAdjustment.TabIndex = 66;
this.lblTCAdjustment.Text = "1";
//
// label40
//
this.label40.AutoSize = true;
this.label40.Location = new System.Drawing.Point(57, 235);
this.label40.Name = "label40";
this.label40.Size = new System.Drawing.Size(186, 13);
this.label40.TabIndex = 65;
this.label40.Text = " [ 1.0 for good rules, 1.5 for bad rules]:";
//
// label39
//
this.label39.AutoSize = true;
this.label39.Location = new System.Drawing.Point(57, 220);
this.label39.Name = "label39";
this.label39.Size = new System.Drawing.Size(118, 13);
this.label39.TabIndex = 64;
this.label39.Text = "True Count Adjustment:";
//
// label38
//
this.label38.AutoSize = true;
this.label38.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label38.Location = new System.Drawing.Point(78, 64);
this.label38.Name = "label38";
this.label38.Size = new System.Drawing.Size(20, 25);
this.label38.TabIndex = 63;
this.label38.Text = "-";
//
// label37
//
this.label37.AutoSize = true;
this.label37.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label37.Location = new System.Drawing.Point(265, 67);
this.label37.Name = "label37";
this.label37.Size = new System.Drawing.Size(19, 20);
this.label37.TabIndex = 62;
this.label37.Text = "+";
//
// lblBettingUnit
//
this.lblBettingUnit.AutoSize = true;
this.lblBettingUnit.Location = new System.Drawing.Point(202, 109);
this.lblBettingUnit.Name = "lblBettingUnit";
this.lblBettingUnit.Size = new System.Drawing.Size(13, 13);
this.lblBettingUnit.TabIndex = 61;
this.lblBettingUnit.Text = "0";
//
// label36
//
this.label36.AutoSize = true;
this.label36.Location = new System.Drawing.Point(18, 73);
this.label36.Name = "label36";
this.label36.Size = new System.Drawing.Size(59, 13);
this.label36.TabIndex = 60;
this.label36.Text = "Agrression:";
//
// tbAgression
//
this.tbAgression.LargeChange = 2;
this.tbAgression.Location = new System.Drawing.Point(93, 67);
this.tbAgression.Name = "tbAgression";
this.tbAgression.Size = new System.Drawing.Size(177, 42);
this.tbAgression.TabIndex = 59;
this.tbAgression.Value = 10;
this.tbAgression.Scroll += new System.EventHandler(this.tbAgression_Scroll);
//
// label33
//
this.label33.AutoSize = true;
this.label33.Location = new System.Drawing.Point(18, 39);
this.label33.Name = "label33";
this.label33.Size = new System.Drawing.Size(114, 13);
this.label33.TabIndex = 58;
this.label33.Text = "Total Starting Bankroll:";
//
// txtStartingBankRoll
//
this.txtStartingBankRoll.Location = new System.Drawing.Point(133, 36);
this.txtStartingBankRoll.Name = "txtStartingBankRoll";
this.txtStartingBankRoll.Size = new System.Drawing.Size(138, 20);
this.txtStartingBankRoll.TabIndex = 57;
this.txtStartingBankRoll.Text = "50000";
this.txtStartingBankRoll.TextChanged += new System.EventHandler(this.txtStartingBankRoll_TextChanged);
//
// lblHighestBankroll
//
this.lblHighestBankroll.AutoSize = true;
this.lblHighestBankroll.Location = new System.Drawing.Point(202, 145);
this.lblHighestBankroll.Name = "lblHighestBankroll";
this.lblHighestBankroll.Size = new System.Drawing.Size(13, 13);
this.lblHighestBankroll.TabIndex = 8;
this.lblHighestBankroll.Text = "0";
//
// lblHighestBet
//
this.lblHighestBet.AutoSize = true;
this.lblHighestBet.Location = new System.Drawing.Point(202, 132);
this.lblHighestBet.Name = "lblHighestBet";
this.lblHighestBet.Size = new System.Drawing.Size(13, 13);
this.lblHighestBet.TabIndex = 7;
this.lblHighestBet.Text = "0";
//
// lblLowestBankroll
//
this.lblLowestBankroll.AutoSize = true;
this.lblLowestBankroll.Location = new System.Drawing.Point(202, 158);
this.lblLowestBankroll.Name = "lblLowestBankroll";
this.lblLowestBankroll.Size = new System.Drawing.Size(13, 13);
this.lblLowestBankroll.TabIndex = 7;
this.lblLowestBankroll.Text = "0";
//
// lblLowestCount
//
this.lblLowestCount.AutoSize = true;
this.lblLowestCount.Location = new System.Drawing.Point(202, 190);
this.lblLowestCount.Name = "lblLowestCount";
this.lblLowestCount.Size = new System.Drawing.Size(13, 13);
this.lblLowestCount.TabIndex = 6;
this.lblLowestCount.Text = "0";
//
// lblHighestCount
//
this.lblHighestCount.AutoSize = true;
this.lblHighestCount.Location = new System.Drawing.Point(202, 177);
this.lblHighestCount.Name = "lblHighestCount";
this.lblHighestCount.Size = new System.Drawing.Size(13, 13);
this.lblHighestCount.TabIndex = 5;
this.lblHighestCount.Text = "0";
//
// label32
//
this.label32.AutoSize = true;
this.label32.Location = new System.Drawing.Point(90, 158);
this.label32.Name = "label32";
this.label32.Size = new System.Drawing.Size(85, 13);
this.label32.TabIndex = 4;
this.label32.Text = "Lowest Bankroll:";
//
// label31
//
this.label31.AutoSize = true;
this.label31.Location = new System.Drawing.Point(90, 145);
this.label31.Name = "label31";
this.label31.Size = new System.Drawing.Size(87, 13);
this.label31.TabIndex = 3;
this.label31.Text = "Highest Bankroll:";
//
// label30
//
this.label30.AutoSize = true;
this.label30.Location = new System.Drawing.Point(90, 132);
this.label30.Name = "label30";
this.label30.Size = new System.Drawing.Size(65, 13);
this.label30.TabIndex = 2;
this.label30.Text = "Highest Bet:";
//
// label29
//
this.label29.AutoSize = true;
this.label29.Location = new System.Drawing.Point(90, 190);
this.label29.Name = "label29";
this.label29.Size = new System.Drawing.Size(75, 13);
this.label29.TabIndex = 1;
this.label29.Text = "Lowest Count:";
//
// label27
//
this.label27.AutoSize = true;
this.label27.Location = new System.Drawing.Point(90, 177);
this.label27.Name = "label27";
this.label27.Size = new System.Drawing.Size(77, 13);
this.label27.TabIndex = 0;
this.label27.Text = "Highest Count:";
//
// groupBox7
//
this.groupBox7.Controls.Add(this.lblErrors);
this.groupBox7.Controls.Add(this.label52);
this.groupBox7.Controls.Add(this.gbError);
this.groupBox7.Controls.Add(this.groupBox8);
this.groupBox7.Location = new System.Drawing.Point(562, 317);
this.groupBox7.Name = "groupBox7";
this.groupBox7.Size = new System.Drawing.Size(305, 258);
this.groupBox7.TabIndex = 61;
this.groupBox7.TabStop = false;
this.groupBox7.Text = "HUMAN ERROR";
this.groupBox7.Enter += new System.EventHandler(this.groupBox7_Enter);
//
// lblErrors
//
this.lblErrors.AutoSize = true;
this.lblErrors.Location = new System.Drawing.Point(187, 239);
this.lblErrors.Name = "lblErrors";
this.lblErrors.Size = new System.Drawing.Size(13, 13);
this.lblErrors.TabIndex = 69;
this.lblErrors.Text = "0";
//
// label52
//
this.label52.AutoSize = true;
this.label52.Location = new System.Drawing.Point(86, 238);
this.label52.Name = "label52";
this.label52.Size = new System.Drawing.Size(104, 13);
this.label52.TabIndex = 68;
this.label52.Text = "Total Num. of Errors:";
//
// gbError
//
this.gbError.Controls.Add(this.lblErrorsPer100Hands);
this.gbError.Controls.Add(this.label50);
this.gbError.Controls.Add(this.label49);
this.gbError.Controls.Add(this.label48);
this.gbError.Controls.Add(this.label46);
this.gbError.Controls.Add(this.label47);
this.gbError.Controls.Add(this.label45);
this.gbError.Controls.Add(this.label44);
this.gbError.Controls.Add(this.tbErrorRate);
this.gbError.Enabled = false;
this.gbError.Location = new System.Drawing.Point(18, 60);
this.gbError.Name = "gbError";
this.gbError.Size = new System.Drawing.Size(271, 174);
this.gbError.TabIndex = 1;
this.gbError.TabStop = false;
this.gbError.Text = "Error Control";
this.gbError.Enter += new System.EventHandler(this.gbError_Enter);
//
// lblErrorsPer100Hands
//
this.lblErrorsPer100Hands.AutoSize = true;
this.lblErrorsPer100Hands.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblErrorsPer100Hands.Location = new System.Drawing.Point(57, 96);
this.lblErrorsPer100Hands.Name = "lblErrorsPer100Hands";
this.lblErrorsPer100Hands.Size = new System.Drawing.Size(170, 13);
this.lblErrorsPer100Hands.TabIndex = 69;
this.lblErrorsPer100Hands.Text = "1 errors per every 100 hands";
//
// label50
//
this.label50.AutoSize = true;
this.label50.Location = new System.Drawing.Point(10, 149);
this.label50.Name = "label50";
this.label50.Size = new System.Drawing.Size(171, 13);
this.label50.TabIndex = 68;
this.label50.Text = "either high or low by that ammount.";
//
// label49
//
this.label49.AutoSize = true;
this.label49.Location = new System.Drawing.Point(229, 64);
this.label49.Name = "label49";
this.label49.Size = new System.Drawing.Size(27, 13);
this.label49.TabIndex = 67;
this.label49.Text = "15%";
//
// label48
//
this.label48.AutoSize = true;
this.label48.Location = new System.Drawing.Point(26, 63);
this.label48.Name = "label48";
this.label48.Size = new System.Drawing.Size(21, 13);
this.label48.TabIndex = 66;
this.label48.Text = "1%";
//
// label46
//
this.label46.AutoSize = true;
this.label46.Location = new System.Drawing.Point(10, 136);
this.label46.Name = "label46";
this.label46.Size = new System.Drawing.Size(252, 13);
this.label46.TabIndex = 65;
this.label46.Text = "and 4 (25% chance of each). The player is randomly";
//
// label47
//
this.label47.AutoSize = true;
this.label47.Location = new System.Drawing.Point(12, 123);
this.label47.Name = "label47";
this.label47.Size = new System.Drawing.Size(236, 13);
this.label47.TabIndex = 64;
this.label47.Text = "A player can miscount by any number between 1";
//
// label45
//
this.label45.AutoSize = true;
this.label45.Location = new System.Drawing.Point(10, 34);
this.label45.Name = "label45";
this.label45.Size = new System.Drawing.Size(247, 13);
this.label45.TabIndex = 62;
this.label45.Text = "player will make a counting error during each hand:";
//
// label44
//
this.label44.AutoSize = true;
this.label44.Location = new System.Drawing.Point(10, 18);
this.label44.Name = "label44";
this.label44.Size = new System.Drawing.Size(223, 13);
this.label44.TabIndex = 61;
this.label44.Text = "This error rate slider reflects the chance that a";
//
// tbErrorRate
//
this.tbErrorRate.LargeChange = 2;
this.tbErrorRate.Location = new System.Drawing.Point(44, 59);
this.tbErrorRate.Maximum = 15;
this.tbErrorRate.Minimum = 1;
this.tbErrorRate.Name = "tbErrorRate";
this.tbErrorRate.Size = new System.Drawing.Size(189, 42);
this.tbErrorRate.TabIndex = 60;
this.tbErrorRate.Value = 1;
this.tbErrorRate.Scroll += new System.EventHandler(this.tbErrorRate_Scroll);
//
// groupBox8
//
this.groupBox8.Controls.Add(this.rbErrorsOff);
this.groupBox8.Controls.Add(this.rbErrorsOn);
this.groupBox8.Location = new System.Drawing.Point(18, 18);
this.groupBox8.Name = "groupBox8";
this.groupBox8.Size = new System.Drawing.Size(271, 39);
this.groupBox8.TabIndex = 0;
this.groupBox8.TabStop = false;
this.groupBox8.Text = "Player Error";
//
// rbErrorsOff
//
this.rbErrorsOff.AutoSize = true;
this.rbErrorsOff.Checked = true;
this.rbErrorsOff.Location = new System.Drawing.Point(143, 13);
this.rbErrorsOff.Name = "rbErrorsOff";
this.rbErrorsOff.Size = new System.Drawing.Size(39, 17);
this.rbErrorsOff.TabIndex = 1;
this.rbErrorsOff.TabStop = true;
this.rbErrorsOff.Text = "Off";
this.rbErrorsOff.UseVisualStyleBackColor = true;
this.rbErrorsOff.CheckedChanged += new System.EventHandler(this.rbErrorsOff_CheckedChanged);
//
// rbErrorsOn
//
this.rbErrorsOn.AutoSize = true;
this.rbErrorsOn.Location = new System.Drawing.Point(98, 13);
this.rbErrorsOn.Name = "rbErrorsOn";
this.rbErrorsOn.Size = new System.Drawing.Size(39, 17);
this.rbErrorsOn.TabIndex = 0;
this.rbErrorsOn.Text = "On";
this.rbErrorsOn.UseVisualStyleBackColor = true;
this.rbErrorsOn.CheckedChanged += new System.EventHandler(this.rbErrorsOn_CheckedChanged);
//
// cmdMultiSim
//
this.cmdMultiSim.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("cmdMultiSim.BackgroundImage")));
this.cmdMultiSim.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.cmdMultiSim.Location = new System.Drawing.Point(24, 22);
this.cmdMultiSim.Name = "cmdMultiSim";
this.cmdMultiSim.Size = new System.Drawing.Size(135, 45);
this.cmdMultiSim.TabIndex = 63;
this.cmdMultiSim.Text = "Start Multiple Sims";
this.cmdMultiSim.UseVisualStyleBackColor = true;
this.cmdMultiSim.Click += new System.EventHandler(this.button1_Click);
//
// numericUpDown1
//
this.numericUpDown1.Location = new System.Drawing.Point(170, 42);
this.numericUpDown1.Maximum = new decimal(new int[] {
5000,
0,
0,
0});
this.numericUpDown1.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDown1.Name = "numericUpDown1";
this.numericUpDown1.Size = new System.Drawing.Size(89, 20);
this.numericUpDown1.TabIndex = 64;
this.numericUpDown1.Value = new decimal(new int[] {
100,
0,
0,
0});
//
// label51
//
this.label51.AutoSize = true;
this.label51.Location = new System.Drawing.Point(169, 25);
this.label51.Name = "label51";
this.label51.Size = new System.Drawing.Size(92, 13);
this.label51.TabIndex = 65;
this.label51.Text = "Num. of iterations:";
//
// txtPath
//
this.txtPath.Location = new System.Drawing.Point(6, 76);
this.txtPath.Name = "txtPath";
this.txtPath.Size = new System.Drawing.Size(264, 20);
this.txtPath.TabIndex = 66;
this.txtPath.Text = "[Enter Path to Save Data To Here] ie. C:\\test.txt";
//
// groupBox9
//
this.groupBox9.Controls.Add(this.txtPath);
this.groupBox9.Controls.Add(this.label51);
this.groupBox9.Controls.Add(this.numericUpDown1);
this.groupBox9.Controls.Add(this.cmdMultiSim);
this.groupBox9.Location = new System.Drawing.Point(278, 337);
this.groupBox9.Name = "groupBox9";
this.groupBox9.Size = new System.Drawing.Size(280, 104);
this.groupBox9.TabIndex = 67;
this.groupBox9.TabStop = false;
this.groupBox9.Text = "Track Repeat Simulations:";
//
// frmBlackJackSim
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(873, 613);
this.Controls.Add(this.groupBox9);
this.Controls.Add(this.cmdDetails);
this.Controls.Add(this.groupBox7);
this.Controls.Add(this.groupBox6);
this.Controls.Add(this.groupBox4);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.label10);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.rtbHandOutcome);
this.Controls.Add(this.cmdDeal);
this.Name = "frmBlackJackSim";
this.Text = "Bertolino - Blackjack Simulation";
this.Load += new System.EventHandler(this.Form1_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
this.groupBox5.ResumeLayout(false);
this.groupBox5.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.groupBox6.ResumeLayout(false);
this.groupBox6.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.tbAgression)).EndInit();
this.groupBox7.ResumeLayout(false);
this.groupBox7.PerformLayout();
this.gbError.ResumeLayout(false);
this.gbError.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.tbErrorRate)).EndInit();
this.groupBox8.ResumeLayout(false);
this.groupBox8.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
this.groupBox9.ResumeLayout(false);
this.groupBox9.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button cmdDeal;
private System.Windows.Forms.RichTextBox rtbHandOutcome;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lblDealerWins;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label lblPlayerWins;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label lblPushes;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label lblShoes;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label lblPlayerBankroll;
private System.Windows.Forms.Label Label12;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox txtHandsToSim;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton rbFalse;
private System.Windows.Forms.RadioButton rbTrue;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label lblSplits;
private System.Windows.Forms.Label lblTotalRounds;
private System.Windows.Forms.Label lblTotalHands;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.Label lblPlayerBlackjacks;
private System.Windows.Forms.Label label21;
private System.Windows.Forms.Label lblWinningDoubles;
private System.Windows.Forms.Label label22;
private System.Windows.Forms.Label lblLosingDoubles;
private System.Windows.Forms.Label label23;
private System.Windows.Forms.Label lblPushingDoubles;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.CheckBox checkBox2;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.CheckBox checkBox3;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.Label lblUnweightedAdv;
private System.Windows.Forms.Label label19;
private System.Windows.Forms.Label lblWinOnBJ;
private System.Windows.Forms.Label lblWinOnDouble;
private System.Windows.Forms.Label lblNonPushingTotal;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label lblPlayerWinTotal;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label lblPlayerStraightWin;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.Label lblDealerStraightWin;
private System.Windows.Forms.Label lblDealerWinOnDouble;
private System.Windows.Forms.Label label24;
private System.Windows.Forms.Label label25;
private System.Windows.Forms.Label lblDealerWinTotal;
private System.Windows.Forms.Label label26;
private System.Windows.Forms.Label lblPlayerCostWin;
private System.Windows.Forms.Label lblDealerCostWin;
private System.Windows.Forms.Label label20;
private System.Windows.Forms.Label label18;
private System.Windows.Forms.Label lblHouseAdvantage;
private System.Windows.Forms.Label label28;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.RadioButton rbCountFalse;
private System.Windows.Forms.RadioButton rbCountTrue;
private System.Windows.Forms.GroupBox groupBox6;
private System.Windows.Forms.Label lblHighestBankroll;
private System.Windows.Forms.Label lblHighestBet;
private System.Windows.Forms.Label lblLowestBankroll;
private System.Windows.Forms.Label lblLowestCount;
private System.Windows.Forms.Label lblHighestCount;
private System.Windows.Forms.Label label32;
private System.Windows.Forms.Label label31;
private System.Windows.Forms.Label label30;
private System.Windows.Forms.Label label29;
private System.Windows.Forms.Label label27;
private System.Windows.Forms.Label label33;
private System.Windows.Forms.TextBox txtStartingBankRoll;
private System.Windows.Forms.TextBox txtTableMax;
private System.Windows.Forms.TextBox txtTableMin;
private System.Windows.Forms.Label label35;
private System.Windows.Forms.Label label34;
private System.Windows.Forms.Label label36;
private System.Windows.Forms.TrackBar tbAgression;
private System.Windows.Forms.Label lblBettingUnit;
private System.Windows.Forms.CheckBox chkGUIUpdate;
private System.Windows.Forms.Label label37;
private System.Windows.Forms.Label label38;
private System.Windows.Forms.Label label39;
private System.Windows.Forms.Label lblTCAdjustment;
private System.Windows.Forms.Label label40;
private System.Windows.Forms.Label label41;
private System.Windows.Forms.Label label42;
private System.Windows.Forms.Label lblInsuranceBetsLost;
private System.Windows.Forms.Label lblInsuranceBetsWon;
private System.Windows.Forms.Label label43;
private System.Windows.Forms.Button cmdDetails;
private System.Windows.Forms.GroupBox groupBox7;
private System.Windows.Forms.GroupBox groupBox8;
private System.Windows.Forms.RadioButton rbErrorsOff;
private System.Windows.Forms.RadioButton rbErrorsOn;
private System.Windows.Forms.TrackBar tbErrorRate;
private System.Windows.Forms.Label label44;
private System.Windows.Forms.Label label45;
private System.Windows.Forms.GroupBox gbError;
private System.Windows.Forms.Label label46;
private System.Windows.Forms.Label label47;
private System.Windows.Forms.Label label49;
private System.Windows.Forms.Label label48;
private System.Windows.Forms.Label label52;
private System.Windows.Forms.Label lblErrors;
private System.Windows.Forms.Label label50;
private System.Windows.Forms.Label lblErrorsPer100Hands;
private System.Windows.Forms.Button cmdMultiSim;
private System.Windows.Forms.NumericUpDown numericUpDown1;
private System.Windows.Forms.Label label51;
private System.Windows.Forms.TextBox txtPath;
private System.Windows.Forms.GroupBox groupBox9;
}
}
| |
// 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.
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public abstract class SendReceive : MemberDatas
{
private readonly ITestOutputHelper _log;
public SendReceive(ITestOutputHelper output)
{
_log = output;
}
public abstract Task<Socket> AcceptAsync(Socket s);
public abstract Task ConnectAsync(Socket s, EndPoint endPoint);
public abstract Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer);
public abstract Task<SocketReceiveFromResult> ReceiveFromAsync(
Socket s, ArraySegment<byte> buffer, EndPoint endPoint);
public abstract Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList);
public abstract Task<int> SendAsync(Socket s, ArraySegment<byte> buffer);
public abstract Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList);
public abstract Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endpoint);
public virtual bool GuaranteedSendOrdering => true;
public virtual bool ValidatesArrayArguments => true;
public virtual bool UsesSync => false;
public virtual bool DisposeDuringOperationResultsInDisposedException => false;
[Theory]
[InlineData(null, 0, 0)] // null array
[InlineData(1, -1, 0)] // offset low
[InlineData(1, 2, 0)] // offset high
[InlineData(1, 0, -1)] // count low
[InlineData(1, 1, 2)] // count high
public async Task InvalidArguments_Throws(int? length, int offset, int count)
{
if (length == null && !ValidatesArrayArguments) return;
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Type expectedExceptionType = length == null ? typeof(ArgumentNullException) : typeof(ArgumentOutOfRangeException);
var validBuffer = new ArraySegment<byte>(new byte[1]);
var invalidBuffer = new FakeArraySegment { Array = length != null ? new byte[length.Value] : null, Offset = offset, Count = count }.ToActual();
await Assert.ThrowsAsync(expectedExceptionType, () => ReceiveAsync(s, invalidBuffer));
await Assert.ThrowsAsync(expectedExceptionType, () => ReceiveAsync(s, new List<ArraySegment<byte>> { invalidBuffer }));
await Assert.ThrowsAsync(expectedExceptionType, () => ReceiveAsync(s, new List<ArraySegment<byte>> { validBuffer, invalidBuffer }));
await Assert.ThrowsAsync(expectedExceptionType, () => SendAsync(s, invalidBuffer));
await Assert.ThrowsAsync(expectedExceptionType, () => SendAsync(s, new List<ArraySegment<byte>> { invalidBuffer }));
await Assert.ThrowsAsync(expectedExceptionType, () => SendAsync(s, new List<ArraySegment<byte>> { validBuffer, invalidBuffer }));
}
}
[ActiveIssue(16945)] // Packet loss, potentially due to other tests running at the same time
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(Loopbacks))]
public async Task SendToRecvFrom_Datagram_UDP(IPAddress loopbackAddress)
{
IPAddress leftAddress = loopbackAddress, rightAddress = loopbackAddress;
// TODO #5185: Harden against packet loss
const int DatagramSize = 256;
const int DatagramsToSend = 256;
const int AckTimeout = 1000;
const int TestTimeout = 30000;
var left = new Socket(leftAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
left.BindToAnonymousPort(leftAddress);
var right = new Socket(rightAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
right.BindToAnonymousPort(rightAddress);
var leftEndpoint = (IPEndPoint)left.LocalEndPoint;
var rightEndpoint = (IPEndPoint)right.LocalEndPoint;
var receiverAck = new SemaphoreSlim(0);
var senderAck = new SemaphoreSlim(0);
var receivedChecksums = new uint?[DatagramsToSend];
Task leftThread = Task.Run(async () =>
{
using (left)
{
EndPoint remote = leftEndpoint.Create(leftEndpoint.Serialize());
var recvBuffer = new byte[DatagramSize];
for (int i = 0; i < DatagramsToSend; i++)
{
SocketReceiveFromResult result = await ReceiveFromAsync(
left, new ArraySegment<byte>(recvBuffer), remote);
Assert.Equal(DatagramSize, result.ReceivedBytes);
Assert.Equal(rightEndpoint, result.RemoteEndPoint);
int datagramId = recvBuffer[0];
Assert.Null(receivedChecksums[datagramId]);
receivedChecksums[datagramId] = Fletcher32.Checksum(recvBuffer, 0, result.ReceivedBytes);
receiverAck.Release();
Assert.True(await senderAck.WaitAsync(TestTimeout));
}
}
});
var sentChecksums = new uint[DatagramsToSend];
using (right)
{
var random = new Random();
var sendBuffer = new byte[DatagramSize];
for (int i = 0; i < DatagramsToSend; i++)
{
random.NextBytes(sendBuffer);
sendBuffer[0] = (byte)i;
int sent = await SendToAsync(right, new ArraySegment<byte>(sendBuffer), leftEndpoint);
Assert.True(await receiverAck.WaitAsync(AckTimeout));
senderAck.Release();
Assert.Equal(DatagramSize, sent);
sentChecksums[i] = Fletcher32.Checksum(sendBuffer, 0, sent);
}
}
await leftThread;
for (int i = 0; i < DatagramsToSend; i++)
{
Assert.NotNull(receivedChecksums[i]);
Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(LoopbacksAndBuffers))]
public async Task SendRecv_Stream_TCP(IPAddress listenAt, bool useMultipleBuffers)
{
const int BytesToSend = 123456, ListenBacklog = 1, LingerTime = 1;
int bytesReceived = 0, bytesSent = 0;
Fletcher32 receivedChecksum = new Fletcher32(), sentChecksum = new Fletcher32();
using (var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
server.BindToAnonymousPort(listenAt);
server.Listen(ListenBacklog);
Task serverProcessingTask = Task.Run(async () =>
{
using (Socket remote = await AcceptAsync(server))
{
if (!useMultipleBuffers)
{
var recvBuffer = new byte[256];
for (;;)
{
int received = await ReceiveAsync(remote, new ArraySegment<byte>(recvBuffer));
if (received == 0)
{
break;
}
bytesReceived += received;
receivedChecksum.Add(recvBuffer, 0, received);
}
}
else
{
var recvBuffers = new List<ArraySegment<byte>> {
new ArraySegment<byte>(new byte[123]),
new ArraySegment<byte>(new byte[256], 2, 100),
new ArraySegment<byte>(new byte[1], 0, 0),
new ArraySegment<byte>(new byte[64], 9, 33)};
for (;;)
{
int received = await ReceiveAsync(remote, recvBuffers);
if (received == 0)
{
break;
}
bytesReceived += received;
for (int i = 0, remaining = received; i < recvBuffers.Count && remaining > 0; i++)
{
ArraySegment<byte> buffer = recvBuffers[i];
int toAdd = Math.Min(buffer.Count, remaining);
receivedChecksum.Add(buffer.Array, buffer.Offset, toAdd);
remaining -= toAdd;
}
}
}
}
});
EndPoint clientEndpoint = server.LocalEndPoint;
using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
await ConnectAsync(client, clientEndpoint);
var random = new Random();
if (!useMultipleBuffers)
{
var sendBuffer = new byte[512];
for (int sent = 0, remaining = BytesToSend; remaining > 0; remaining -= sent)
{
random.NextBytes(sendBuffer);
sent = await SendAsync(client, new ArraySegment<byte>(sendBuffer, 0, Math.Min(sendBuffer.Length, remaining)));
bytesSent += sent;
sentChecksum.Add(sendBuffer, 0, sent);
}
}
else
{
var sendBuffers = new List<ArraySegment<byte>> {
new ArraySegment<byte>(new byte[23]),
new ArraySegment<byte>(new byte[256], 2, 100),
new ArraySegment<byte>(new byte[1], 0, 0),
new ArraySegment<byte>(new byte[64], 9, 9)};
for (int sent = 0, toSend = BytesToSend; toSend > 0; toSend -= sent)
{
for (int i = 0; i < sendBuffers.Count; i++)
{
random.NextBytes(sendBuffers[i].Array);
}
sent = await SendAsync(client, sendBuffers);
bytesSent += sent;
for (int i = 0, remaining = sent; i < sendBuffers.Count && remaining > 0; i++)
{
ArraySegment<byte> buffer = sendBuffers[i];
int toAdd = Math.Min(buffer.Count, remaining);
sentChecksum.Add(buffer.Array, buffer.Offset, toAdd);
remaining -= toAdd;
}
}
}
client.LingerState = new LingerOption(true, LingerTime);
client.Shutdown(SocketShutdown.Send);
await serverProcessingTask;
}
Assert.Equal(bytesSent, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(Loopbacks))]
public async Task SendRecv_Stream_TCP_AlternateBufferAndBufferList(IPAddress listenAt)
{
const int BytesToSend = 123456;
int bytesReceived = 0, bytesSent = 0;
Fletcher32 receivedChecksum = new Fletcher32(), sentChecksum = new Fletcher32();
using (var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
server.BindToAnonymousPort(listenAt);
server.Listen(1);
Task serverProcessingTask = Task.Run(async () =>
{
using (Socket remote = await AcceptAsync(server))
{
byte[] recvBuffer1 = new byte[256], recvBuffer2 = new byte[256];
long iter = 0;
while (true)
{
ArraySegment<byte> seg1 = new ArraySegment<byte>(recvBuffer1), seg2 = new ArraySegment<byte>(recvBuffer2);
int received;
switch (iter++ % 3)
{
case 0: // single buffer
received = await ReceiveAsync(remote, seg1);
break;
case 1: // buffer list with a single buffer
received = await ReceiveAsync(remote, new List<ArraySegment<byte>> { seg1 });
break;
default: // buffer list with multiple buffers
received = await ReceiveAsync(remote, new List<ArraySegment<byte>> { seg1, seg2 });
break;
}
if (received == 0)
{
break;
}
bytesReceived += received;
receivedChecksum.Add(recvBuffer1, 0, Math.Min(received, recvBuffer1.Length));
if (received > recvBuffer1.Length)
{
receivedChecksum.Add(recvBuffer2, 0, received - recvBuffer1.Length);
}
}
}
});
EndPoint clientEndpoint = server.LocalEndPoint;
using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
await ConnectAsync(client, clientEndpoint);
var random = new Random();
byte[] sendBuffer1 = new byte[512], sendBuffer2 = new byte[512];
long iter = 0;
for (int sent = 0, remaining = BytesToSend; remaining > 0; remaining -= sent)
{
random.NextBytes(sendBuffer1);
random.NextBytes(sendBuffer2);
int amountFromSendBuffer1 = Math.Min(sendBuffer1.Length, remaining);
switch (iter++ % 3)
{
case 0: // single buffer
sent = await SendAsync(client, new ArraySegment<byte>(sendBuffer1, 0, amountFromSendBuffer1));
break;
case 1: // buffer list with a single buffer
sent = await SendAsync(client, new List<ArraySegment<byte>>
{
new ArraySegment<byte>(sendBuffer1, 0, amountFromSendBuffer1)
});
break;
default: // buffer list with multiple buffers
sent = await SendAsync(client, new List<ArraySegment<byte>>
{
new ArraySegment<byte>(sendBuffer1, 0, amountFromSendBuffer1),
new ArraySegment<byte>(sendBuffer2, 0, Math.Min(sendBuffer2.Length, remaining - amountFromSendBuffer1)),
});
break;
}
bytesSent += sent;
sentChecksum.Add(sendBuffer1, 0, Math.Min(sent, sendBuffer1.Length));
if (sent > sendBuffer1.Length)
{
sentChecksum.Add(sendBuffer2, 0, sent - sendBuffer1.Length);
}
}
client.Shutdown(SocketShutdown.Send);
await serverProcessingTask;
}
Assert.Equal(bytesSent, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(LoopbacksAndBuffers))]
public async Task SendRecv_Stream_TCP_MultipleConcurrentReceives(IPAddress listenAt, bool useMultipleBuffers)
{
using (var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
server.BindToAnonymousPort(listenAt);
server.Listen(1);
EndPoint clientEndpoint = server.LocalEndPoint;
using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
Task clientConnect = ConnectAsync(client, clientEndpoint);
using (Socket remote = await AcceptAsync(server))
{
await clientConnect;
if (useMultipleBuffers)
{
byte[] buffer1 = new byte[1], buffer2 = new byte[1], buffer3 = new byte[1], buffer4 = new byte[1], buffer5 = new byte[1];
Task<int> receive1 = ReceiveAsync(client, new List<ArraySegment<byte>> { new ArraySegment<byte>(buffer1), new ArraySegment<byte>(buffer2) });
Task<int> receive2 = ReceiveAsync(client, new List<ArraySegment<byte>> { new ArraySegment<byte>(buffer3), new ArraySegment<byte>(buffer4) });
Task<int> receive3 = ReceiveAsync(client, new List<ArraySegment<byte>> { new ArraySegment<byte>(buffer5) });
await Task.WhenAll(
SendAsync(remote, new ArraySegment<byte>(new byte[] { 1, 2, 3, 4, 5 })),
receive1, receive2, receive3);
Assert.True(receive1.Result == 1 || receive1.Result == 2, $"Expected 1 or 2, got {receive1.Result}");
Assert.True(receive2.Result == 1 || receive2.Result == 2, $"Expected 1 or 2, got {receive2.Result}");
Assert.Equal(1, receive3.Result);
if (GuaranteedSendOrdering)
{
if (receive1.Result == 1 && receive2.Result == 1)
{
Assert.Equal(1, buffer1[0]);
Assert.Equal(0, buffer2[0]);
Assert.Equal(2, buffer3[0]);
Assert.Equal(0, buffer4[0]);
Assert.Equal(3, buffer5[0]);
}
else if (receive1.Result == 1 && receive2.Result == 2)
{
Assert.Equal(1, buffer1[0]);
Assert.Equal(0, buffer2[0]);
Assert.Equal(2, buffer3[0]);
Assert.Equal(3, buffer4[0]);
Assert.Equal(4, buffer5[0]);
}
else if (receive1.Result == 2 && receive2.Result == 1)
{
Assert.Equal(1, buffer1[0]);
Assert.Equal(2, buffer2[0]);
Assert.Equal(3, buffer3[0]);
Assert.Equal(0, buffer4[0]);
Assert.Equal(4, buffer5[0]);
}
else // receive1.Result == 2 && receive2.Result == 2
{
Assert.Equal(1, buffer1[0]);
Assert.Equal(2, buffer2[0]);
Assert.Equal(3, buffer3[0]);
Assert.Equal(4, buffer4[0]);
Assert.Equal(5, buffer5[0]);
}
}
}
else
{
var buffer1 = new ArraySegment<byte>(new byte[1]);
var buffer2 = new ArraySegment<byte>(new byte[1]);
var buffer3 = new ArraySegment<byte>(new byte[1]);
Task<int> receive1 = ReceiveAsync(client, buffer1);
Task<int> receive2 = ReceiveAsync(client, buffer2);
Task<int> receive3 = ReceiveAsync(client, buffer3);
await Task.WhenAll(
SendAsync(remote, new ArraySegment<byte>(new byte[] { 1, 2, 3 })),
receive1, receive2, receive3);
Assert.Equal(3, receive1.Result + receive2.Result + receive3.Result);
if (GuaranteedSendOrdering)
{
Assert.Equal(1, buffer1.Array[0]);
Assert.Equal(2, buffer2.Array[0]);
Assert.Equal(3, buffer3.Array[0]);
}
}
}
}
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(LoopbacksAndBuffers))]
public async Task SendRecv_Stream_TCP_MultipleConcurrentSends(IPAddress listenAt, bool useMultipleBuffers)
{
using (var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
byte[] sendData = new byte[5000000];
new Random(42).NextBytes(sendData);
Func<byte[], int, int, byte[]> slice = (input, offset, count) =>
{
var arr = new byte[count];
Array.Copy(input, offset, arr, 0, count);
return arr;
};
server.BindToAnonymousPort(listenAt);
server.Listen(1);
EndPoint clientEndpoint = server.LocalEndPoint;
using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
Task clientConnect = ConnectAsync(client, clientEndpoint);
using (Socket remote = await AcceptAsync(server))
{
await clientConnect;
Task<int> send1, send2, send3;
if (useMultipleBuffers)
{
var bufferList1 = new List<ArraySegment<byte>> { new ArraySegment<byte>(slice(sendData, 0, 1000000)), new ArraySegment<byte>(slice(sendData, 1000000, 1000000)) };
var bufferList2 = new List<ArraySegment<byte>> { new ArraySegment<byte>(slice(sendData, 2000000, 1000000)), new ArraySegment<byte>(slice(sendData, 3000000, 1000000)) };
var bufferList3 = new List<ArraySegment<byte>> { new ArraySegment<byte>(slice(sendData, 4000000, 1000000)) };
send1 = SendAsync(client, bufferList1);
send2 = SendAsync(client, bufferList2);
send3 = SendAsync(client, bufferList3);
}
else
{
var buffer1 = new ArraySegment<byte>(slice(sendData, 0, 2000000));
var buffer2 = new ArraySegment<byte>(slice(sendData, 2000000, 2000000));
var buffer3 = new ArraySegment<byte>(slice(sendData, 4000000, 1000000));
send1 = SendAsync(client, buffer1);
send2 = SendAsync(client, buffer2);
send3 = SendAsync(client, buffer3);
}
int receivedTotal = 0;
int received;
var receiveBuffer = new byte[sendData.Length];
while (receivedTotal < receiveBuffer.Length)
{
if ((received = await ReceiveAsync(remote, new ArraySegment<byte>(receiveBuffer, receivedTotal, receiveBuffer.Length - receivedTotal))) == 0) break;
receivedTotal += received;
}
Assert.Equal(5000000, receivedTotal);
if (GuaranteedSendOrdering)
{
Assert.Equal(sendData, receiveBuffer);
}
}
}
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(LoopbacksAndBuffers))]
public void SendRecvPollSync_TcpListener_Socket(IPAddress listenAt, bool pollBeforeOperation)
{
const int BytesToSend = 123456;
const int ListenBacklog = 1;
const int TestTimeout = 30000;
var listener = new TcpListener(listenAt, 0);
listener.Start(ListenBacklog);
try
{
int bytesReceived = 0;
var receivedChecksum = new Fletcher32();
Task serverTask = Task.Run(async () =>
{
using (Socket remote = await listener.AcceptSocketAsync())
{
var recvBuffer = new byte[256];
while (true)
{
if (pollBeforeOperation)
{
Assert.True(remote.Poll(-1, SelectMode.SelectRead), "Read poll before completion should have succeeded");
}
int received = remote.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None);
if (received == 0)
{
Assert.True(remote.Poll(0, SelectMode.SelectRead), "Read poll after completion should have succeeded");
break;
}
bytesReceived += received;
receivedChecksum.Add(recvBuffer, 0, received);
}
}
});
int bytesSent = 0;
var sentChecksum = new Fletcher32();
Task clientTask = Task.Run(async () =>
{
var clientEndpoint = (IPEndPoint)listener.LocalEndpoint;
using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
await ConnectAsync(client, clientEndpoint);
if (pollBeforeOperation)
{
Assert.False(client.Poll(TestTimeout, SelectMode.SelectRead), "Expected writer's read poll to fail after timeout");
}
var random = new Random();
var sendBuffer = new byte[512];
for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent)
{
random.NextBytes(sendBuffer);
if (pollBeforeOperation)
{
Assert.True(client.Poll(-1, SelectMode.SelectWrite), "Write poll should have succeeded");
}
sent = client.Send(sendBuffer, 0, Math.Min(sendBuffer.Length, remaining), SocketFlags.None);
bytesSent += sent;
sentChecksum.Add(sendBuffer, 0, sent);
}
}
});
Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout), "Wait timed out");
Assert.Equal(bytesSent, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
}
finally
{
listener.Stop();
}
}
[Fact]
public async Task SendRecv_0ByteReceive_Success()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = AcceptAsync(listener);
await Task.WhenAll(
acceptTask,
ConnectAsync(client, new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
for (int i = 0; i < 3; i++)
{
// Have the client do a 0-byte receive. No data is available, so this should pend.
Task<int> receive = ReceiveAsync(client, new ArraySegment<byte>(Array.Empty<byte>()));
Assert.False(receive.IsCompleted);
Assert.Equal(0, client.Available);
// Have the server send 1 byte to the client.
Assert.Equal(1, server.Send(new byte[1], 0, 1, SocketFlags.None));
Assert.Equal(0, server.Available);
// The client should now wake up, getting 0 bytes with 1 byte available.
Assert.Equal(0, await receive);
Assert.Equal(1, client.Available);
// We should be able to do another 0-byte receive that completes immediateliy
Assert.Equal(0, await ReceiveAsync(client, new ArraySegment<byte>(new byte[1], 0, 0)));
Assert.Equal(1, client.Available);
// Then receive the byte
Assert.Equal(1, await ReceiveAsync(client, new ArraySegment<byte>(new byte[1])));
Assert.Equal(0, client.Available);
}
}
}
}
[Theory]
[InlineData(false, 1)]
[InlineData(true, 1)]
public async Task SendRecv_BlockingNonBlocking_LingerTimeout_Success(bool blocking, int lingerTimeout)
{
if (UsesSync) return;
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
client.Blocking = blocking;
listener.Blocking = blocking;
client.LingerState = new LingerOption(true, lingerTimeout);
listener.LingerState = new LingerOption(true, lingerTimeout);
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = AcceptAsync(listener);
await Task.WhenAll(
acceptTask,
ConnectAsync(client, new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
server.Blocking = blocking;
server.LingerState = new LingerOption(true, lingerTimeout);
Task<int> receive = ReceiveAsync(client, new ArraySegment<byte>(new byte[1]));
Assert.Equal(1, await SendAsync(server, new ArraySegment<byte>(new byte[1])));
Assert.Equal(1, await receive);
}
}
}
[Fact]
[PlatformSpecific(~TestPlatforms.OSX)] // SendBufferSize, ReceiveBufferSize = 0 not supported on OSX.
public async Task SendRecv_NoBuffering_Success()
{
if (UsesSync) return;
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = AcceptAsync(listener);
await Task.WhenAll(
acceptTask,
ConnectAsync(client, new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
client.SendBufferSize = 0;
server.ReceiveBufferSize = 0;
var sendBuffer = new byte[10000];
Task sendTask = SendAsync(client, new ArraySegment<byte>(sendBuffer));
int totalReceived = 0;
var receiveBuffer = new ArraySegment<byte>(new byte[4096]);
while (totalReceived < sendBuffer.Length)
{
int received = await ReceiveAsync(server, receiveBuffer);
if (received <= 0) break;
totalReceived += received;
}
Assert.Equal(sendBuffer.Length, totalReceived);
await sendTask;
}
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task SendRecv_DisposeDuringPendingReceive_ThrowsSocketException()
{
if (UsesSync) return; // if sync, can't guarantee call will have been initiated by time of disposal
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Task<Socket> acceptTask = AcceptAsync(listener);
await Task.WhenAll(
acceptTask,
ConnectAsync(client, new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)));
using (Socket server = await acceptTask)
{
Task receiveTask = ReceiveAsync(client, new ArraySegment<byte>(new byte[1]));
Assert.False(receiveTask.IsCompleted, "Receive should be pending");
client.Dispose();
if (DisposeDuringOperationResultsInDisposedException)
{
await Assert.ThrowsAsync<ObjectDisposedException>(() => receiveTask);
}
else
{
var se = await Assert.ThrowsAsync<SocketException>(() => receiveTask);
Assert.True(
se.SocketErrorCode == SocketError.OperationAborted || se.SocketErrorCode == SocketError.ConnectionAborted,
$"Expected {nameof(SocketError.OperationAborted)} or {nameof(SocketError.ConnectionAborted)}, got {se.SocketErrorCode}");
}
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX)]
public void SocketSendReceiveBufferSize_SetZero_ThrowsSocketException()
{
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
SocketException e;
e = Assert.Throws<SocketException>(() => socket.SendBufferSize = 0);
Assert.Equal(e.SocketErrorCode, SocketError.InvalidArgument);
e = Assert.Throws<SocketException>(() => socket.ReceiveBufferSize = 0);
Assert.Equal(e.SocketErrorCode, SocketError.InvalidArgument);
}
}
}
public sealed class SendReceiveUdpClient : MemberDatas
{
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(Loopbacks))]
public void SendToRecvFromAsync_Datagram_UDP_UdpClient(IPAddress loopbackAddress)
{
IPAddress leftAddress = loopbackAddress, rightAddress = loopbackAddress;
// TODO #5185: harden against packet loss
const int DatagramSize = 256;
const int DatagramsToSend = 256;
const int AckTimeout = 1000;
const int TestTimeout = 30000;
using (var left = new UdpClient(new IPEndPoint(leftAddress, 0)))
using (var right = new UdpClient(new IPEndPoint(rightAddress, 0)))
{
var leftEndpoint = (IPEndPoint)left.Client.LocalEndPoint;
var rightEndpoint = (IPEndPoint)right.Client.LocalEndPoint;
var receiverAck = new ManualResetEventSlim();
var senderAck = new ManualResetEventSlim();
var receivedChecksums = new uint?[DatagramsToSend];
int receivedDatagrams = 0;
Task receiverTask = Task.Run(async () =>
{
for (; receivedDatagrams < DatagramsToSend; receivedDatagrams++)
{
UdpReceiveResult result = await left.ReceiveAsync();
receiverAck.Set();
Assert.True(senderAck.Wait(AckTimeout));
senderAck.Reset();
Assert.Equal(DatagramSize, result.Buffer.Length);
Assert.Equal(rightEndpoint, result.RemoteEndPoint);
int datagramId = (int)result.Buffer[0];
Assert.Null(receivedChecksums[datagramId]);
receivedChecksums[datagramId] = Fletcher32.Checksum(result.Buffer, 0, result.Buffer.Length);
}
});
var sentChecksums = new uint[DatagramsToSend];
int sentDatagrams = 0;
Task senderTask = Task.Run(async () =>
{
var random = new Random();
var sendBuffer = new byte[DatagramSize];
for (; sentDatagrams < DatagramsToSend; sentDatagrams++)
{
random.NextBytes(sendBuffer);
sendBuffer[0] = (byte)sentDatagrams;
int sent = await right.SendAsync(sendBuffer, DatagramSize, leftEndpoint);
Assert.True(receiverAck.Wait(AckTimeout));
receiverAck.Reset();
senderAck.Set();
Assert.Equal(DatagramSize, sent);
sentChecksums[sentDatagrams] = Fletcher32.Checksum(sendBuffer, 0, sent);
}
});
Assert.True(Task.WaitAll(new[] { receiverTask, senderTask }, TestTimeout));
for (int i = 0; i < DatagramsToSend; i++)
{
Assert.NotNull(receivedChecksums[i]);
Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]);
}
}
}
}
public sealed class SendReceiveListener : MemberDatas
{
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(Loopbacks))]
public void SendRecvAsync_TcpListener_TcpClient(IPAddress listenAt)
{
const int BytesToSend = 123456;
const int ListenBacklog = 1;
const int LingerTime = 10;
const int TestTimeout = 30000;
var listener = new TcpListener(listenAt, 0);
listener.Start(ListenBacklog);
int bytesReceived = 0;
var receivedChecksum = new Fletcher32();
Task serverTask = Task.Run(async () =>
{
using (TcpClient remote = await listener.AcceptTcpClientAsync())
using (NetworkStream stream = remote.GetStream())
{
var recvBuffer = new byte[256];
for (;;)
{
int received = await stream.ReadAsync(recvBuffer, 0, recvBuffer.Length);
if (received == 0)
{
break;
}
bytesReceived += received;
receivedChecksum.Add(recvBuffer, 0, received);
}
}
});
int bytesSent = 0;
var sentChecksum = new Fletcher32();
Task clientTask = Task.Run(async () =>
{
var clientEndpoint = (IPEndPoint)listener.LocalEndpoint;
using (var client = new TcpClient(clientEndpoint.AddressFamily))
{
await client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port);
using (NetworkStream stream = client.GetStream())
{
var random = new Random();
var sendBuffer = new byte[512];
for (int remaining = BytesToSend, sent = 0; remaining > 0; remaining -= sent)
{
random.NextBytes(sendBuffer);
sent = Math.Min(sendBuffer.Length, remaining);
await stream.WriteAsync(sendBuffer, 0, sent);
bytesSent += sent;
sentChecksum.Add(sendBuffer, 0, sent);
}
client.LingerState = new LingerOption(true, LingerTime);
}
}
});
Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout),
$"Time out waiting for serverTask ({serverTask.Status}) and clientTask ({clientTask.Status})");
Assert.Equal(bytesSent, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
}
}
public sealed class SendReceiveSync : SendReceive
{
public SendReceiveSync(ITestOutputHelper output) : base(output) { }
public override Task<Socket> AcceptAsync(Socket s) =>
Task.Run(() => s.Accept());
public override Task ConnectAsync(Socket s, EndPoint endPoint) =>
Task.Run(() => s.Connect(endPoint));
public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) =>
Task.Run(() => s.Receive(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None));
public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
Task.Run(() => s.Receive(bufferList, SocketFlags.None));
public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
Task.Run(() =>
{
int received = s.ReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, ref endPoint);
return new SocketReceiveFromResult
{
ReceivedBytes = received,
RemoteEndPoint = endPoint
};
});
public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) =>
Task.Run(() => s.Send(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None));
public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
Task.Run(() => s.Send(bufferList, SocketFlags.None));
public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
Task.Run(() => s.SendTo(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, endPoint));
public override bool GuaranteedSendOrdering => false;
public override bool UsesSync => true;
}
public sealed class SendReceiveApm : SendReceive
{
public SendReceiveApm(ITestOutputHelper output) : base(output) { }
public override bool DisposeDuringOperationResultsInDisposedException => true;
public override Task<Socket> AcceptAsync(Socket s) =>
Task.Factory.FromAsync(s.BeginAccept, s.EndAccept, null);
public override Task ConnectAsync(Socket s, EndPoint endPoint) =>
Task.Factory.FromAsync(s.BeginConnect, s.EndConnect, endPoint, null);
public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) =>
Task.Factory.FromAsync((callback, state) =>
s.BeginReceive(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, callback, state),
s.EndReceive, null);
public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
Task.Factory.FromAsync(s.BeginReceive, s.EndReceive, bufferList, SocketFlags.None, null);
public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint)
{
var tcs = new TaskCompletionSource<SocketReceiveFromResult>();
s.BeginReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, ref endPoint, iar =>
{
try
{
int receivedBytes = s.EndReceiveFrom(iar, ref endPoint);
tcs.TrySetResult(new SocketReceiveFromResult
{
ReceivedBytes = receivedBytes,
RemoteEndPoint = endPoint
});
}
catch (Exception e) { tcs.TrySetException(e); }
}, null);
return tcs.Task;
}
public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) =>
Task.Factory.FromAsync((callback, state) =>
s.BeginSend(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, callback, state),
s.EndSend, null);
public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
Task.Factory.FromAsync(s.BeginSend, s.EndSend, bufferList, SocketFlags.None, null);
public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
Task.Factory.FromAsync(
(callback, state) => s.BeginSendTo(buffer.Array, buffer.Offset, buffer.Count, SocketFlags.None, endPoint, callback, state),
s.EndSendTo, null);
}
public sealed class SendReceiveTask : SendReceive
{
public SendReceiveTask(ITestOutputHelper output) : base(output) { }
public override bool DisposeDuringOperationResultsInDisposedException =>
PlatformDetection.IsFullFramework; // due to SocketTaskExtensions.netfx implementation wrapping APM rather than EAP
public override Task<Socket> AcceptAsync(Socket s) =>
s.AcceptAsync();
public override Task ConnectAsync(Socket s, EndPoint endPoint) =>
s.ConnectAsync(endPoint);
public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) =>
s.ReceiveAsync(buffer, SocketFlags.None);
public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
s.ReceiveAsync(bufferList, SocketFlags.None);
public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
s.ReceiveFromAsync(buffer, SocketFlags.None, endPoint);
public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) =>
s.SendAsync(buffer, SocketFlags.None);
public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
s.SendAsync(bufferList, SocketFlags.None);
public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
s.SendToAsync(buffer, SocketFlags.None, endPoint);
}
public sealed class SendReceiveEap : SendReceive
{
public SendReceiveEap(ITestOutputHelper output) : base(output) { }
public override bool ValidatesArrayArguments => false;
public override Task<Socket> AcceptAsync(Socket s) =>
InvokeAsync(s, e => e.AcceptSocket, e => s.AcceptAsync(e));
public override Task ConnectAsync(Socket s, EndPoint endPoint) =>
InvokeAsync(s, e => true, e =>
{
e.RemoteEndPoint = endPoint;
return s.ConnectAsync(e);
});
public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
return s.ReceiveAsync(e);
});
public override Task<int> ReceiveAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.BufferList = bufferList;
return s.ReceiveAsync(e);
});
public override Task<SocketReceiveFromResult> ReceiveFromAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
InvokeAsync(s, e => new SocketReceiveFromResult { ReceivedBytes = e.BytesTransferred, RemoteEndPoint = e.RemoteEndPoint }, e =>
{
e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
e.RemoteEndPoint = endPoint;
return s.ReceiveFromAsync(e);
});
public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
return s.SendAsync(e);
});
public override Task<int> SendAsync(Socket s, IList<ArraySegment<byte>> bufferList) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.BufferList = bufferList;
return s.SendAsync(e);
});
public override Task<int> SendToAsync(Socket s, ArraySegment<byte> buffer, EndPoint endPoint) =>
InvokeAsync(s, e => e.BytesTransferred, e =>
{
e.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
e.RemoteEndPoint = endPoint;
return s.SendToAsync(e);
});
private static Task<TResult> InvokeAsync<TResult>(
Socket s,
Func<SocketAsyncEventArgs, TResult> getResult,
Func<SocketAsyncEventArgs, bool> invoke)
{
var tcs = new TaskCompletionSource<TResult>();
var saea = new SocketAsyncEventArgs();
EventHandler<SocketAsyncEventArgs> handler = (_, e) =>
{
if (e.SocketError == SocketError.Success) tcs.SetResult(getResult(e));
else tcs.SetException(new SocketException((int)e.SocketError));
saea.Dispose();
};
saea.Completed += handler;
if (!invoke(saea)) handler(s, saea);
return tcs.Task;
}
[Theory]
[InlineData(1, -1, 0)] // offset low
[InlineData(1, 2, 0)] // offset high
[InlineData(1, 0, -1)] // count low
[InlineData(1, 1, 2)] // count high
public void BufferList_InvalidArguments_Throws(int length, int offset, int count)
{
using (var e = new SocketAsyncEventArgs())
{
ArraySegment<byte> invalidBuffer = new FakeArraySegment { Array = new byte[length], Offset = offset, Count = count }.ToActual();
Assert.Throws<ArgumentOutOfRangeException>(() => e.BufferList = new List<ArraySegment<byte>> { invalidBuffer });
ArraySegment<byte> validBuffer = new ArraySegment<byte>(new byte[1]);
Assert.Throws<ArgumentOutOfRangeException>(() => e.BufferList = new List<ArraySegment<byte>> { validBuffer, invalidBuffer });
}
}
}
public abstract class MemberDatas
{
public static readonly object[][] Loopbacks = new[]
{
new object[] { IPAddress.Loopback },
new object[] { IPAddress.IPv6Loopback },
};
public static readonly object[][] LoopbacksAndBuffers = new object[][]
{
new object[] { IPAddress.IPv6Loopback, true },
new object[] { IPAddress.IPv6Loopback, false },
new object[] { IPAddress.Loopback, true },
new object[] { IPAddress.Loopback, false },
};
}
internal struct FakeArraySegment
{
public byte[] Array;
public int Offset;
public int Count;
public ArraySegment<byte> ToActual()
{
ArraySegmentWrapper wrapper = default(ArraySegmentWrapper);
wrapper.Fake = this;
return wrapper.Actual;
}
}
[StructLayout(LayoutKind.Explicit)]
internal struct ArraySegmentWrapper
{
[FieldOffset(0)] public ArraySegment<byte> Actual;
[FieldOffset(0)] public FakeArraySegment Fake;
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Text;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using AutoMapper;
using ClientDependency.Core;
using Examine.LuceneEngine;
using Examine.LuceneEngine.Providers;
using Newtonsoft.Json;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Services;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Mvc;
using System.Linq;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models;
using Umbraco.Web.WebApi.Filters;
using umbraco.cms.businesslogic.packager;
using Constants = Umbraco.Core.Constants;
using Examine;
using Examine.LuceneEngine.SearchCriteria;
using Examine.SearchCriteria;
using Umbraco.Web.Dynamics;
using umbraco;
using System.Text.RegularExpressions;
using Umbraco.Core.Xml;
namespace Umbraco.Web.Editors
{
/// <summary>
/// The API controller used for getting entity objects, basic name, icon, id representation of umbraco objects that are based on CMSNode
/// </summary>
/// <remarks>
/// Some objects such as macros are not based on CMSNode
/// </remarks>
[EntityControllerConfiguration]
[PluginController("UmbracoApi")]
public class EntityController : UmbracoAuthorizedJsonController
{
/// <summary>
/// Searches for results based on the entity type
/// </summary>
/// <param name="query"></param>
/// <param name="type"></param>
/// <param name="searchFrom">
/// A starting point for the search, generally a node id, but for members this is a member type alias
/// </param>
/// <returns></returns>
[HttpGet]
public IEnumerable<EntityBasic> Search(string query, UmbracoEntityTypes type, string searchFrom = null)
{
//TODO: Should we restrict search results based on what app the user has access to?
// - Theoretically you shouldn't be able to see member data if you don't have access to members right?
if (string.IsNullOrEmpty(query))
return Enumerable.Empty<EntityBasic>();
return ExamineSearch(query, type, searchFrom);
}
/// <summary>
/// Searches for all content that the user is allowed to see (based on their allowed sections)
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
/// <remarks>
/// Even though a normal entity search will allow any user to search on a entity type that they may not have access to edit, we need
/// to filter these results to the sections they are allowed to edit since this search function is explicitly for the global search
/// so if we showed entities that they weren't allowed to edit they would get errors when clicking on the result.
///
/// The reason a user is allowed to search individual entity types that they are not allowed to edit is because those search
/// methods might be used in things like pickers in the content editor.
/// </remarks>
[HttpGet]
public IEnumerable<EntityTypeSearchResult> SearchAll(string query)
{
if (string.IsNullOrEmpty(query))
return Enumerable.Empty<EntityTypeSearchResult>();
var allowedSections = Security.CurrentUser.AllowedSections.ToArray();
var result = new List<EntityTypeSearchResult>();
if (allowedSections.InvariantContains(Constants.Applications.Content))
{
result.Add(new EntityTypeSearchResult
{
Results = ExamineSearch(query, UmbracoEntityTypes.Document),
EntityType = UmbracoEntityTypes.Document.ToString()
});
}
if (allowedSections.InvariantContains(Constants.Applications.Media))
{
result.Add(new EntityTypeSearchResult
{
Results = ExamineSearch(query, UmbracoEntityTypes.Media),
EntityType = UmbracoEntityTypes.Media.ToString()
});
}
if (allowedSections.InvariantContains(Constants.Applications.Members))
{
result.Add(new EntityTypeSearchResult
{
Results = ExamineSearch(query, UmbracoEntityTypes.Member),
EntityType = UmbracoEntityTypes.Member.ToString()
});
}
return result;
}
/// <summary>
/// Gets the path for a given node ID
/// </summary>
/// <param name="id"></param>
/// <param name="type"></param>
/// <returns></returns>
public IEnumerable<int> GetPath(int id, UmbracoEntityTypes type)
{
var foundContent = GetResultForId(id, type);
return foundContent.Path.Split(new[] {','}, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse);
}
/// <summary>
/// Gets an entity by it's unique id if the entity supports that
/// </summary>
/// <param name="id"></param>
/// <param name="type"></param>
/// <returns></returns>
public EntityBasic GetByKey(Guid id, UmbracoEntityTypes type)
{
return GetResultForKey(id, type);
}
/// <summary>
/// Gets an entity by a xpath query
/// </summary>
/// <param name="query"></param>
/// <param name="nodeContextId"></param>
/// <param name="type"></param>
/// <returns></returns>
public EntityBasic GetByQuery(string query, int nodeContextId, UmbracoEntityTypes type)
{
//TODO: Rename this!!! It's a bit misleading, it should be GetByXPath
if (type != UmbracoEntityTypes.Document)
throw new ArgumentException("Get by query is only compatible with enitities of type Document");
var q = ParseXPathQuery(query, nodeContextId);
var node = Umbraco.TypedContentSingleAtXPath(q);
if (node == null)
return null;
return GetById(node.Id, type);
}
//PP: wip in progress on the query parser
private string ParseXPathQuery(string query, int id)
{
return UmbracoXPathPathSyntaxParser.ParseXPathQuery(
xpathExpression: query,
nodeContextId: id,
getPath: nodeid =>
{
var ent = Services.EntityService.Get(nodeid);
return ent.Path.Split(',').Reverse();
},
publishedContentExists: i => Umbraco.TypedContent(i) != null);
}
public EntityBasic GetById(int id, UmbracoEntityTypes type)
{
return GetResultForId(id, type);
}
public IEnumerable<EntityBasic> GetByIds([FromUri]int[] ids, UmbracoEntityTypes type)
{
if (ids == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return GetResultForIds(ids, type);
}
public IEnumerable<EntityBasic> GetByKeys([FromUri]Guid[] ids, UmbracoEntityTypes type)
{
if (ids == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return GetResultForKeys(ids, type);
}
public IEnumerable<EntityBasic> GetChildren(int id, UmbracoEntityTypes type)
{
return GetResultForChildren(id, type);
}
public IEnumerable<EntityBasic> GetAncestors(int id, UmbracoEntityTypes type)
{
return GetResultForAncestors(id, type);
}
public IEnumerable<EntityBasic> GetAll(UmbracoEntityTypes type, string postFilter, [FromUri]IDictionary<string, object> postFilterParams)
{
return GetResultForAll(type, postFilter, postFilterParams);
}
/// <summary>
/// Searches for results based on the entity type
/// </summary>
/// <param name="query"></param>
/// <param name="entityType"></param>
/// <param name="searchFrom">
/// A starting point for the search, generally a node id, but for members this is a member type alias
/// </param>
/// <returns></returns>
private IEnumerable<EntityBasic> ExamineSearch(string query, UmbracoEntityTypes entityType, string searchFrom = null)
{
var sb = new StringBuilder();
string type;
var searcher = Constants.Examine.InternalSearcher;
var fields = new[] { "id", "__NodeId" };
//TODO: WE should really just allow passing in a lucene raw query
switch (entityType)
{
case UmbracoEntityTypes.Member:
searcher = Constants.Examine.InternalMemberSearcher;
type = "member";
fields = new[] { "id", "__NodeId", "email", "loginName"};
if (searchFrom != null && searchFrom != Constants.Conventions.MemberTypes.AllMembersListId && searchFrom.Trim() != "-1")
{
sb.Append("+__NodeTypeAlias:");
sb.Append(searchFrom);
sb.Append(" ");
}
break;
case UmbracoEntityTypes.Media:
type = "media";
var mediaSearchFrom = int.MinValue;
if (Security.CurrentUser.StartMediaId > 0 ||
//if searchFrom is specified and it is greater than 0
(searchFrom != null && int.TryParse(searchFrom, out mediaSearchFrom) && mediaSearchFrom > 0))
{
sb.Append("+__Path: \\-1*\\,");
sb.Append(mediaSearchFrom > 0
? mediaSearchFrom.ToString(CultureInfo.InvariantCulture)
: Security.CurrentUser.StartMediaId.ToString(CultureInfo.InvariantCulture));
sb.Append("\\,* ");
}
break;
case UmbracoEntityTypes.Document:
type = "content";
var contentSearchFrom = int.MinValue;
if (Security.CurrentUser.StartContentId > 0 ||
//if searchFrom is specified and it is greater than 0
(searchFrom != null && int.TryParse(searchFrom, out contentSearchFrom) && contentSearchFrom > 0))
{
sb.Append("+__Path: \\-1*\\,");
sb.Append(contentSearchFrom > 0
? contentSearchFrom.ToString(CultureInfo.InvariantCulture)
: Security.CurrentUser.StartContentId.ToString(CultureInfo.InvariantCulture));
sb.Append("\\,* ");
}
break;
default:
throw new NotSupportedException("The " + typeof(EntityController) + " currently does not support searching against object type " + entityType);
}
var internalSearcher = ExamineManager.Instance.SearchProviderCollection[searcher];
//build a lucene query:
// the __nodeName will be boosted 10x without wildcards
// then __nodeName will be matched normally with wildcards
// the rest will be normal without wildcards
//check if text is surrounded by single or double quotes, if so, then exact match
var surroundedByQuotes = Regex.IsMatch(query, "^\".*?\"$")
|| Regex.IsMatch(query, "^\'.*?\'$");
if (surroundedByQuotes)
{
//strip quotes, escape string, the replace again
query = query.Trim(new[] { '\"', '\'' });
query = Lucene.Net.QueryParsers.QueryParser.Escape(query);
if (query.IsNullOrWhiteSpace())
{
return new List<EntityBasic>();
}
//add back the surrounding quotes
query = string.Format("{0}{1}{0}", "\"", query);
//node name exactly boost x 10
sb.Append("+(__nodeName: (");
sb.Append(query.ToLower());
sb.Append(")^10.0 ");
foreach (var f in fields)
{
//additional fields normally
sb.Append(f);
sb.Append(": (");
sb.Append(query);
sb.Append(") ");
}
}
else
{
if (query.Trim(new[] { '\"', '\'' }).IsNullOrWhiteSpace())
{
return new List<EntityBasic>();
}
query = Lucene.Net.QueryParsers.QueryParser.Escape(query);
var querywords = query.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
//node name exactly boost x 10
sb.Append("+(__nodeName:");
sb.Append("\"");
sb.Append(query.ToLower());
sb.Append("\"");
sb.Append("^10.0 ");
//node name normally with wildcards
sb.Append(" __nodeName:");
sb.Append("(");
foreach (var w in querywords)
{
sb.Append(w.ToLower());
sb.Append("* ");
}
sb.Append(") ");
foreach (var f in fields)
{
//additional fields normally
sb.Append(f);
sb.Append(":");
sb.Append("(");
foreach (var w in querywords)
{
sb.Append(w.ToLower());
sb.Append("* ");
}
sb.Append(")");
sb.Append(" ");
}
}
//must match index type
sb.Append(") +__IndexType:");
sb.Append(type);
var raw = internalSearcher.CreateSearchCriteria().RawQuery(sb.ToString());
//limit results to 200 to avoid huge over processing (CPU)
var result = internalSearcher.Search(raw, 200);
switch (entityType)
{
case UmbracoEntityTypes.Member:
return MemberFromSearchResults(result);
case UmbracoEntityTypes.Media:
return MediaFromSearchResults(result);
case UmbracoEntityTypes.Document:
return ContentFromSearchResults(result);
default:
throw new NotSupportedException("The " + typeof(EntityController) + " currently does not support searching against object type " + entityType);
}
}
/// <summary>
/// Returns a collection of entities for media based on search results
/// </summary>
/// <param name="results"></param>
/// <returns></returns>
private IEnumerable<EntityBasic> MemberFromSearchResults(ISearchResults results)
{
var mapped = Mapper.Map<IEnumerable<EntityBasic>>(results).ToArray();
//add additional data
foreach (var m in mapped)
{
//if no icon could be mapped, it will be set to document, so change it to picture
if (m.Icon == "icon-document")
{
m.Icon = "icon-user";
}
var searchResult = results.First(x => x.Id.ToInvariantString() == m.Id.ToString());
if (searchResult.Fields.ContainsKey("email") && searchResult.Fields["email"] != null)
{
m.AdditionalData["Email"] = results.First(x => x.Id.ToInvariantString() == m.Id.ToString()).Fields["email"];
}
if (searchResult.Fields.ContainsKey("__key") && searchResult.Fields["__key"] != null)
{
Guid key;
if (Guid.TryParse(searchResult.Fields["__key"], out key))
{
m.Key = key;
}
}
}
return mapped;
}
/// <summary>
/// Returns a collection of entities for media based on search results
/// </summary>
/// <param name="results"></param>
/// <returns></returns>
private IEnumerable<EntityBasic> MediaFromSearchResults(ISearchResults results)
{
var mapped = Mapper.Map<IEnumerable<EntityBasic>>(results).ToArray();
//add additional data
foreach (var m in mapped)
{
//if no icon could be mapped, it will be set to document, so change it to picture
if (m.Icon == "icon-document")
{
m.Icon = "icon-picture";
}
}
return mapped;
}
/// <summary>
/// Returns a collection of entities for content based on search results
/// </summary>
/// <param name="results"></param>
/// <returns></returns>
private IEnumerable<EntityBasic> ContentFromSearchResults(ISearchResults results)
{
var mapped = Mapper.Map<ISearchResults, IEnumerable<EntityBasic>>(results).ToArray();
//add additional data
foreach (var m in mapped)
{
var intId = m.Id.TryConvertTo<int>();
if (intId.Success)
{
m.AdditionalData["Url"] = Umbraco.NiceUrl(intId.Result);
}
}
return mapped;
}
private IEnumerable<EntityBasic> GetResultForChildren(int id, UmbracoEntityTypes entityType)
{
var objectType = ConvertToObjectType(entityType);
if (objectType.HasValue)
{
//TODO: Need to check for Object types that support hierarchic here, some might not.
return Services.EntityService.GetChildren(id, objectType.Value)
.WhereNotNull()
.Select(Mapper.Map<EntityBasic>);
}
//now we need to convert the unknown ones
switch (entityType)
{
case UmbracoEntityTypes.Domain:
case UmbracoEntityTypes.Language:
case UmbracoEntityTypes.User:
case UmbracoEntityTypes.Macro:
default:
throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType);
}
}
private IEnumerable<EntityBasic> GetResultForAncestors(int id, UmbracoEntityTypes entityType)
{
var objectType = ConvertToObjectType(entityType);
if (objectType.HasValue)
{
//TODO: Need to check for Object types that support hierarchic here, some might not.
var ids = Services.EntityService.Get(id).Path.Split(',').Select(int.Parse).Distinct().ToArray();
return Services.EntityService.GetAll(objectType.Value, ids)
.WhereNotNull()
.OrderBy(x => x.Level)
.Select(Mapper.Map<EntityBasic>);
}
//now we need to convert the unknown ones
switch (entityType)
{
case UmbracoEntityTypes.PropertyType:
case UmbracoEntityTypes.PropertyGroup:
case UmbracoEntityTypes.Domain:
case UmbracoEntityTypes.Language:
case UmbracoEntityTypes.User:
case UmbracoEntityTypes.Macro:
default:
throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType);
}
}
/// <summary>
/// Gets the result for the entity list based on the type
/// </summary>
/// <param name="entityType"></param>
/// <param name="postFilter">A string where filter that will filter the results dynamically with linq - optional</param>
/// <param name="postFilterParams">the parameters to fill in the string where filter - optional</param>
/// <returns></returns>
private IEnumerable<EntityBasic> GetResultForAll(UmbracoEntityTypes entityType, string postFilter = null, IDictionary<string, object> postFilterParams = null)
{
var objectType = ConvertToObjectType(entityType);
if (objectType.HasValue)
{
//TODO: Should we order this by something ?
var entities = Services.EntityService.GetAll(objectType.Value).WhereNotNull().Select(Mapper.Map<EntityBasic>);
return ExecutePostFilter(entities, postFilter, postFilterParams);
}
//now we need to convert the unknown ones
switch (entityType)
{
case UmbracoEntityTypes.Macro:
//Get all macros from the macro service
var macros = Services.MacroService.GetAll().WhereNotNull().OrderBy(x => x.Name);
var filteredMacros = ExecutePostFilter(macros, postFilter, postFilterParams);
return filteredMacros.Select(Mapper.Map<EntityBasic>);
case UmbracoEntityTypes.PropertyType:
//get all document types, then combine all property types into one list
var propertyTypes = Services.ContentTypeService.GetAllContentTypes().Cast<IContentTypeComposition>()
.Concat(Services.ContentTypeService.GetAllMediaTypes())
.ToArray()
.SelectMany(x => x.PropertyTypes)
.DistinctBy(composition => composition.Alias);
var filteredPropertyTypes = ExecutePostFilter(propertyTypes, postFilter, postFilterParams);
return Mapper.Map<IEnumerable<PropertyType>, IEnumerable<EntityBasic>>(filteredPropertyTypes);
case UmbracoEntityTypes.PropertyGroup:
//get all document types, then combine all property types into one list
var propertyGroups = Services.ContentTypeService.GetAllContentTypes().Cast<IContentTypeComposition>()
.Concat(Services.ContentTypeService.GetAllMediaTypes())
.ToArray()
.SelectMany(x => x.PropertyGroups)
.DistinctBy(composition => composition.Name);
var filteredpropertyGroups = ExecutePostFilter(propertyGroups, postFilter, postFilterParams);
return Mapper.Map<IEnumerable<PropertyGroup>, IEnumerable<EntityBasic>>(filteredpropertyGroups);
case UmbracoEntityTypes.User:
int total;
var users = Services.UserService.GetAll(0, int.MaxValue, out total);
var filteredUsers = ExecutePostFilter(users, postFilter, postFilterParams);
return Mapper.Map<IEnumerable<IUser>, IEnumerable<EntityBasic>>(filteredUsers);
case UmbracoEntityTypes.Domain:
case UmbracoEntityTypes.Language:
default:
throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType);
}
}
private IEnumerable<EntityBasic> GetResultForKeys(IEnumerable<Guid> keys, UmbracoEntityTypes entityType)
{
var keysArray = keys.ToArray();
if (keysArray.Any() == false) return Enumerable.Empty<EntityBasic>();
var objectType = ConvertToObjectType(entityType);
if (objectType.HasValue)
{
var entities = Services.EntityService.GetAll(objectType.Value, keysArray)
.WhereNotNull()
.Select(Mapper.Map<EntityBasic>);
// entities are in "some" order, put them back in order
var xref = entities.ToDictionary(x => x.Id);
var result = keysArray.Select(x => xref.ContainsKey(x) ? xref[x] : null).Where(x => x != null);
return result;
}
//now we need to convert the unknown ones
switch (entityType)
{
case UmbracoEntityTypes.PropertyType:
case UmbracoEntityTypes.PropertyGroup:
case UmbracoEntityTypes.Domain:
case UmbracoEntityTypes.Language:
case UmbracoEntityTypes.User:
case UmbracoEntityTypes.Macro:
default:
throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType);
}
}
private IEnumerable<EntityBasic> GetResultForIds(IEnumerable<int> ids, UmbracoEntityTypes entityType)
{
var idsArray = ids.ToArray();
if (idsArray.Any() == false) return Enumerable.Empty<EntityBasic>();
var objectType = ConvertToObjectType(entityType);
if (objectType.HasValue)
{
var entities = Services.EntityService.GetAll(objectType.Value, idsArray)
.WhereNotNull()
.Select(Mapper.Map<EntityBasic>);
// entities are in "some" order, put them back in order
var xref = entities.ToDictionary(x => x.Id);
var result = idsArray.Select(x => xref.ContainsKey(x) ? xref[x] : null).Where(x => x != null);
return result;
}
//now we need to convert the unknown ones
switch (entityType)
{
case UmbracoEntityTypes.PropertyType:
case UmbracoEntityTypes.PropertyGroup:
case UmbracoEntityTypes.Domain:
case UmbracoEntityTypes.Language:
case UmbracoEntityTypes.User:
case UmbracoEntityTypes.Macro:
default:
throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType);
}
}
private EntityBasic GetResultForKey(Guid key, UmbracoEntityTypes entityType)
{
var objectType = ConvertToObjectType(entityType);
if (objectType.HasValue)
{
var found = Services.EntityService.GetByKey(key, objectType.Value);
if (found == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return Mapper.Map<EntityBasic>(found);
}
//now we need to convert the unknown ones
switch (entityType)
{
case UmbracoEntityTypes.PropertyType:
case UmbracoEntityTypes.PropertyGroup:
case UmbracoEntityTypes.Domain:
case UmbracoEntityTypes.Language:
case UmbracoEntityTypes.User:
case UmbracoEntityTypes.Macro:
default:
throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType);
}
}
private EntityBasic GetResultForId(int id, UmbracoEntityTypes entityType)
{
var objectType = ConvertToObjectType(entityType);
if (objectType.HasValue)
{
var found = Services.EntityService.Get(id, objectType.Value);
if (found == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return Mapper.Map<EntityBasic>(found);
}
//now we need to convert the unknown ones
switch (entityType)
{
case UmbracoEntityTypes.PropertyType:
case UmbracoEntityTypes.PropertyGroup:
case UmbracoEntityTypes.Domain:
case UmbracoEntityTypes.Language:
case UmbracoEntityTypes.User:
case UmbracoEntityTypes.Macro:
default:
throw new NotSupportedException("The " + typeof(EntityController) + " does not currently support data for the type " + entityType);
}
}
private static UmbracoObjectTypes? ConvertToObjectType(UmbracoEntityTypes entityType)
{
switch (entityType)
{
case UmbracoEntityTypes.Document:
return UmbracoObjectTypes.Document;
case UmbracoEntityTypes.Media:
return UmbracoObjectTypes.Media;
case UmbracoEntityTypes.MemberType:
return UmbracoObjectTypes.MediaType;
case UmbracoEntityTypes.Template:
return UmbracoObjectTypes.Template;
case UmbracoEntityTypes.MemberGroup:
return UmbracoObjectTypes.MemberGroup;
case UmbracoEntityTypes.ContentItem:
return UmbracoObjectTypes.ContentItem;
case UmbracoEntityTypes.MediaType:
return UmbracoObjectTypes.MediaType;
case UmbracoEntityTypes.DocumentType:
return UmbracoObjectTypes.DocumentType;
case UmbracoEntityTypes.Stylesheet:
return UmbracoObjectTypes.Stylesheet;
case UmbracoEntityTypes.Member:
return UmbracoObjectTypes.Member;
case UmbracoEntityTypes.DataType:
return UmbracoObjectTypes.DataType;
default:
//There is no UmbracoEntity conversion (things like Macros, Users, etc...)
return null;
}
}
/// <summary>
/// Executes the post filter against a collection of objects
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entities"></param>
/// <param name="postFilter"></param>
/// <param name="postFilterParams"></param>
/// <returns></returns>
private IEnumerable<T> ExecutePostFilter<T>(IEnumerable<T> entities, string postFilter, IDictionary<string, object> postFilterParams)
{
//if a post filter is assigned then try to execute it
if (postFilter.IsNullOrWhiteSpace() == false)
{
return postFilterParams == null
? entities.AsQueryable().Where(postFilter).ToArray()
: entities.AsQueryable().Where(postFilter, postFilterParams).ToArray();
}
return entities;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowSplitAfterSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using Akka.Streams.Dsl;
using Akka.Streams.Implementation;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using FluentAssertions;
using Reactive.Streams;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable InvokeAsExtensionMethod
// ReSharper disable UnusedMember.Local
namespace Akka.Streams.Tests.Dsl
{
public class FlowSplitAfterSpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public FlowSplitAfterSpec(ITestOutputHelper helper) : base(helper)
{
var settings =
ActorMaterializerSettings.Create(Sys)
.WithInputBuffer(2, 2)
.WithSubscriptionTimeoutSettings(
new StreamSubscriptionTimeoutSettings(
StreamSubscriptionTimeoutTerminationMode.CancelTermination, TimeSpan.FromSeconds(1)));
Materializer = ActorMaterializer.Create(Sys, settings);
}
private sealed class StreamPuppet
{
private readonly TestSubscriber.ManualProbe<int> _probe;
private readonly ISubscription _subscription;
public StreamPuppet(IPublisher<int> p, TestKitBase kit)
{
_probe = kit.CreateManualSubscriberProbe<int>();
p.Subscribe(_probe);
_subscription = _probe.ExpectSubscription();
}
public void Request(int demand) => _subscription.Request(demand);
public void ExpectNext(int element) => _probe.ExpectNext(element);
public void ExpectNoMsg(TimeSpan max) => _probe.ExpectNoMsg(max);
public void ExpectComplete() => _probe.ExpectComplete();
public void ExpectError(Exception ex) => _probe.ExpectError().Should().Be(ex);
public void Cancel() => _subscription.Cancel();
}
private void WithSubstreamsSupport(int splitAfter = 3, int elementCount = 6,
SubstreamCancelStrategy substreamCancelStrategy = SubstreamCancelStrategy.Drain,
Action<TestSubscriber.ManualProbe<Source<int, NotUsed>>, ISubscription, Func<Source<int, NotUsed>>> run = null)
{
var source = Source.From(Enumerable.Range(1, elementCount));
var groupStream =
source.SplitAfter(substreamCancelStrategy, i => i == splitAfter)
.Lift()
.RunWith(Sink.AsPublisher<Source<int, NotUsed>>(false), Materializer);
var masterSubscriber = this.CreateManualSubscriberProbe<Source<int, NotUsed>>();
groupStream.Subscribe(masterSubscriber);
var masterSubscription = masterSubscriber.ExpectSubscription();
run?.Invoke(masterSubscriber, masterSubscription, () =>
{
masterSubscription.Request(1);
return masterSubscriber.ExpectNext();
});
}
[Fact]
public void SplitAfter_must_work_in_the_happy_case()
{
this.AssertAllStagesStopped(() =>
{
WithSubstreamsSupport(3,5,run: (masterSubscriber, masterSubscription, expectSubFlow) =>
{
var s1 = new StreamPuppet(expectSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this);
masterSubscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
s1.Request(2);
s1.ExpectNext(1);
s1.ExpectNext(2);
s1.Request(1);
s1.ExpectNext(3);
s1.Request(1);
s1.ExpectComplete();
var s2 = new StreamPuppet(expectSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this);
s2.Request(2);
s2.ExpectNext(4);
s2.ExpectNext(5);
s2.ExpectComplete();
masterSubscription.Request(1);
masterSubscriber.ExpectComplete();
});
}, Materializer);
}
[Fact]
public void SplitAfter_must_work_when_first_element_is_split_by()
{
this.AssertAllStagesStopped(() =>
{
WithSubstreamsSupport(1, 3, run: (masterSubscriber, masterSubscription, expectSubFlow) =>
{
var s1 = new StreamPuppet(expectSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this);
masterSubscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
s1.Request(3);
s1.ExpectNext(1);
s1.ExpectComplete();
var s2 = new StreamPuppet(expectSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this);
s2.Request(3);
s2.ExpectNext(2);
s2.ExpectNext(3);
s2.ExpectComplete();
masterSubscription.Request(1);
masterSubscriber.ExpectComplete();
});
}, Materializer);
}
[Fact]
public void SplitAfter_must_work_with_single_element_splits_by()
{
this.AssertAllStagesStopped(() =>
{
var task = Source.From(Enumerable.Range(1, 10))
.SplitAfter(_ => true)
.Lift()
.SelectAsync(1, s => s.RunWith(Sink.First<int>(), Materializer))
.Grouped(10)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10));
}, Materializer);
}
[Fact]
public void SplitAfter_must_support_cancelling_substreams()
{
this.AssertAllStagesStopped(() =>
{
WithSubstreamsSupport(5, 8, run: (masterSubscriber, masterSubscription, expectSubFlow) =>
{
var s1 = new StreamPuppet(expectSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this);
masterSubscription.Cancel();
s1.Request(5);
s1.ExpectNext(1);
s1.ExpectNext(2);
s1.ExpectNext(3);
s1.ExpectNext(4);
s1.ExpectNext(5);
s1.Request(1);
s1.ExpectComplete();
});
}, Materializer);
}
[Fact]
public void SplitAfter_must_fail_stream_when_SplitAfter_function_throws()
{
this.AssertAllStagesStopped(() =>
{
var publisherProbe = this.CreateManualPublisherProbe<int>();
var ex = new TestException("test");
var publisher = Source.FromPublisher(publisherProbe).SplitAfter(i =>
{
if (i == 3)
throw ex;
return i%3 == 0;
}).Lift().RunWith(Sink.AsPublisher<Source<int, NotUsed>>(false), Materializer);
var subscriber = this.CreateManualSubscriberProbe<Source<int, NotUsed>>();
publisher.Subscribe(subscriber);
var upstreamSubscription = publisherProbe.ExpectSubscription();
var downstreamSubscription = subscriber.ExpectSubscription();
downstreamSubscription.Request(100);
upstreamSubscription.SendNext(1);
var substream = subscriber.ExpectNext();
var substreamPuppet = new StreamPuppet(substream.RunWith(Sink.AsPublisher<int>(false), Materializer), this);
substreamPuppet.Request(10);
substreamPuppet.ExpectNext(1);
upstreamSubscription.SendNext(2);
substreamPuppet.ExpectNext(2);
upstreamSubscription.SendNext(3);
subscriber.ExpectError().Should().Be(ex);
substreamPuppet.ExpectError(ex);
upstreamSubscription.ExpectCancellation();
}, Materializer);
}
[Fact(Skip = "Supervision is not supported fully by GraphStages yet")]
public void SplitAfter_must_resume_stream_when_SplitAfter_function_throws()
{
this.AssertAllStagesStopped(() =>
{
}, Materializer);
}
[Fact]
public void SplitAfter_must_pass_along_early_cancellation()
{
this.AssertAllStagesStopped(() =>
{
var up = this.CreateManualPublisherProbe<int>();
var down = this.CreateManualSubscriberProbe<Source<int, NotUsed>>();
var flowSubscriber =
Source.AsSubscriber<int>()
.SplitAfter(i => i%3 == 0)
.Lift()
.To(Sink.FromSubscriber(down))
.Run(Materializer);
var downstream = down.ExpectSubscription();
downstream.Cancel();
up.Subscribe(flowSubscriber);
var upSub = up.ExpectSubscription();
upSub.ExpectCancellation();
}, Materializer);
}
[Fact]
public void SplitAfter_must_support_eager_cancellation_of_master_stream_on_cancelling_substreams()
{
this.AssertAllStagesStopped(() =>
{
WithSubstreamsSupport(5,8,SubstreamCancelStrategy.Propagate,
(masterSubscriber, masterSubscription, expectSubFlow) =>
{
var s1 = new StreamPuppet(expectSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer),
this);
s1.Cancel();
masterSubscriber.ExpectComplete();
});
}, Materializer);
}
[Fact]
public void SplitAfter_should_work_when_last_element_is_split_by() => this.AssertAllStagesStopped(() =>
{
WithSubstreamsSupport(splitAfter: 3, elementCount: 3,
run: (masterSubscriber, masterSubscription, expectSubFlow) =>
{
var s1 = new StreamPuppet(expectSubFlow()
.RunWith(Sink.AsPublisher<int>(false), Materializer), this);
masterSubscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
s1.Request(3);
s1.ExpectNext(1);
s1.ExpectNext(2);
s1.ExpectNext(3);
s1.ExpectComplete();
masterSubscription.Request(1);
masterSubscriber.ExpectComplete();
});
}, Materializer);
[Fact]
public void SplitAfter_should_fail_stream_if_substream_not_materialized_in_time() => this.AssertAllStagesStopped(() =>
{
var timeout = new StreamSubscriptionTimeoutSettings(StreamSubscriptionTimeoutTerminationMode.CancelTermination, TimeSpan.FromMilliseconds(500));
var settings = ActorMaterializerSettings.Create(Sys).WithSubscriptionTimeoutSettings(timeout);
var tightTimeoutMaterializer = ActorMaterializer.Create(Sys, settings);
var testSource = Source.Single(1).ConcatMaterialized(Source.Maybe<int>(), Keep.Left).SplitAfter(_ => true);
Action a = () =>
{
testSource.Lift().Delay(TimeSpan.FromSeconds(1)).ConcatMany(x => x)
.RunWith(Sink.Ignore<int>(), tightTimeoutMaterializer)
.Wait(TimeSpan.FromSeconds(3));
};
a.ShouldThrow<SubscriptionTimeoutException>();
}, Materializer);
// Probably covert by SplitAfter_should_work_when_last_element_is_split_by
// but we received a specific example which we want to cover too,
// see https://github.com/akkadotnet/akka.net/issues/3222
[Fact]
public void SplitAfter_should_not_create_a_subflow_when_no_element_is_left()
{
var result = new ConcurrentQueue<ImmutableList<Tuple<bool, int>>>();
Source.From(new[]
{
Tuple.Create(true, 1), Tuple.Create(true, 2), Tuple.Create(false, 0),
Tuple.Create(true, 3), Tuple.Create(true, 4), Tuple.Create(false, 0),
Tuple.Create(true, 5), Tuple.Create(false, 0)
})
.SplitAfter(t => !t.Item1)
.Where(t => t.Item1)
.Aggregate(ImmutableList.Create<Tuple<bool, int>>(), (list, b) => list.Add(b))
.To(Sink.ForEach<ImmutableList<Tuple<bool, int>>>(list => result.Enqueue(list)))
.Run(Materializer);
Thread.Sleep(500);
result.All(l => l.Count > 0).Should().BeTrue();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Rynchodon.AntennaRelay;
using Rynchodon.Attached;
using Rynchodon.Autopilot.Data;
using Rynchodon.Utility;
using VRage.Game.ModAPI;
using VRageMath;
namespace Rynchodon.Autopilot
{
/// <summary>
/// Finds a friendly grid and possibly a block, given a ship controller block.
/// </summary>
public class GridFinder
{
public enum ReasonCannotTarget : byte { None, Too_Far, Grid_Condition, Too_Fast }
private const ulong SearchInterval_Grid = 100ul, SearchInterval_Block = 100ul;
public readonly string m_targetGridName, m_targetBlockName;
private readonly ShipControllerBlock m_controlBlock;
private readonly AttachedGrid.AttachmentKind m_allowedAttachment;
private readonly AllNavigationSettings m_navSet;
private readonly bool m_mustBeRecent;
public Vector3D m_startPosition;
public ulong NextSearch_Grid { get; private set; }
public ulong NextSearch_Block { get; private set; }
public virtual LastSeen Grid { get; protected set; }
public IMyCubeBlock Block { get; private set; }
public Func<LastSeen, double> OrderValue;
public Func<IMyCubeGrid, bool> GridCondition;
/// <summary>Block requirements, other than can control.</summary>
public Func<IMyCubeBlock, bool> BlockCondition;
public ReasonCannotTarget m_reason;
public LastSeen m_bestGrid;
protected float MaximumRange;
protected long m_targetEntityId;
//private Vector3I m_previousCell;
private RelayStorage m_netStore { get { return m_controlBlock.NetworkStorage; } }
private Logable Log { get { return new Logable(m_controlBlock?.CubeBlock); } }
/// <summary>
/// Creates a GridFinder to find a friendly grid based on its name.
/// </summary>
public GridFinder(AllNavigationSettings navSet, ShipControllerBlock controller, string targetGrid, string targetBlock = null,
AttachedGrid.AttachmentKind allowedAttachment = AttachedGrid.AttachmentKind.Permanent, bool mustBeRecent = false)
{
Log.DebugLog("navSet == null", Logger.severity.FATAL, condition: navSet == null);
Log.DebugLog("controller == null", Logger.severity.FATAL, condition: controller == null);
Log.DebugLog("controller.CubeBlock == null", Logger.severity.FATAL, condition: controller.CubeBlock == null);
Log.DebugLog("targetGrid == null", Logger.severity.FATAL, condition: targetGrid == null);
this.m_targetGridName = targetGrid.LowerRemoveWhitespace();
if (targetBlock != null)
this.m_targetBlockName = targetBlock.LowerRemoveWhitespace();
this.m_controlBlock = controller;
this.m_allowedAttachment = allowedAttachment;
this.MaximumRange = 0f;
this.m_navSet = navSet;
this.m_mustBeRecent = mustBeRecent;
this.m_startPosition = m_controlBlock.CubeBlock.GetPosition();
}
/// <summary>
/// Creates a GridFinder to find an enemy grid based on distance.
/// </summary>
public GridFinder(AllNavigationSettings navSet, ShipControllerBlock controller, float maxRange = 0f)
{
Log.DebugLog("navSet == null", Logger.severity.FATAL, condition: navSet == null);
Log.DebugLog("controller == null", Logger.severity.FATAL, condition: controller == null);
Log.DebugLog("controller.CubeBlock == null", Logger.severity.FATAL, condition: controller.CubeBlock == null);
this.m_controlBlock = controller;
//this.m_enemies = new List<LastSeen>();
this.MaximumRange = maxRange;
this.m_navSet = navSet;
this.m_mustBeRecent = true;
this.m_startPosition = m_controlBlock.CubeBlock.GetPosition();
}
public void Update()
{
if (Grid == null || OrderValue != null)
{
if (Globals.UpdateCount >= NextSearch_Grid)
GridSearch();
}
else
GridUpdate();
if (Grid != null && m_targetBlockName != null)
{
if (Block == null)
{
if (Globals.UpdateCount >= NextSearch_Block)
BlockSearch();
}
else
BlockCheck();
}
}
/// <summary>
/// Find a seen grid that matches m_targetGridName
/// </summary>
private void GridSearch()
{
NextSearch_Grid = Globals.UpdateCount + SearchInterval_Grid;
if (m_targetGridName != null)
GridSearch_Friend();
else
GridSearch_Enemy();
}
private void GridSearch_Friend()
{
int bestNameLength = int.MaxValue;
RelayStorage store = m_netStore;
if (store == null)
{
Log.DebugLog("no storage", Logger.severity.DEBUG);
return;
}
store.SearchLastSeen(seen => {
IMyCubeGrid grid = seen.Entity as IMyCubeGrid;
if (grid != null && grid.DisplayName.Length < bestNameLength && grid.DisplayName.LowerRemoveWhitespace().Contains(m_targetGridName) && CanTarget(seen))
{
Grid = seen;
bestNameLength = grid.DisplayName.Length;
if (bestNameLength == m_targetGridName.Length)
{
Log.DebugLog("perfect match LastSeen: " + seen.Entity.getBestName());
return true;
}
}
return false;
});
if (Grid != null)
Log.DebugLog("Best match LastSeen: " + Grid.Entity.getBestName());
}
private void GridSearch_Enemy()
{
RelayStorage store = m_netStore;
if (store == null)
{
Log.DebugLog("no storage", Logger.severity.DEBUG);
return;
}
if (m_targetEntityId != 0L)
{
LastSeen target;
if (store.TryGetLastSeen(m_targetEntityId, out target) && CanTarget(target))
{
Grid = target;
Log.DebugLog("found target: " + target.Entity.getBestName());
}
else
Grid = null;
return;
}
List<LastSeen> enemies = ResourcePool<List<LastSeen>>.Get();
Vector3D position = m_controlBlock.CubeBlock.GetPosition();
store.SearchLastSeen(seen => {
if (!seen.IsValid || !seen.isRecent())
return false;
IMyCubeGrid asGrid = seen.Entity as IMyCubeGrid;
if (asGrid == null)
return false;
if (!m_controlBlock.CubeBlock.canConsiderHostile(asGrid))
return false;
enemies.Add(seen);
Log.DebugLog("enemy: " + asGrid.DisplayName);
return false;
});
Log.DebugLog("number of enemies: " + enemies.Count);
IOrderedEnumerable<LastSeen> enemiesByDistance = enemies.OrderBy(OrderValue != null ? OrderValue : seen => Vector3D.DistanceSquared(position, seen.GetPosition()));
m_reason = ReasonCannotTarget.None;
foreach (LastSeen enemy in enemiesByDistance)
{
if (CanTarget(enemy))
{
Grid = enemy;
Log.DebugLog("found target: " + enemy.Entity.getBestName());
enemies.Clear();
ResourcePool<List<LastSeen>>.Return(enemies);
return;
}
}
Grid = null;
Log.DebugLog("nothing found");
enemies.Clear();
ResourcePool<List<LastSeen>>.Return(enemies);
}
private void GridUpdate()
{
Log.DebugLog("Grid == null", Logger.severity.FATAL, condition: Grid == null);
if (!Grid.IsValid)
{
Log.DebugLog("no longer valid: " + Grid.Entity.getBestName(), Logger.severity.DEBUG);
Grid = null;
return;
}
if (m_mustBeRecent && !Grid.isRecent())
{
Log.DebugLog("no longer recent: " + Grid.Entity.getBestName() + ", age: " + (Globals.ElapsedTime - Grid.LastSeenAt));
Grid = null;
return;
}
if (!CanTarget(Grid))
{
Log.DebugLog("can no longer target: " + Grid.Entity.getBestName(), Logger.severity.DEBUG);
Grid = null;
return;
}
RelayStorage storage = m_netStore;
if (storage == null)
{
Log.DebugLog("lost storage", Logger.severity.DEBUG);
Grid = null;
return;
}
LastSeen updated;
if (!m_netStore.TryGetLastSeen(Grid.Entity.EntityId, out updated))
{
Log.AlwaysLog("Where does the good go? Searching for " + Grid.Entity.EntityId, Logger.severity.WARNING);
Grid = null;
return;
}
//Log.DebugLog("updating grid last seen " + Grid.LastSeenAt + " => " + updated.LastSeenAt, "GridUpdate()");
Grid = updated;
}
/// <summary>
/// Find a block that matches m_targetBlockName.
/// </summary>
private void BlockSearch()
{
Log.DebugLog("Grid == null", Logger.severity.FATAL, condition: Grid == null);
Log.DebugLog("m_targetBlockName == null", Logger.severity.FATAL, condition: m_targetBlockName == null);
NextSearch_Block = Globals.UpdateCount + SearchInterval_Block;
Block = null;
int bestNameLength = int.MaxValue;
IMyCubeGrid asGrid = Grid.Entity as IMyCubeGrid;
Log.DebugLog("asGrid == null", Logger.severity.FATAL, condition: asGrid == null);
foreach (IMyCubeBlock Fatblock in AttachedGrid.AttachedCubeBlocks(asGrid, m_allowedAttachment, true))
{
if (!m_controlBlock.CubeBlock.canControlBlock(Fatblock))
continue;
string blockName = Fatblock.DisplayNameText.LowerRemoveWhitespace();
if (BlockCondition != null && !BlockCondition(Fatblock))
continue;
//Log.DebugLog("checking block name: \"" + blockName + "\" contains \"" + m_targetBlockName + "\"", "BlockSearch()");
if (blockName.Length < bestNameLength && blockName.Contains(m_targetBlockName))
{
Log.DebugLog("block name matches: " + Fatblock.DisplayNameText);
Block = Fatblock;
bestNameLength = blockName.Length;
if (m_targetBlockName.Length == bestNameLength)
return;
}
}
}
private void BlockCheck()
{
Log.DebugLog("Grid == null", Logger.severity.FATAL, condition: Grid == null);
Log.DebugLog("m_targetBlockName == null", Logger.severity.FATAL, condition: m_targetBlockName == null);
Log.DebugLog("Block == null", Logger.severity.FATAL, condition: Block == null);
if (!m_controlBlock.CubeBlock.canControlBlock(Block))
{
Log.DebugLog("lost control of block: " + Block.DisplayNameText, Logger.severity.DEBUG);
Block = null;
return;
}
if (BlockCondition != null && !BlockCondition(Block))
{
Log.DebugLog("Block does not statisfy condition: " + Block.DisplayNameText, Logger.severity.DEBUG);
Block = null;
return;
}
}
private bool CanTarget(LastSeen seen)
{
try
{
// if it is too far from start, cannot target
if (MaximumRange > 1f && Vector3.DistanceSquared(m_startPosition, seen.GetPosition()) > MaximumRange * MaximumRange)
{
Log.DebugLog("out of range: " + seen.Entity.getBestName());
if (m_reason < ReasonCannotTarget.Too_Far)
{
m_reason = ReasonCannotTarget.Too_Far;
m_bestGrid = seen;
}
return false;
}
// if it is too fast, cannot target
float speedTarget = m_navSet.Settings_Task_NavEngage.SpeedTarget - 1f;
if (seen.GetLinearVelocity().LengthSquared() >= speedTarget * speedTarget)
{
Log.DebugLog("too fast to target: " + seen.Entity.getBestName() + ", speed: " + seen.GetLinearVelocity().Length() + ", my speed: " + m_navSet.Settings_Task_NavEngage.SpeedTarget);
if (m_reason < ReasonCannotTarget.Too_Fast)
{
m_reason = ReasonCannotTarget.Too_Fast;
m_bestGrid = seen;
}
return false;
}
if (GridCondition != null && !GridCondition(seen.Entity as IMyCubeGrid))
{
Log.DebugLog("Failed grid condition: " + seen.Entity.getBestName());
if (m_reason < ReasonCannotTarget.Grid_Condition)
{
m_reason = ReasonCannotTarget.Grid_Condition;
m_bestGrid = seen;
}
return false;
}
m_bestGrid = seen;
return true;
}
catch (NullReferenceException nre)
{
Log.AlwaysLog("Exception: " + nre, Logger.severity.ERROR);
if (!seen.Entity.Closed)
throw;
Log.DebugLog("Caught exception caused by grid closing, ignoring.");
return false;
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
public interface ITileMapEditorHost
{
void BuildIncremental();
void Build(bool force);
}
[InitializeOnLoad]
public static class tk2dTileMapEditorUtility {
static tk2dTileMapEditorUtility() {
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
System.Reflection.FieldInfo undoCallback = typeof(EditorApplication).GetField("undoRedoPerformed", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
if (undoCallback != null) {
undoCallback.SetValue(null, (EditorApplication.CallbackFunction)OnUndoRedo);
}
else {
Debug.LogError("tk2d Undo/Redo callback failed. Undo/Redo not supported in this version of Unity.");
}
#else
Undo.undoRedoPerformed += OnUndoRedo;
#endif
}
static void OnUndoRedo() {
foreach (GameObject go in Selection.gameObjects) {
tk2dUtil.UndoEnabled = false;
tk2dTileMap tilemap = go.GetComponent<tk2dTileMap>();
if (tilemap != null) {
tilemap.ForceBuild();
}
tk2dUtil.UndoEnabled = true;
}
}
}
[CustomEditor(typeof(tk2dTileMap))]
public class tk2dTileMapEditor : Editor, ITileMapEditorHost
{
tk2dTileMap tileMap { get { return (tk2dTileMap)target; } }
tk2dTileMapEditorData editorData;
tk2dTileMapSceneGUI sceneGUI;
tk2dEditor.BrushRenderer _brushRenderer;
tk2dEditor.BrushRenderer brushRenderer
{
get {
if (_brushRenderer == null) _brushRenderer = new tk2dEditor.BrushRenderer(tileMap);
return _brushRenderer;
}
set {
if (value != null) { Debug.LogError("Only alloyed to set to null"); return; }
if (_brushRenderer != null)
{
_brushRenderer.Destroy();
_brushRenderer = null;
}
}
}
tk2dEditor.BrushBuilder _guiBrushBuilder;
tk2dEditor.BrushBuilder guiBrushBuilder
{
get {
if (_guiBrushBuilder == null) _guiBrushBuilder = new tk2dEditor.BrushBuilder();
return _guiBrushBuilder;
}
set {
if (value != null) { Debug.LogError("Only allowed to set to null"); return; }
if (_guiBrushBuilder != null)
{
_guiBrushBuilder = null;
}
}
}
int width, height;
int partitionSizeX, partitionSizeY;
// Sprite collection accessor, cleanup when changed
tk2dSpriteCollectionData _spriteCollection = null;
tk2dSpriteCollectionData SpriteCollection
{
get
{
if (_spriteCollection != tileMap.SpriteCollectionInst)
{
_spriteCollection = tileMap.SpriteCollectionInst;
}
return _spriteCollection;
}
}
void OnEnable()
{
if (Application.isPlaying || !tileMap.AllowEdit)
return;
LoadTileMapData();
}
void OnDestroy() {
tk2dGrid.Done();
tk2dEditorSkin.Done();
tk2dPreferences.inst.Save();
tk2dSpriteThumbnailCache.Done();
}
void InitEditor()
{
// Initialize editor
LoadTileMapData();
}
void OnDisable()
{
brushRenderer = null;
guiBrushBuilder = null;
if (sceneGUI != null)
{
sceneGUI.Destroy();
sceneGUI = null;
}
if (editorData)
{
EditorUtility.SetDirty(editorData);
}
if (tileMap && tileMap.data)
{
EditorUtility.SetDirty(tileMap.data);
}
}
void LoadTileMapData()
{
width = tileMap.width;
height = tileMap.height;
partitionSizeX = tileMap.partitionSizeX;
partitionSizeY = tileMap.partitionSizeY;
GetEditorData();
if (tileMap.data && editorData && tileMap.Editor__SpriteCollection != null)
{
// Rebuild the palette
editorData.CreateDefaultPalette(tileMap.SpriteCollectionInst, editorData.paletteBrush, editorData.paletteTilesPerRow);
}
// Rebuild the render utility
if (sceneGUI != null)
{
sceneGUI.Destroy();
}
sceneGUI = new tk2dTileMapSceneGUI(this, tileMap, editorData);
// Rebuild the brush renderer
brushRenderer = null;
}
public void Build(bool force, bool incremental)
{
if (force)
{
//if (buildKey != tileMap.buildKey)
//tk2dEditor.TileMap.TileMapUtility.CleanRenderData(tileMap);
tk2dTileMap.BuildFlags buildFlags = tk2dTileMap.BuildFlags.EditMode;
if (!incremental) buildFlags |= tk2dTileMap.BuildFlags.ForceBuild;
tileMap.Build(buildFlags);
}
}
public void Build(bool force) { Build(force, false); }
public void BuildIncremental() { Build(true, true); }
bool Ready
{
get
{
return (tileMap != null && tileMap.data != null && editorData != null & tileMap.Editor__SpriteCollection != null && tileMap.SpriteCollectionInst != null);
}
}
void HighlightTile(Rect rect, Rect tileSize, int tilesPerRow, int x, int y, Color fillColor, Color outlineColor)
{
Rect highlightRect = new Rect(rect.x + x * tileSize.width,
rect.y + y * tileSize.height,
tileSize.width,
tileSize.height);
Vector3[] rectVerts = { new Vector3(highlightRect.x, highlightRect.y, 0),
new Vector3(highlightRect.x + highlightRect.width, highlightRect.y, 0),
new Vector3(highlightRect.x + highlightRect.width, highlightRect.y + highlightRect.height, 0),
new Vector3(highlightRect.x, highlightRect.y + highlightRect.height, 0) };
Handles.DrawSolidRectangleWithOutline(rectVerts, fillColor, outlineColor);
}
Vector2 tiledataScrollPos = Vector2.zero;
int selectedDataTile = -1;
void DrawTileDataSetupPanel()
{
// Sanitize prefabs
if (tileMap.data.tilePrefabs == null)
tileMap.data.tilePrefabs = new GameObject[0];
if (tileMap.data.tilePrefabs.Length != SpriteCollection.Count)
{
System.Array.Resize(ref tileMap.data.tilePrefabs, SpriteCollection.Count);
}
Rect innerRect = brushRenderer.GetBrushViewRect(editorData.paletteBrush, editorData.paletteTilesPerRow);
tiledataScrollPos = BeginHScrollView(tiledataScrollPos, GUILayout.MinHeight(innerRect.height * editorData.brushDisplayScale + 32.0f));
innerRect.width *= editorData.brushDisplayScale;
innerRect.height *= editorData.brushDisplayScale;
tk2dGrid.Draw(innerRect);
Rect rect = brushRenderer.DrawBrush(tileMap, editorData.paletteBrush, editorData.brushDisplayScale, true, editorData.paletteTilesPerRow);
float displayScale = brushRenderer.LastScale;
Rect tileSize = new Rect(0, 0, brushRenderer.TileSizePixels.width * displayScale, brushRenderer.TileSizePixels.height * displayScale);
int tilesPerRow = editorData.paletteTilesPerRow;
int newSelectedPrefab = selectedDataTile;
if (Event.current.type == EventType.MouseUp && rect.Contains(Event.current.mousePosition))
{
Vector2 localClickPosition = Event.current.mousePosition - new Vector2(rect.x, rect.y);
Vector2 tileLocalPosition = new Vector2(localClickPosition.x / tileSize.width, localClickPosition.y / tileSize.height);
int tx = (int)tileLocalPosition.x;
int ty = (int)tileLocalPosition.y;
newSelectedPrefab = ty * tilesPerRow + tx;
}
if (Event.current.type == EventType.Repaint)
{
for (int tileId = 0; tileId < SpriteCollection.Count; ++tileId)
{
Color noDataFillColor = new Color(0, 0, 0, 0.2f);
Color noDataOutlineColor = Color.clear;
Color selectedFillColor = new Color(1,0,0,0.05f);
Color selectedOutlineColor = Color.red;
if (tileMap.data.tilePrefabs[tileId] == null || tileId == selectedDataTile)
{
Color fillColor = (selectedDataTile == tileId)?selectedFillColor:noDataFillColor;
Color outlineColor = (selectedDataTile == tileId)?selectedOutlineColor:noDataOutlineColor;
HighlightTile(rect, tileSize, editorData.paletteTilesPerRow, tileId % tilesPerRow, tileId / tilesPerRow, fillColor, outlineColor);
}
}
}
EndHScrollView();
if (selectedDataTile >= 0 && selectedDataTile < tileMap.data.tilePrefabs.Length)
{
tileMap.data.tilePrefabs[selectedDataTile] = EditorGUILayout.ObjectField("Prefab", tileMap.data.tilePrefabs[selectedDataTile], typeof(GameObject), true) as GameObject;
}
// Add all additional tilemap data
var allTileInfos = tileMap.data.GetOrCreateTileInfo(SpriteCollection.Count);
if (selectedDataTile >= 0 && selectedDataTile < allTileInfos.Length)
{
var tileInfo = allTileInfos[selectedDataTile];
GUILayout.Space(16.0f);
tileInfo.stringVal = (tileInfo.stringVal==null)?"":tileInfo.stringVal;
tileInfo.stringVal = EditorGUILayout.TextField("String", tileInfo.stringVal);
tileInfo.intVal = EditorGUILayout.IntField("Int", tileInfo.intVal);
tileInfo.floatVal = EditorGUILayout.FloatField("Float", tileInfo.floatVal);
tileInfo.enablePrefabOffset = EditorGUILayout.Toggle("Enable Prefab Offset", tileInfo.enablePrefabOffset);
}
if (newSelectedPrefab != selectedDataTile)
{
selectedDataTile = newSelectedPrefab;
Repaint();
}
}
void DrawLayersPanel(bool allowEditing)
{
GUILayout.BeginVertical();
// constrain selected layer
editorData.layer = Mathf.Clamp(editorData.layer, 0, tileMap.data.NumLayers - 1);
if (allowEditing)
{
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
tileMap.data.useSortingLayers = GUILayout.Toggle(tileMap.data.useSortingLayers, "Sorting Layers", EditorStyles.miniButton, GUILayout.ExpandWidth(false));
#endif
tileMap.data.layersFixedZ = GUILayout.Toggle(tileMap.data.layersFixedZ, "Fixed Z", EditorStyles.miniButton, GUILayout.ExpandWidth(false));
if (GUILayout.Button("Add Layer", EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
{
editorData.layer = tk2dEditor.TileMap.TileMapUtility.AddNewLayer(tileMap);
}
GUILayout.EndHorizontal();
}
if (tileMap.data.useSortingLayers) {
EditorGUILayout.HelpBox("Unity Sorting Layers take precedence over z sorting. Please ensure your sprites / prefabs are on the correct layers for them to sort properly - they don't automatically inherit the sorting layer/order of the parent.", MessageType.Warning);
}
string zValueLabel = tileMap.data.layersFixedZ ? "Z Value" : "Z Offset";
int numLayers = tileMap.data.NumLayers;
int deleteLayer = -1;
int moveUp = -1;
int moveDown = -1;
for (int layer = numLayers - 1; layer >= 0; --layer)
{
GUILayout.Space(4.0f);
if (allowEditing) {
GUILayout.BeginVertical(tk2dEditorSkin.SC_InspectorHeaderBG);
GUILayout.BeginHorizontal();
if (editorData.layer == layer) {
string newName = GUILayout.TextField(tileMap.data.Layers[layer].name, EditorStyles.textField, GUILayout.MinWidth(120), GUILayout.ExpandWidth(true));
tileMap.data.Layers[layer].name = newName;
} else {
if (GUILayout.Button(tileMap.data.Layers[layer].name, EditorStyles.textField, GUILayout.MinWidth(120), GUILayout.ExpandWidth(true))) {
editorData.layer = layer;
Repaint();
}
}
GUI.enabled = (layer != 0);
if (GUILayout.Button("", tk2dEditorSkin.SimpleButton("btn_down")))
{
moveUp = layer;
Repaint();
}
GUI.enabled = (layer != numLayers - 1);
if (GUILayout.Button("", tk2dEditorSkin.SimpleButton("btn_up")))
{
moveDown = layer;
Repaint();
}
GUI.enabled = numLayers > 1;
if (GUILayout.Button("", tk2dEditorSkin.GetStyle("TilemapDeleteItem")))
{
deleteLayer = layer;
Repaint();
}
GUI.enabled = true;
GUILayout.EndHorizontal();
// Row 2
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
tk2dGuiUtility.BeginChangeCheck();
tileMap.data.Layers[layer].skipMeshGeneration = !GUILayout.Toggle(!tileMap.data.Layers[layer].skipMeshGeneration, "Render Mesh", EditorStyles.miniButton, GUILayout.ExpandWidth(false));
tileMap.data.Layers[layer].useColor = GUILayout.Toggle(tileMap.data.Layers[layer].useColor, "Color", EditorStyles.miniButton, GUILayout.ExpandWidth(false));
tileMap.data.Layers[layer].generateCollider = GUILayout.Toggle(tileMap.data.Layers[layer].generateCollider, "Collider", EditorStyles.miniButton, GUILayout.ExpandWidth(false));
if (tk2dGuiUtility.EndChangeCheck())
Build(true);
GUILayout.EndHorizontal();
// Row 3
tk2dGuiUtility.BeginChangeCheck();
if (layer == 0 && !tileMap.data.layersFixedZ) {
GUI.enabled = false;
EditorGUILayout.FloatField(zValueLabel, 0.0f);
GUI.enabled = true;
}
else {
tileMap.data.Layers[layer].z = EditorGUILayout.FloatField(zValueLabel, tileMap.data.Layers[layer].z);
}
if (!tileMap.data.layersFixedZ)
tileMap.data.Layers[layer].z = Mathf.Max(0, tileMap.data.Layers[layer].z);
tileMap.data.Layers[layer].unityLayer = EditorGUILayout.LayerField("Unity Layer", tileMap.data.Layers[layer].unityLayer);
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
// Unity sorting layers
if (tileMap.data.useSortingLayers) {
tk2dGuiUtility.BeginChangeCheck();
tileMap.data.Layers[layer].sortingLayerName = tk2dEditorUtility.SortingLayerNamePopup("Sorting Layer", tileMap.data.Layers[layer].sortingLayerName);
tileMap.data.Layers[layer].sortingOrder = EditorGUILayout.IntField("Sorting Order in Layer", tileMap.data.Layers[layer].sortingOrder);
if (tk2dGuiUtility.EndChangeCheck()) {
Build(true);
}
}
#endif
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
bool using2DPhysics = (tileMap.SpriteCollectionInst != null && tileMap.SpriteCollectionInst.FirstValidDefinition != null && tileMap.SpriteCollectionInst.FirstValidDefinition.physicsEngine == tk2dSpriteDefinition.PhysicsEngine.Physics2D);
if (using2DPhysics) {
tileMap.data.Layers[layer].physicsMaterial2D = (PhysicsMaterial2D)EditorGUILayout.ObjectField("Physics Material (2D)", tileMap.data.Layers[layer].physicsMaterial2D, typeof(PhysicsMaterial2D), false);
}
else
#endif
{
tileMap.data.Layers[layer].physicMaterial = (PhysicMaterial)EditorGUILayout.ObjectField("Physic Material", tileMap.data.Layers[layer].physicMaterial, typeof(PhysicMaterial), false);
}
if (tk2dGuiUtility.EndChangeCheck())
Build(true);
GUILayout.EndVertical();
} else {
GUILayout.BeginHorizontal(tk2dEditorSkin.SC_InspectorHeaderBG);
bool layerSelVal = editorData.layer == layer;
bool newLayerSelVal = GUILayout.Toggle(layerSelVal, tileMap.data.Layers[layer].name, EditorStyles.toggle, GUILayout.ExpandWidth(true));
if (newLayerSelVal != layerSelVal)
{
editorData.layer = layer;
Repaint();
}
GUILayout.FlexibleSpace();
var layerGameObject = tileMap.Layers[layer].gameObject;
if (layerGameObject)
{
bool b = GUILayout.Toggle(tk2dEditorUtility.IsGameObjectActive(layerGameObject), "", tk2dEditorSkin.SimpleCheckbox("icon_eye_inactive", "icon_eye"));
if (b != tk2dEditorUtility.IsGameObjectActive(layerGameObject))
tk2dEditorUtility.SetGameObjectActive(layerGameObject, b);
}
GUILayout.EndHorizontal();
}
}
if (deleteLayer != -1)
{
//Undo.RegisterUndo(new Object[] { tileMap, tileMap.data }, "Deleted layer");
tk2dEditor.TileMap.TileMapUtility.DeleteLayer(tileMap, deleteLayer);
}
if (moveUp != -1)
{
//Undo.RegisterUndo(new Object[] { tileMap, tileMap.data }, "Moved layer");
tk2dEditor.TileMap.TileMapUtility.MoveLayer(tileMap, moveUp, -1);
}
if (moveDown != -1)
{
//Undo.RegisterUndo(new Object[] { tileMap, tileMap.data }, "Moved layer");
tk2dEditor.TileMap.TileMapUtility.MoveLayer(tileMap, moveDown, 1);
}
GUILayout.EndVertical();
}
bool Foldout(ref tk2dTileMapEditorData.SetupMode val, tk2dTileMapEditorData.SetupMode ident, string name)
{
bool selected = false;
if ((val & ident) != 0)
selected = true;
//GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
bool newSelected = GUILayout.Toggle(selected, name, EditorStyles.toolbarDropDown, GUILayout.ExpandWidth(true));
if (newSelected != selected)
{
if (selected == false)
val = ident;
else
val = 0;
}
return newSelected;
}
int tilePropertiesPreviewIdx = 0;
Vector2 paletteSettingsScrollPos = Vector2.zero;
void DrawSettingsPanel()
{
GUILayout.Space(8);
// Sprite collection
GUILayout.BeginHorizontal();
tk2dSpriteCollectionData newSpriteCollection = tk2dSpriteGuiUtility.SpriteCollectionList("Sprite Collection", tileMap.Editor__SpriteCollection);
if (newSpriteCollection != tileMap.Editor__SpriteCollection) {
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.RegisterSceneUndo("Set TileMap Sprite Collection");
#else
Undo.RegisterCompleteObjectUndo(tileMap, "Set TileMap Sprite Collection");
#endif
tileMap.Editor__SpriteCollection = newSpriteCollection;
newSpriteCollection.InitMaterialIds();
LoadTileMapData();
EditorUtility.SetDirty(tileMap);
if (Ready)
{
Init(tileMap.data);
tileMap.ForceBuild();
}
}
if (tileMap.Editor__SpriteCollection != null && GUILayout.Button(">", EditorStyles.miniButton, GUILayout.Width(19))) {
tk2dSpriteCollectionEditorPopup v = EditorWindow.GetWindow( typeof(tk2dSpriteCollectionEditorPopup), false, "Sprite Collection Editor" ) as tk2dSpriteCollectionEditorPopup;
string assetPath = AssetDatabase.GUIDToAssetPath(tileMap.Editor__SpriteCollection.spriteCollectionGUID);
var spriteCollection = AssetDatabase.LoadAssetAtPath(assetPath, typeof(tk2dSpriteCollection)) as tk2dSpriteCollection;
v.SetGeneratorAndSelectedSprite(spriteCollection, tileMap.Editor__SpriteCollection.FirstValidDefinitionIndex);
}
GUILayout.EndHorizontal();
GUILayout.Space(8);
// Tilemap data
tk2dTileMapData newData = (tk2dTileMapData)EditorGUILayout.ObjectField("Tile Map Data", tileMap.data, typeof(tk2dTileMapData), false);
if (newData != tileMap.data)
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.RegisterSceneUndo("Assign TileMap Data");
#else
Undo.RegisterCompleteObjectUndo(tileMap, "Assign TileMap Data");
#endif
tileMap.data = newData;
LoadTileMapData();
}
if (tileMap.data == null)
{
if (tk2dGuiUtility.InfoBoxWithButtons(
"TileMap needs an data object to proceed. " +
"Please create one or drag an existing data object into the inspector slot.\n",
tk2dGuiUtility.WarningLevel.Info,
"Create") != -1)
{
string assetPath = EditorUtility.SaveFilePanelInProject("Save Tile Map Data", "tileMapData", "asset", "");
if (assetPath.Length > 0)
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.RegisterSceneUndo("Create TileMap Data");
#else
Undo.RegisterCompleteObjectUndo(tileMap, "Create TileMap Data");
#endif
tk2dTileMapData tileMapData = ScriptableObject.CreateInstance<tk2dTileMapData>();
AssetDatabase.CreateAsset(tileMapData, assetPath);
tileMap.data = tileMapData;
EditorUtility.SetDirty(tileMap);
Init(tileMapData);
LoadTileMapData();
}
}
}
// Editor data
tk2dTileMapEditorData newEditorData = (tk2dTileMapEditorData)EditorGUILayout.ObjectField("Editor Data", editorData, typeof(tk2dTileMapEditorData), false);
if (newEditorData != editorData)
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.RegisterSceneUndo("Assign TileMap Editor Data");
#else
Undo.RegisterCompleteObjectUndo(tileMap, "Assign TileMap Editor Data");
#endif
string assetPath = AssetDatabase.GetAssetPath(newEditorData);
if (assetPath.Length > 0)
{
tileMap.editorDataGUID = AssetDatabase.AssetPathToGUID(assetPath);
EditorUtility.SetDirty(tileMap);
LoadTileMapData();
}
}
if (editorData == null)
{
if (tk2dGuiUtility.InfoBoxWithButtons(
"TileMap needs an editor data object to proceed. " +
"Please create one or drag an existing data object into the inspector slot.\n",
tk2dGuiUtility.WarningLevel.Info,
"Create") != -1)
{
string assetPath = EditorUtility.SaveFilePanelInProject("Save Tile Map Editor Data", "tileMapEditorData", "asset", "");
if (assetPath.Length > 0)
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.RegisterSceneUndo("Create TileMap Editor Data");
#else
Undo.RegisterCompleteObjectUndo(tileMap, "Create TileMap Editor Data");
#endif
tk2dTileMapEditorData tileMapEditorData = ScriptableObject.CreateInstance<tk2dTileMapEditorData>();
AssetDatabase.CreateAsset(tileMapEditorData, assetPath);
tileMap.editorDataGUID = AssetDatabase.AssetPathToGUID(assetPath);
EditorUtility.SetDirty(tileMap);
LoadTileMapData();
}
}
}
// If not set up, don't bother drawing anything else
if (!Ready)
return;
// this is intentionally read only
GUILayout.Space(8);
GUILayout.BeginHorizontal();
GUI.enabled = false;
EditorGUILayout.ObjectField("Render Data", tileMap.renderData, typeof(GameObject), false);
GUI.enabled = true;
if (tileMap.renderData != null && GUILayout.Button("Unlink", EditorStyles.miniButton, GUILayout.ExpandWidth(false))) {
tk2dEditor.TileMap.TileMapUtility.MakeUnique(tileMap);
}
GUILayout.EndHorizontal();
GUILayout.Space(8);
// tile map size
if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.Dimensions, "Dimensions"))
{
EditorGUI.indentLevel++;
width = Mathf.Clamp(EditorGUILayout.IntField("Width", width), 1, tk2dEditor.TileMap.TileMapUtility.MaxWidth);
height = Mathf.Clamp(EditorGUILayout.IntField("Height", height), 1, tk2dEditor.TileMap.TileMapUtility.MaxHeight);
partitionSizeX = Mathf.Clamp(EditorGUILayout.IntField("PartitionSizeX", partitionSizeX), 4, 32);
partitionSizeY = Mathf.Clamp(EditorGUILayout.IntField("PartitionSizeY", partitionSizeY), 4, 32);
// Create a default tilemap with given dimensions
if (!tileMap.AreSpritesInitialized())
{
tk2dRuntime.TileMap.BuilderUtil.InitDataStore(tileMap);
tk2dEditor.TileMap.TileMapUtility.ResizeTileMap(tileMap, width, height, tileMap.partitionSizeX, tileMap.partitionSizeY);
}
if (width != tileMap.width || height != tileMap.height || partitionSizeX != tileMap.partitionSizeX || partitionSizeY != tileMap.partitionSizeY)
{
if ((width < tileMap.width || height < tileMap.height))
{
tk2dGuiUtility.InfoBox("The new size of the tile map is smaller than the current size." +
"Some clipping will occur.", tk2dGuiUtility.WarningLevel.Warning);
}
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Apply", EditorStyles.miniButton))
{
tk2dEditor.TileMap.TileMapUtility.ResizeTileMap(tileMap, width, height, partitionSizeX, partitionSizeY);
}
GUILayout.EndHorizontal();
}
EditorGUI.indentLevel--;
}
if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.Layers, "Layers"))
{
EditorGUI.indentLevel++;
DrawLayersPanel(true);
EditorGUI.indentLevel--;
}
// tilemap info
if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.Info, "Info"))
{
EditorGUI.indentLevel++;
int numActiveChunks = 0;
if (tileMap.Layers != null)
{
foreach (var layer in tileMap.Layers)
numActiveChunks += layer.NumActiveChunks;
}
EditorGUILayout.LabelField("Active chunks", numActiveChunks.ToString());
int partitionMemSize = partitionSizeX * partitionSizeY * 4;
EditorGUILayout.LabelField("Memory", ((numActiveChunks * partitionMemSize) / 1024).ToString() + "kB" );
int numActiveColorChunks = 0;
if (tileMap.ColorChannel != null)
numActiveColorChunks += tileMap.ColorChannel.NumActiveChunks;
EditorGUILayout.LabelField("Active color chunks", numActiveColorChunks.ToString());
int colorMemSize = (partitionSizeX + 1) * (partitionSizeY + 1) * 4;
EditorGUILayout.LabelField("Memory", ((numActiveColorChunks * colorMemSize) / 1024).ToString() + "kB" );
EditorGUI.indentLevel--;
}
// tile properties
if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.TileProperties, "Tile Properties"))
{
EditorGUI.indentLevel++;
// sort method
tk2dGuiUtility.BeginChangeCheck();
tileMap.data.tileType = (tk2dTileMapData.TileType)EditorGUILayout.EnumPopup("Tile Type", tileMap.data.tileType);
if (tileMap.data.tileType != tk2dTileMapData.TileType.Rectangular) {
tk2dGuiUtility.InfoBox("Non-rectangular tile types are still in beta testing.", tk2dGuiUtility.WarningLevel.Info);
}
tileMap.data.sortMethod = (tk2dTileMapData.SortMethod)EditorGUILayout.EnumPopup("Sort Method", tileMap.data.sortMethod);
if (tk2dGuiUtility.EndChangeCheck())
{
tileMap.BeginEditMode();
}
// reset sizes
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Reset sizes");
GUILayout.FlexibleSpace();
if (GUILayout.Button("Reset", EditorStyles.miniButtonRight))
{
Init(tileMap.data);
Build(true);
}
GUILayout.EndHorizontal();
// convert these to pixel units
Vector3 texelSize = SpriteCollection.spriteDefinitions[0].texelSize;
Vector3 tileOriginPixels = new Vector3(tileMap.data.tileOrigin.x / texelSize.x, tileMap.data.tileOrigin.y / texelSize.y, tileMap.data.tileOrigin.z);
Vector3 tileSizePixels = new Vector3(tileMap.data.tileSize.x / texelSize.x, tileMap.data.tileSize.y / texelSize.y, tileMap.data.tileSize.z);
Vector3 newTileOriginPixels = EditorGUILayout.Vector3Field("Origin", tileOriginPixels);
Vector3 newTileSizePixels = EditorGUILayout.Vector3Field("Size", tileSizePixels);
if (newTileOriginPixels != tileOriginPixels ||
newTileSizePixels != tileSizePixels)
{
tileMap.data.tileOrigin = new Vector3(newTileOriginPixels.x * texelSize.x, newTileOriginPixels.y * texelSize.y, newTileOriginPixels.z);
tileMap.data.tileSize = new Vector3(newTileSizePixels.x * texelSize.x, newTileSizePixels.y * texelSize.y, newTileSizePixels.z);
Build(true);
}
// preview tile origin and size setting
Vector2 spritePixelOrigin = Vector2.zero;
Vector2 spritePixelSize = Vector2.one;
tk2dSpriteDefinition[] spriteDefs = tileMap.SpriteCollectionInst.spriteDefinitions;
tk2dSpriteDefinition spriteDef = (tilePropertiesPreviewIdx < spriteDefs.Length) ? spriteDefs[tilePropertiesPreviewIdx] : null;
if (!spriteDef.Valid) spriteDef = null;
if (spriteDef != null) {
spritePixelOrigin = new Vector2(spriteDef.untrimmedBoundsData[0].x / spriteDef.texelSize.x, spriteDef.untrimmedBoundsData[0].y / spriteDef.texelSize.y);
spritePixelSize = new Vector2(spriteDef.untrimmedBoundsData[1].x / spriteDef.texelSize.x, spriteDef.untrimmedBoundsData[1].y / spriteDef.texelSize.y);
}
float zoomFactor = (Screen.width - 32.0f) / (spritePixelSize.x * 2.0f);
EditorGUILayout.BeginScrollView(Vector2.zero, GUILayout.Height(spritePixelSize.y * 2.0f * zoomFactor + 32.0f));
Rect innerRect = new Rect(0, 0, spritePixelSize.x * 2.0f * zoomFactor, spritePixelSize.y * 2.0f * zoomFactor);
tk2dGrid.Draw(innerRect);
if (spriteDef != null) {
// Preview tiles
tk2dSpriteThumbnailCache.DrawSpriteTexture(new Rect(spritePixelSize.x * 0.5f * zoomFactor, spritePixelSize.y * 0.5f * zoomFactor, spritePixelSize.x * zoomFactor, spritePixelSize.y * zoomFactor), spriteDef);
// Preview cursor
Vector2 cursorOffset = (spritePixelSize * 0.5f - spritePixelOrigin) * zoomFactor;
Vector2 cursorSize = new Vector2(tileSizePixels.x * zoomFactor, tileSizePixels.y * zoomFactor);
cursorOffset.x += tileOriginPixels.x * zoomFactor;
cursorOffset.y += tileOriginPixels.y * zoomFactor;
cursorOffset.x += spritePixelSize.x * 0.5f * zoomFactor;
cursorOffset.y += spritePixelSize.y * 0.5f * zoomFactor;
float top = spritePixelSize.y * 2.0f * zoomFactor;
Vector3[] cursorVerts = new Vector3[] {
new Vector3(cursorOffset.x, top - cursorOffset.y, 0),
new Vector3(cursorOffset.x + cursorSize.x, top - cursorOffset.y, 0),
new Vector3(cursorOffset.x + cursorSize.x, top - (cursorOffset.y + cursorSize.y), 0),
new Vector3(cursorOffset.x, top - (cursorOffset.y + cursorSize.y), 0)
};
Handles.DrawSolidRectangleWithOutline(cursorVerts, new Color(1.0f, 1.0f, 1.0f, 0.2f), Color.white);
}
if (GUILayout.Button(new GUIContent("", "Click - preview using different tile"), "label", GUILayout.Width(innerRect.width), GUILayout.Height(innerRect.height))) {
int n = spriteDefs.Length;
for (int i = 0; i < n; ++i) {
if (++tilePropertiesPreviewIdx >= n)
tilePropertiesPreviewIdx = 0;
if (spriteDefs[tilePropertiesPreviewIdx].Valid)
break;
}
}
EditorGUILayout.EndScrollView();
EditorGUI.indentLevel--;
}
if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.PaletteProperties, "Palette Properties"))
{
EditorGUI.indentLevel++;
int newTilesPerRow = Mathf.Clamp(EditorGUILayout.IntField("Tiles Per Row", editorData.paletteTilesPerRow),
1, SpriteCollection.Count);
if (newTilesPerRow != editorData.paletteTilesPerRow)
{
guiBrushBuilder.Reset();
editorData.paletteTilesPerRow = newTilesPerRow;
editorData.CreateDefaultPalette(tileMap.SpriteCollectionInst, editorData.paletteBrush, editorData.paletteTilesPerRow);
}
GUILayout.BeginHorizontal();
editorData.brushDisplayScale = EditorGUILayout.FloatField("Display Scale", editorData.brushDisplayScale);
editorData.brushDisplayScale = Mathf.Clamp(editorData.brushDisplayScale, 1.0f / 16.0f, 4.0f);
if (GUILayout.Button("Reset", EditorStyles.miniButtonRight, GUILayout.ExpandWidth(false)))
{
editorData.brushDisplayScale = 1.0f;
Repaint();
}
GUILayout.EndHorizontal();
EditorGUILayout.PrefixLabel("Preview");
Rect innerRect = brushRenderer.GetBrushViewRect(editorData.paletteBrush, editorData.paletteTilesPerRow);
paletteSettingsScrollPos = BeginHScrollView(paletteSettingsScrollPos, GUILayout.MinHeight(innerRect.height * editorData.brushDisplayScale + 32.0f));
innerRect.width *= editorData.brushDisplayScale;
innerRect.height *= editorData.brushDisplayScale;
tk2dGrid.Draw(innerRect);
brushRenderer.DrawBrush(tileMap, editorData.paletteBrush, editorData.brushDisplayScale, true, editorData.paletteTilesPerRow);
EndHScrollView();
EditorGUI.indentLevel--;
}
if (Foldout(ref editorData.setupMode, tk2dTileMapEditorData.SetupMode.Import, "Import"))
{
EditorGUI.indentLevel++;
if (GUILayout.Button("Import TMX"))
{
if (tk2dEditor.TileMap.Importer.Import(tileMap, tk2dEditor.TileMap.Importer.Format.TMX))
{
Build(true);
width = tileMap.width;
height = tileMap.height;
partitionSizeX = tileMap.partitionSizeX;
partitionSizeY = tileMap.partitionSizeY;
}
}
EditorGUI.indentLevel--;
}
}
// Little hack to allow nested scrollviews to behave properly
Vector2 hScrollDelta = Vector2.zero;
Vector2 BeginHScrollView(Vector2 pos, params GUILayoutOption[] options) {
hScrollDelta = Vector2.zero;
if (Event.current.type == EventType.ScrollWheel) {
hScrollDelta.y = Event.current.delta.y;
}
return EditorGUILayout.BeginScrollView(pos, options);
}
void EndHScrollView() {
EditorGUILayout.EndScrollView();
if (hScrollDelta != Vector2.zero) {
Event.current.type = EventType.ScrollWheel;
Event.current.delta = hScrollDelta;
}
}
void DrawColorPaintPanel()
{
if (!tileMap.HasColorChannel())
{
if (GUILayout.Button("Create Color Channel"))
{
tk2dUndo.RegisterCompleteObjectUndo(tileMap, "Created Color Channel");
tileMap.CreateColorChannel();
tileMap.BeginEditMode();
}
Repaint();
return;
}
tk2dTileMapToolbar.ColorToolsWindow();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Clear to Color");
if (GUILayout.Button("Clear", GUILayout.ExpandWidth(false)))
{
tk2dUndo.RegisterCompleteObjectUndo(tileMap, "Created Color Channel");
tileMap.ColorChannel.Clear(tk2dTileMapToolbar.colorBrushColor);
Build(true);
}
EditorGUILayout.EndHorizontal();
if (tileMap.HasColorChannel())
{
EditorGUILayout.Separator();
if (GUILayout.Button("Delete Color Channel"))
{
tk2dUndo.RegisterCompleteObjectUndo(tileMap, "Deleted Color Channel");
tileMap.DeleteColorChannel();
tileMap.BeginEditMode();
Repaint();
return;
}
}
}
int InlineToolbar(string name, int val, string[] names)
{
int selectedIndex = val;
GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
GUILayout.Label(name, EditorStyles.toolbarButton);
GUILayout.FlexibleSpace();
for (int i = 0; i < names.Length; ++i)
{
bool selected = (i == selectedIndex);
bool toggled = GUILayout.Toggle(selected, names[i], EditorStyles.toolbarButton);
if (toggled == true)
{
selectedIndex = i;
}
}
GUILayout.EndHorizontal();
return selectedIndex;
}
bool showSaveSection = false;
bool showLoadSection = false;
void DrawLoadSaveBrushSection(tk2dTileMapEditorBrush activeBrush)
{
// Brush load & save handling
bool startedSave = false;
bool prevGuiEnabled = GUI.enabled;
GUILayout.BeginHorizontal();
if (showLoadSection) GUI.enabled = false;
if (GUILayout.Button(showSaveSection?"Cancel":"Save"))
{
if (showSaveSection == false) startedSave = true;
showSaveSection = !showSaveSection;
if (showSaveSection) showLoadSection = false;
Repaint();
}
GUI.enabled = prevGuiEnabled;
if (showSaveSection) GUI.enabled = false;
if (GUILayout.Button(showLoadSection?"Cancel":"Load"))
{
showLoadSection = !showLoadSection;
if (showLoadSection) showSaveSection = false;
}
GUI.enabled = prevGuiEnabled;
GUILayout.EndHorizontal();
if (showSaveSection)
{
GUI.SetNextControlName("BrushNameEntry");
activeBrush.name = EditorGUILayout.TextField("Name", activeBrush.name);
if (startedSave)
GUI.FocusControl("BrushNameEntry");
if (GUILayout.Button("Save"))
{
if (activeBrush.name.Length == 0)
{
Debug.LogError("Active brush needs a name");
}
else
{
bool replaced = false;
for (int i = 0; i < editorData.brushes.Count; ++i)
{
if (editorData.brushes[i].name == activeBrush.name)
{
editorData.brushes[i] = new tk2dTileMapEditorBrush(activeBrush);
replaced = true;
}
}
if (!replaced)
editorData.brushes.Add(new tk2dTileMapEditorBrush(activeBrush));
showSaveSection = false;
}
}
}
if (showLoadSection)
{
GUILayout.Space(8);
if (editorData.brushes.Count == 0)
GUILayout.Label("No saved brushes.");
GUILayout.BeginVertical();
int deleteBrushId = -1;
for (int i = 0; i < editorData.brushes.Count; ++i)
{
var v = editorData.brushes[i];
GUILayout.BeginHorizontal();
if (GUILayout.Button(v.name, EditorStyles.miniButton))
{
showLoadSection = false;
editorData.activeBrush = new tk2dTileMapEditorBrush(v);
}
if (GUILayout.Button("X", EditorStyles.miniButton, GUILayout.Width(16)))
{
deleteBrushId = i;
}
GUILayout.EndHorizontal();
}
if (deleteBrushId != -1)
{
editorData.brushes.RemoveAt(deleteBrushId);
Repaint();
}
GUILayout.EndVertical();
}
}
Vector2 paletteScrollPos = Vector2.zero;
Vector2 activeBrushScrollPos = Vector2.zero;
void DrawPaintPanel()
{
var activeBrush = editorData.activeBrush;
if (Ready && (activeBrush == null || activeBrush.Empty))
{
editorData.InitBrushes(tileMap.SpriteCollectionInst);
}
// Draw layer selector
if (tileMap.data.NumLayers > 1)
{
GUILayout.BeginVertical();
GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
GUILayout.Label("Layers", EditorStyles.toolbarButton); GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
DrawLayersPanel(false);
EditorGUILayout.Space();
GUILayout.EndVertical();
}
#if TK2D_TILEMAP_EXPERIMENTAL
DrawLoadSaveBrushSection(activeBrush);
#endif
// Draw palette
if (!showLoadSection && !showSaveSection)
{
editorData.showPalette = EditorGUILayout.Foldout(editorData.showPalette, "Palette");
if (editorData.showPalette)
{
// brush name
string selectionDesc = "";
if (activeBrush.tiles.Length == 1) {
int tile = tk2dRuntime.TileMap.BuilderUtil.GetTileFromRawTile(activeBrush.tiles[0].spriteId);
if (tile >= 0 && tile < SpriteCollection.spriteDefinitions.Length)
selectionDesc = SpriteCollection.spriteDefinitions[tile].name;
}
GUILayout.Label(selectionDesc);
Rect innerRect = brushRenderer.GetBrushViewRect(editorData.paletteBrush, editorData.paletteTilesPerRow);
paletteScrollPos = BeginHScrollView(paletteScrollPos, GUILayout.MinHeight(innerRect.height * editorData.brushDisplayScale + 32.0f));
innerRect.width *= editorData.brushDisplayScale;
innerRect.height *= editorData.brushDisplayScale;
tk2dGrid.Draw(innerRect);
// palette
Rect rect = brushRenderer.DrawBrush(tileMap, editorData.paletteBrush, editorData.brushDisplayScale, true, editorData.paletteTilesPerRow);
float displayScale = brushRenderer.LastScale;
Rect tileSize = new Rect(0, 0, brushRenderer.TileSizePixels.width * displayScale, brushRenderer.TileSizePixels.height * displayScale);
guiBrushBuilder.HandleGUI(rect, tileSize, editorData.paletteTilesPerRow, tileMap.SpriteCollectionInst, activeBrush);
EditorGUILayout.Separator();
EndHScrollView();
}
EditorGUILayout.Separator();
}
// Draw brush
if (!showLoadSection)
{
editorData.showBrush = EditorGUILayout.Foldout(editorData.showBrush, "Brush");
if (editorData.showBrush)
{
GUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Cursor Tile Opacity");
tk2dTileMapToolbar.workBrushOpacity = EditorGUILayout.Slider(tk2dTileMapToolbar.workBrushOpacity, 0.0f, 1.0f);
GUILayout.EndHorizontal();
Rect innerRect = brushRenderer.GetBrushViewRect(editorData.activeBrush, editorData.paletteTilesPerRow);
activeBrushScrollPos = BeginHScrollView(activeBrushScrollPos, GUILayout.MinHeight(innerRect.height * editorData.brushDisplayScale + 32.0f));
innerRect.width *= editorData.brushDisplayScale;
innerRect.height *= editorData.brushDisplayScale;
tk2dGrid.Draw(innerRect);
brushRenderer.DrawBrush(tileMap, editorData.activeBrush, editorData.brushDisplayScale, false, editorData.paletteTilesPerRow);
EndHScrollView();
EditorGUILayout.Separator();
}
}
}
/// <summary>
/// Initialize tilemap data to sensible values.
/// Mainly, tileSize and tileOffset
/// </summary>
void Init(tk2dTileMapData tileMapData)
{
if (tileMap.SpriteCollectionInst != null) {
tileMapData.tileSize = tileMap.SpriteCollectionInst.spriteDefinitions[0].untrimmedBoundsData[1];
tileMapData.tileOrigin = this.tileMap.SpriteCollectionInst.spriteDefinitions[0].untrimmedBoundsData[0] - tileMap.SpriteCollectionInst.spriteDefinitions[0].untrimmedBoundsData[1] * 0.5f;
}
}
void GetEditorData() {
// Don't guess, load editor data every frame
string editorDataPath = AssetDatabase.GUIDToAssetPath(tileMap.editorDataGUID);
editorData = AssetDatabase.LoadAssetAtPath(editorDataPath, typeof(tk2dTileMapEditorData)) as tk2dTileMapEditorData;
}
public override void OnInspectorGUI()
{
if (tk2dEditorUtility.IsPrefab(target))
{
tk2dGuiUtility.InfoBox("Editor disabled on prefabs.", tk2dGuiUtility.WarningLevel.Error);
return;
}
if (Application.isPlaying)
{
tk2dGuiUtility.InfoBox("Editor disabled while game is running.", tk2dGuiUtility.WarningLevel.Error);
return;
}
GetEditorData();
if (tileMap.data == null || editorData == null || tileMap.Editor__SpriteCollection == null) {
DrawSettingsPanel();
return;
}
if (tileMap.renderData != null)
{
if (tileMap.renderData.transform.position != tileMap.transform.position) {
tileMap.renderData.transform.position = tileMap.transform.position;
}
if (tileMap.renderData.transform.rotation != tileMap.transform.rotation) {
tileMap.renderData.transform.rotation = tileMap.transform.rotation;
}
if (tileMap.renderData.transform.localScale != tileMap.transform.localScale) {
tileMap.renderData.transform.localScale = tileMap.transform.localScale;
}
}
if (!tileMap.AllowEdit)
{
GUILayout.BeginHorizontal();
if (GUILayout.Button("Edit"))
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.RegisterSceneUndo("Tilemap Enter Edit Mode");
#else
tk2dUtil.BeginGroup("Tilemap Enter Edit Mode");
Undo.RegisterCompleteObjectUndo(tileMap, "Tilemap Enter Edit Mode");
#endif
tileMap.BeginEditMode();
InitEditor();
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
tk2dUtil.EndGroup();
#endif
Repaint();
}
GUILayout.EndHorizontal();
return;
}
// Commit
GUILayout.BeginHorizontal();
if (GUILayout.Button("Commit"))
{
#if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
Undo.RegisterSceneUndo("Tilemap Leave Edit Mode");
#else
tk2dUtil.BeginGroup("Tilemap Leave Edit Mode");
Undo.RegisterCompleteObjectUndo(tileMap, "Tilemap Leave Edit Mode");
#endif
tileMap.EndEditMode();
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
tk2dUtil.EndGroup();
#endif
Repaint();
}
GUILayout.EndHorizontal();
EditorGUILayout.Separator();
if (tileMap.editorDataGUID.Length > 0 && editorData == null)
{
// try to load it in
LoadTileMapData();
// failed, so the asset is lost
if (editorData == null)
{
tileMap.editorDataGUID = "";
}
}
if (editorData == null || tileMap.data == null || tileMap.Editor__SpriteCollection == null || !tileMap.AreSpritesInitialized())
{
DrawSettingsPanel();
}
else
{
// In case things have changed
if (tk2dRuntime.TileMap.BuilderUtil.InitDataStore(tileMap))
Build(true);
string[] toolBarButtonNames = System.Enum.GetNames(typeof(tk2dTileMapEditorData.EditMode));
tk2dTileMapEditorData.EditMode newEditMode = (tk2dTileMapEditorData.EditMode)GUILayout.Toolbar((int)editorData.editMode, toolBarButtonNames );
if (newEditMode != editorData.editMode) {
// Force updating the scene view when mode changes
EditorUtility.SetDirty(target);
editorData.editMode = newEditMode;
}
switch (editorData.editMode)
{
case tk2dTileMapEditorData.EditMode.Paint: DrawPaintPanel(); break;
case tk2dTileMapEditorData.EditMode.Color: DrawColorPaintPanel(); break;
case tk2dTileMapEditorData.EditMode.Settings: DrawSettingsPanel(); break;
case tk2dTileMapEditorData.EditMode.Data: DrawTileDataSetupPanel(); break;
}
}
}
void OnSceneGUI()
{
if (!Ready)
{
return;
}
if (sceneGUI != null && tk2dEditorUtility.IsEditable(target))
{
sceneGUI.OnSceneGUI();
}
if (!Application.isPlaying && tileMap.AllowEdit)
{
// build if necessary
if (tk2dRuntime.TileMap.BuilderUtil.InitDataStore(tileMap))
Build(true);
else
Build(false);
}
}
[MenuItem(tk2dMenu.createBase + "TileMap", false, 13850)]
static void Create()
{
tk2dSpriteCollectionData sprColl = null;
if (sprColl == null)
{
// try to inherit from other TileMaps in scene
tk2dTileMap sceneTileMaps = GameObject.FindObjectOfType(typeof(tk2dTileMap)) as tk2dTileMap;
if (sceneTileMaps)
{
sprColl = sceneTileMaps.Editor__SpriteCollection;
}
}
if (sprColl == null)
{
tk2dSpriteCollectionIndex[] spriteCollections = tk2dEditorUtility.GetOrCreateIndex().GetSpriteCollectionIndex();
foreach (var v in spriteCollections)
{
if (v.managedSpriteCollection) continue; // don't wanna pick a managed one
GameObject scgo = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(v.spriteCollectionDataGUID), typeof(GameObject)) as GameObject;
var sc = scgo.GetComponent<tk2dSpriteCollectionData>();
if (sc != null && sc.spriteDefinitions != null && sc.spriteDefinitions.Length > 0 && sc.allowMultipleAtlases == false)
{
sprColl = sc;
break;
}
}
if (sprColl == null)
{
EditorUtility.DisplayDialog("Create TileMap", "Unable to create sprite as no SpriteCollections have been found.", "Ok");
return;
}
}
GameObject go = tk2dEditorUtility.CreateGameObjectInScene("TileMap");
go.transform.position = Vector3.zero;
go.transform.rotation = Quaternion.identity;
tk2dTileMap tileMap = go.AddComponent<tk2dTileMap>();
tileMap.BeginEditMode();
Selection.activeGameObject = go;
Undo.RegisterCreatedObjectUndo(go, "Create TileMap");
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace System.ComponentModel.DataAnnotations
{
/// <summary>
/// Base class for all validation attributes.
/// <para>Override <see cref="IsValid(object, ValidationContext)" /> to implement validation logic.</para>
/// </summary>
/// <remarks>
/// The properties <see cref="ErrorMessageResourceType" /> and <see cref="ErrorMessageResourceName" /> are used to
/// provide
/// a localized error message, but they cannot be set if <see cref="ErrorMessage" /> is also used to provide a
/// non-localized
/// error message.
/// </remarks>
public abstract class ValidationAttribute : Attribute
{
#region Member Fields
private string _errorMessage;
private Func<string> _errorMessageResourceAccessor;
private string _errorMessageResourceName;
private Type _errorMessageResourceType;
private volatile bool _hasBaseIsValid;
private string _defaultErrorMessage;
#endregion
#region All Constructors
/// <summary>
/// Default constructor for any validation attribute.
/// </summary>
/// <remarks>
/// This constructor chooses a very generic validation error message.
/// Developers subclassing ValidationAttribute should use other constructors
/// or supply a better message.
/// </remarks>
protected ValidationAttribute()
: this(() => SR.ValidationAttribute_ValidationError)
{
}
/// <summary>
/// Constructor that accepts a fixed validation error message.
/// </summary>
/// <param name="errorMessage">A non-localized error message to use in <see cref="ErrorMessageString" />.</param>
protected ValidationAttribute(string errorMessage)
: this(() => errorMessage)
{
}
/// <summary>
/// Allows for providing a resource accessor function that will be used by the <see cref="ErrorMessageString" />
/// property to retrieve the error message. An example would be to have something like
/// CustomAttribute() : base( () => MyResources.MyErrorMessage ) {}.
/// </summary>
/// <param name="errorMessageAccessor">The <see cref="Func{T}" /> that will return an error message.</param>
protected ValidationAttribute(Func<string> errorMessageAccessor)
{
// If null, will later be exposed as lack of error message to be able to construct accessor
_errorMessageResourceAccessor = errorMessageAccessor;
}
#endregion
#region Internal Properties
/// <summary>
/// Gets or sets and the default error message string.
/// This message will be used if the user has not set <see cref="ErrorMessage"/>
/// or the <see cref="ErrorMessageResourceType"/> and <see cref="ErrorMessageResourceName"/> pair.
/// This property was added after the public contract for DataAnnotations was created.
/// It is internal to avoid changing the DataAnnotations contract.
/// </summary>
internal string DefaultErrorMessage
{
get
{
return _defaultErrorMessage;
}
set
{
_defaultErrorMessage = value;
_errorMessageResourceAccessor = null;
CustomErrorMessageSet = true;
}
}
#endregion
#region Protected Properties
/// <summary>
/// Gets the localized error message string, coming either from <see cref="ErrorMessage" />, or from evaluating the
/// <see cref="ErrorMessageResourceType" /> and <see cref="ErrorMessageResourceName" /> pair.
/// </summary>
protected string ErrorMessageString
{
get
{
SetupResourceAccessor();
return _errorMessageResourceAccessor();
}
}
/// <summary>
/// A flag indicating whether a developer has customized the attribute's error message by setting any one of
/// ErrorMessage, ErrorMessageResourceName, ErrorMessageResourceType or DefaultErrorMessage.
/// </summary>
internal bool CustomErrorMessageSet { get; private set; }
/// <summary>
/// A flag indicating that the attribute requires a non-null
/// <see cref= System.ComponentModel.DataAnnotations.ValidationContext /> to perform validation.
/// Base class returns false. Override in child classes as appropriate.
/// </summary>
public virtual bool RequiresValidationContext
{
get { return false; }
}
#endregion
#region Public Properties
/// <summary>
/// Gets or sets and explicit error message string.
/// </summary>
/// <value>
/// This property is intended to be used for non-localizable error messages. Use
/// <see cref="ErrorMessageResourceType" /> and <see cref="ErrorMessageResourceName" /> for localizable error messages.
/// </value>
public string ErrorMessage
{
get
{
// If _errorMessage is not set, return the default. This is done to preserve
// behavior prior to the fix where ErrorMessage showed the non-null message to use.
return _errorMessage ?? _defaultErrorMessage;
}
set
{
_errorMessage = value;
_errorMessageResourceAccessor = null;
CustomErrorMessageSet = true;
// Explicitly setting ErrorMessage also sets DefaultErrorMessage if null.
// This prevents subsequent read of ErrorMessage from returning default.
if (value == null)
{
_defaultErrorMessage = null;
}
}
}
/// <summary>
/// Gets or sets the resource name (property name) to use as the key for lookups on the resource type.
/// </summary>
/// <value>
/// Use this property to set the name of the property within <see cref="ErrorMessageResourceType" />
/// that will provide a localized error message. Use <see cref="ErrorMessage" /> for non-localized error messages.
/// </value>
public string ErrorMessageResourceName
{
get { return _errorMessageResourceName; }
set
{
_errorMessageResourceName = value;
_errorMessageResourceAccessor = null;
CustomErrorMessageSet = true;
}
}
/// <summary>
/// Gets or sets the resource type to use for error message lookups.
/// </summary>
/// <value>
/// Use this property only in conjunction with <see cref="ErrorMessageResourceName" />. They are
/// used together to retrieve localized error messages at runtime.
/// <para>
/// Use <see cref="ErrorMessage" /> instead of this pair if error messages are not localized.
/// </para>
/// </value>
public Type ErrorMessageResourceType
{
get { return _errorMessageResourceType; }
set
{
_errorMessageResourceType = value;
_errorMessageResourceAccessor = null;
CustomErrorMessageSet = true;
}
}
#endregion
#region Private Methods
/// <summary>
/// Validates the configuration of this attribute and sets up the appropriate error string accessor.
/// This method bypasses all verification once the ResourceAccessor has been set.
/// </summary>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
private void SetupResourceAccessor()
{
if (_errorMessageResourceAccessor == null)
{
string localErrorMessage = ErrorMessage;
bool resourceNameSet = !string.IsNullOrEmpty(_errorMessageResourceName);
bool errorMessageSet = !string.IsNullOrEmpty(_errorMessage);
bool resourceTypeSet = _errorMessageResourceType != null;
bool defaultMessageSet = !string.IsNullOrEmpty(_defaultErrorMessage);
// The following combinations are illegal and throw InvalidOperationException:
// 1) Both ErrorMessage and ErrorMessageResourceName are set, or
// 2) None of ErrorMessage, ErrorMessageReourceName, and DefaultErrorMessage are set.
if ((resourceNameSet && errorMessageSet) || !(resourceNameSet || errorMessageSet || defaultMessageSet))
{
throw new InvalidOperationException(
SR.ValidationAttribute_Cannot_Set_ErrorMessage_And_Resource);
}
// Must set both or neither of ErrorMessageResourceType and ErrorMessageResourceName
if (resourceTypeSet != resourceNameSet)
{
throw new InvalidOperationException(
SR.ValidationAttribute_NeedBothResourceTypeAndResourceName);
}
// If set resource type (and we know resource name too), then go setup the accessor
if (resourceNameSet)
{
SetResourceAccessorByPropertyLookup();
}
else
{
// Here if not using resource type/name -- the accessor is just the error message string,
// which we know is not empty to have gotten this far.
_errorMessageResourceAccessor = delegate
{
// We captured error message to local in case it changes before accessor runs
return localErrorMessage;
};
}
}
}
private void SetResourceAccessorByPropertyLookup()
{
if (_errorMessageResourceType != null && !string.IsNullOrEmpty(_errorMessageResourceName))
{
var property = _errorMessageResourceType
.GetTypeInfo().GetDeclaredProperty(_errorMessageResourceName);
if (property != null && !ValidationAttributeStore.IsStatic(property))
{
property = null;
}
if (property != null)
{
var propertyGetter = property.GetMethod;
// We only support internal and public properties
if (propertyGetter == null || (!propertyGetter.IsAssembly && !propertyGetter.IsPublic))
{
// Set the property to null so the exception is thrown as if the property wasn't found
property = null;
}
}
if (property == null)
{
throw new InvalidOperationException(
string.Format(
CultureInfo.CurrentCulture,
SR.ValidationAttribute_ResourceTypeDoesNotHaveProperty,
_errorMessageResourceType.FullName,
_errorMessageResourceName));
}
if (property.PropertyType != typeof(string))
{
throw new InvalidOperationException(
string.Format(
CultureInfo.CurrentCulture,
SR.ValidationAttribute_ResourcePropertyNotStringType,
property.Name,
_errorMessageResourceType.FullName));
}
_errorMessageResourceAccessor = delegate { return (string)property.GetValue(null, null); };
}
else
{
throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
SR.ValidationAttribute_NeedBothResourceTypeAndResourceName));
}
}
#endregion
#region Protected & Public Methods
/// <summary>
/// Formats the error message to present to the user.
/// </summary>
/// <remarks>
/// The error message will be re-evaluated every time this function is called.
/// It applies the <paramref name="name" /> (for example, the name of a field) to the formated error message, resulting
/// in something like "The field 'name' has an incorrect value".
/// <para>
/// Derived classes can override this method to customize how errors are generated.
/// </para>
/// <para>
/// The base class implementation will use <see cref="ErrorMessageString" /> to obtain a localized
/// error message from properties within the current attribute. If those have not been set, a generic
/// error message will be provided.
/// </para>
/// </remarks>
/// <param name="name">The user-visible name to include in the formatted message.</param>
/// <returns>The localized string describing the validation error</returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
public virtual string FormatErrorMessage(string name)
{
return string.Format(CultureInfo.CurrentCulture, ErrorMessageString, name);
}
/// <summary>
/// Gets the value indicating whether or not the specified <paramref name="value" /> is valid
/// with respect to the current validation attribute.
/// <para>
/// Derived classes should not override this method as it is only available for backwards compatibility.
/// Instead, implement <see cref="IsValid(object, ValidationContext)" />.
/// </para>
/// </summary>
/// <remarks>
/// The preferred public entry point for clients requesting validation is the <see cref="GetValidationResult" />
/// method.
/// </remarks>
/// <param name="value">The value to validate</param>
/// <returns><c>true</c> if the <paramref name="value" /> is acceptable, <c>false</c> if it is not acceptable</returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
/// <exception cref="NotImplementedException">
/// is thrown when neither overload of IsValid has been implemented
/// by a derived class.
/// </exception>
public virtual bool IsValid(object value)
{
if (!_hasBaseIsValid)
{
// track that this method overload has not been overridden.
_hasBaseIsValid = true;
}
// call overridden method.
return IsValid(value, null) == ValidationResult.Success;
}
/// <summary>
/// Protected virtual method to override and implement validation logic.
/// <para>
/// Derived classes should override this method instead of <see cref="IsValid(object)" />, which is deprecated.
/// </para>
/// </summary>
/// <param name="value">The value to validate.</param>
/// <param name="validationContext">
/// A <see cref="ValidationContext" /> instance that provides
/// context about the validation operation, such as the object and member being validated.
/// </param>
/// <returns>
/// When validation is valid, <see cref="ValidationResult.Success" />.
/// <para>
/// When validation is invalid, an instance of <see cref="ValidationResult" />.
/// </para>
/// </returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
/// <exception cref="NotImplementedException">
/// is thrown when <see cref="IsValid(object, ValidationContext)" />
/// has not been implemented by a derived class.
/// </exception>
protected virtual ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (_hasBaseIsValid)
{
// this means neither of the IsValid methods has been overridden, throw.
throw NotImplemented.ByDesignWithMessage(
SR.ValidationAttribute_IsValid_NotImplemented);
}
var result = ValidationResult.Success;
// call overridden method.
if (!IsValid(value))
{
string[] memberNames = validationContext.MemberName != null
? new string[] { validationContext.MemberName }
: null;
result = new ValidationResult(FormatErrorMessage(validationContext.DisplayName), memberNames);
}
return result;
}
/// <summary>
/// Tests whether the given <paramref name="value" /> is valid with respect to the current
/// validation attribute without throwing a <see cref="ValidationException" />
/// </summary>
/// <remarks>
/// If this method returns <see cref="ValidationResult.Success" />, then validation was successful, otherwise
/// an instance of <see cref="ValidationResult" /> will be returned with a guaranteed non-null
/// <see cref="ValidationResult.ErrorMessage" />.
/// </remarks>
/// <param name="value">The value to validate</param>
/// <param name="validationContext">
/// A <see cref="ValidationContext" /> instance that provides
/// context about the validation operation, such as the object and member being validated.
/// </param>
/// <returns>
/// When validation is valid, <see cref="ValidationResult.Success" />.
/// <para>
/// When validation is invalid, an instance of <see cref="ValidationResult" />.
/// </para>
/// </returns>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
/// <exception cref="ArgumentNullException">When <paramref name="validationContext" /> is null.</exception>
/// <exception cref="NotImplementedException">
/// is thrown when <see cref="IsValid(object, ValidationContext)" />
/// has not been implemented by a derived class.
/// </exception>
public ValidationResult GetValidationResult(object value, ValidationContext validationContext)
{
if (validationContext == null)
{
throw new ArgumentNullException("validationContext");
}
var result = IsValid(value, validationContext);
// If validation fails, we want to ensure we have a ValidationResult that guarantees it has an ErrorMessage
if (result != null)
{
if (string.IsNullOrEmpty(result.ErrorMessage))
{
var errorMessage = FormatErrorMessage(validationContext.DisplayName);
result = new ValidationResult(errorMessage, result.MemberNames);
}
}
return result;
}
/// <summary>
/// Validates the specified <paramref name="value" /> and throws <see cref="ValidationException" /> if it is not.
/// <para>
/// The overloaded <see cref="Validate(object, ValidationContext)" /> is the recommended entry point as it
/// can provide additional context to the <see cref="ValidationAttribute" /> being validated.
/// </para>
/// </summary>
/// <remarks>
/// This base method invokes the <see cref="IsValid(object)" /> method to determine whether or not the
/// <paramref name="value" /> is acceptable. If <see cref="IsValid(object)" /> returns <c>false</c>, this base
/// method will invoke the <see cref="FormatErrorMessage" /> to obtain a localized message describing
/// the problem, and it will throw a <see cref="ValidationException" />
/// </remarks>
/// <param name="value">The value to validate</param>
/// <param name="name">The string to be included in the validation error message if <paramref name="value" /> is not valid</param>
/// <exception cref="ValidationException">
/// is thrown if <see cref="IsValid(object)" /> returns <c>false</c>.
/// </exception>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
public void Validate(object value, string name)
{
if (!IsValid(value))
{
throw new ValidationException(FormatErrorMessage(name), this, value);
}
}
/// <summary>
/// Validates the specified <paramref name="value" /> and throws <see cref="ValidationException" /> if it is not.
/// </summary>
/// <remarks>
/// This method invokes the <see cref="IsValid(object, ValidationContext)" /> method
/// to determine whether or not the <paramref name="value" /> is acceptable given the
/// <paramref name="validationContext" />.
/// If that method doesn't return <see cref="ValidationResult.Success" />, this base method will throw
/// a <see cref="ValidationException" /> containing the <see cref="ValidationResult" /> describing the problem.
/// </remarks>
/// <param name="value">The value to validate</param>
/// <param name="validationContext">Additional context that may be used for validation. It cannot be null.</param>
/// <exception cref="ValidationException">
/// is thrown if <see cref="IsValid(object, ValidationContext)" />
/// doesn't return <see cref="ValidationResult.Success" />.
/// </exception>
/// <exception cref="InvalidOperationException"> is thrown if the current attribute is malformed.</exception>
/// <exception cref="NotImplementedException">
/// is thrown when <see cref="IsValid(object, ValidationContext)" />
/// has not been implemented by a derived class.
/// </exception>
public void Validate(object value, ValidationContext validationContext)
{
if (validationContext == null)
{
throw new ArgumentNullException("validationContext");
}
ValidationResult result = GetValidationResult(value, validationContext);
if (result != null)
{
// Convenience -- if implementation did not fill in an error message,
throw new ValidationException(result, this, value);
}
}
#endregion
}
}
| |
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
#if UNITY_5_0 || UNITY_5_1
using System.Reflection;
#endif
namespace Fungus.EditorUtils
{
[CustomEditor(typeof(FungusEditorResources))]
internal class FungusEditorResourcesInspector : Editor
{
public override void OnInspectorGUI()
{
if (serializedObject.FindProperty("updateOnReloadScripts").boolValue)
{
GUILayout.Label("Updating...");
}
else
{
if (GUILayout.Button("Sync with EditorResources folder"))
{
FungusEditorResources.GenerateResourcesScript();
}
DrawDefaultInspector();
}
}
}
// Handle reimporting all assets
internal class EditorResourcesPostProcessor : AssetPostprocessor
{
private static void OnPostprocessAllAssets(string[] importedAssets, string[] _, string[] __, string[] ___)
{
foreach (var path in importedAssets)
{
if (path.EndsWith("FungusEditorResources.asset"))
{
var asset = AssetDatabase.LoadAssetAtPath(path, typeof(FungusEditorResources)) as FungusEditorResources;
if (asset != null)
{
FungusEditorResources.UpdateTextureReferences(asset);
AssetDatabase.SaveAssets();
return;
}
}
}
}
}
internal partial class FungusEditorResources : ScriptableObject
{
[Serializable]
internal class EditorTexture
{
[SerializeField] private Texture2D free;
[SerializeField] private Texture2D pro;
public Texture2D Texture2D
{
get { return EditorGUIUtility.isProSkin && pro != null ? pro : free; }
}
public EditorTexture(Texture2D free, Texture2D pro)
{
this.free = free;
this.pro = pro;
}
}
private static FungusEditorResources instance;
private static readonly string editorResourcesFolderName = "\"EditorResources\"";
private static readonly string PartialEditorResourcesPath = System.IO.Path.Combine("Fungus", "EditorResources");
[SerializeField] [HideInInspector] private bool updateOnReloadScripts = false;
internal static FungusEditorResources Instance
{
get
{
if (instance == null)
{
var guids = AssetDatabase.FindAssets("FungusEditorResources t:FungusEditorResources");
if (guids.Length == 0)
{
instance = ScriptableObject.CreateInstance(typeof(FungusEditorResources)) as FungusEditorResources;
AssetDatabase.CreateAsset(instance, GetRootFolder() + "/FungusEditorResources.asset");
}
else
{
if (guids.Length > 1)
{
Debug.LogError("Multiple FungusEditorResources assets found!");
}
var path = AssetDatabase.GUIDToAssetPath(guids[0]);
instance = AssetDatabase.LoadAssetAtPath(path, typeof(FungusEditorResources)) as FungusEditorResources;
}
}
return instance;
}
}
private static string GetRootFolder()
{
var res = AssetDatabase.FindAssets(editorResourcesFolderName);
foreach (var item in res)
{
var path = AssetDatabase.GUIDToAssetPath(item);
var safePath = System.IO.Path.GetFullPath(path);
if (safePath.IndexOf(PartialEditorResourcesPath) != -1)
return path;
}
return string.Empty;
}
internal static void GenerateResourcesScript()
{
// Get all unique filenames
var textureNames = new HashSet<string>();
var guids = AssetDatabase.FindAssets("t:Texture2D", new [] { GetRootFolder() });
var paths = guids.Select(guid => AssetDatabase.GUIDToAssetPath(guid));
foreach (var path in paths)
{
textureNames.Add(Path.GetFileNameWithoutExtension(path));
}
var scriptGuid = AssetDatabase.FindAssets("FungusEditorResources t:MonoScript")[0];
var relativePath = AssetDatabase.GUIDToAssetPath(scriptGuid).Replace("FungusEditorResources.cs", "FungusEditorResourcesGenerated.cs");
var absolutePath = Application.dataPath + relativePath.Substring("Assets".Length);
using (var writer = new StreamWriter(absolutePath))
{
writer.WriteLine("// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).");
writer.WriteLine("// It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)");
writer.WriteLine("");
writer.WriteLine("#pragma warning disable 0649");
writer.WriteLine("");
writer.WriteLine("using UnityEngine;");
writer.WriteLine("");
writer.WriteLine("namespace Fungus.EditorUtils");
writer.WriteLine("{");
writer.WriteLine(" internal partial class FungusEditorResources : ScriptableObject");
writer.WriteLine(" {");
foreach (var name in textureNames)
{
writer.WriteLine(" [SerializeField] private EditorTexture " + name + ";");
}
writer.WriteLine("");
foreach (var name in textureNames)
{
var pascalCase = string.Join("", name.Split(new [] { '_' }, StringSplitOptions.RemoveEmptyEntries).Select(
s => s.Substring(0, 1).ToUpper() + s.Substring(1)).ToArray()
);
writer.WriteLine(" public static Texture2D " + pascalCase + " { get { return Instance." + name + ".Texture2D; } }");
}
writer.WriteLine(" }");
writer.WriteLine("}");
}
Instance.updateOnReloadScripts = true;
AssetDatabase.ImportAsset(relativePath);
}
[DidReloadScripts]
private static void OnDidReloadScripts()
{
if (Instance.updateOnReloadScripts)
{
UpdateTextureReferences(Instance);
}
}
internal static void UpdateTextureReferences(FungusEditorResources instance)
{
// Iterate through all fields in instance and set texture references
var serializedObject = new SerializedObject(instance);
var prop = serializedObject.GetIterator();
var rootFolder = new [] { GetRootFolder() };
prop.NextVisible(true);
while (prop.NextVisible(false))
{
if (prop.propertyType == SerializedPropertyType.Generic)
{
var guids = AssetDatabase.FindAssets(prop.name + " t:Texture2D", rootFolder);
var paths = guids.Select(guid => AssetDatabase.GUIDToAssetPath(guid)).Where(
path => path.Contains(prop.name + ".")
);
foreach (var path in paths)
{
var texture = AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)) as Texture2D;
if (path.ToLower().Contains("/pro/"))
{
prop.FindPropertyRelative("pro").objectReferenceValue = texture;
}
else
{
prop.FindPropertyRelative("free").objectReferenceValue = texture;
}
}
}
}
serializedObject.FindProperty("updateOnReloadScripts").boolValue = false;
// The ApplyModifiedPropertiesWithoutUndo() function wasn't documented until Unity 5.2
#if UNITY_5_0 || UNITY_5_1
var flags = BindingFlags.Instance | BindingFlags.NonPublic;
var applyMethod = typeof(SerializedObject).GetMethod("ApplyModifiedPropertiesWithoutUndo", flags);
applyMethod.Invoke(serializedObject, null);
#else
serializedObject.ApplyModifiedPropertiesWithoutUndo();
#endif
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using WhatsAppApi.Parser;
using WhatsAppApi.Settings;
namespace WhatsAppApi.Register
{
public static class WhatsRegisterV2
{
public static string GenerateIdentity(string phoneNumber, string salt = "")
{
return (phoneNumber + salt).Reverse().ToSHAString();
}
public static string GetToken(string number)
{
return WaToken.GenerateTokenAndroid(number);
}
public static bool RequestCode(string phoneNumber, out string password, string method = "sms", string id = null)
{
string response = string.Empty;
return RequestCode(phoneNumber, out password, out response, method, id);
}
public static bool RequestCode(string phoneNumber, out string password, out string response, string method = "sms", string id = null)
{
string request = string.Empty;
return RequestCode(phoneNumber, out password, out request, out response, method, id);
}
public static bool CheckCredentials(string phoneNumber, out string response, string id = null)
{
try
{
if (string.IsNullOrEmpty(id))
{
//Auto-Generate
id = GenerateIdentity(phoneNumber);
}
PhoneNumber pn = new PhoneNumber(phoneNumber);
String countryCode = (pn.ISO3166 != "") ? pn.ISO3166 : "US";
String langCode = (pn.ISO639 != "") ? pn.ISO639 : "en";
byte[] sha256bytes = new byte[20];
new Random().NextBytes(sha256bytes);
NameValueCollection QueryStringParameters = new NameValueCollection();
QueryStringParameters.Add("cc", pn.CC);
QueryStringParameters.Add("in", pn.Number);
QueryStringParameters.Add("lg", langCode);
QueryStringParameters.Add("lc", countryCode);
QueryStringParameters.Add("id", id);
QueryStringParameters.Add("mistyped", "6");
QueryStringParameters.Add("network_radio_type", "1");
QueryStringParameters.Add("simnum", "1");
QueryStringParameters.Add("s", "");
QueryStringParameters.Add("copiedrc", "1");
QueryStringParameters.Add("hasinrc", "1");
QueryStringParameters.Add("rcmatch", "1");
QueryStringParameters.Add("pid", new Random().Next(100, 9999).ToString());
QueryStringParameters.Add("extexist", "1");
QueryStringParameters.Add("extstate", "1");
NameValueCollection RequestHttpHeaders = new NameValueCollection();
RequestHttpHeaders.Add("User-Agent", WhatsConstants.UserAgent);
RequestHttpHeaders.Add("Accept", "text/json");
response = GetResponse("https://" + WhatsConstants.WhatsAppCheckHost, QueryStringParameters, RequestHttpHeaders);
if (!response.GetJsonValue("status").Equals("ok"))
{
/*
$this->eventManager()->fire('onCredentialsBad',
[
$this->phoneNumber,
$response->status,
$response->reason,
]);
*/
return false;
}
else
{
/*
$this->eventManager()->fire('onCredentialsGood',
[
$this->phoneNumber,
$response->login,
$response->pw,
$response->type,
$response->expiration,
$response->kind,
$response->price,
$response->cost,
$response->currency,
$response->price_expiration,
]);
*/
return true;
}
}
catch (Exception e)
{
response = e.Message;
return false;
}
}
public static bool RequestCode(string phoneNumber, out string password, out string request, out string response, string method = "sms", string id = null, string carrierName = "T-Mobile5")
{
response = null;
password = null;
request = null;
try
{
if (string.IsNullOrEmpty(id))
{
//Auto-Generate
id = GenerateIdentity(phoneNumber);
}
PhoneNumber pn = new PhoneNumber(phoneNumber);
string token = System.Uri.EscapeDataString(WhatsRegisterV2.GetToken(pn.Number));
String countryCode = (pn.ISO3166 != "") ? pn.ISO3166 : "US";
String langCode = (pn.ISO639 != "") ? pn.ISO639 : "en";
String mnc = pn.MNC;
if (carrierName != null)
{
mnc = PhoneNumber.DetectMnc(countryCode, carrierName);
}
byte[] sha256bytes = new byte[20];
new Random().NextBytes(sha256bytes);
NameValueCollection QueryStringParameters = new NameValueCollection();
QueryStringParameters.Add("cc", pn.CC);
QueryStringParameters.Add("in", pn.Number);
QueryStringParameters.Add("lg", langCode);
QueryStringParameters.Add("lc", countryCode);
QueryStringParameters.Add("id", id);
QueryStringParameters.Add("token", token);
QueryStringParameters.Add("mistyped", "6");
QueryStringParameters.Add("network_radio_type", "1");
QueryStringParameters.Add("simnum", "1");
QueryStringParameters.Add("s", "");
QueryStringParameters.Add("copiedrc", "1");
QueryStringParameters.Add("hasinrc", "1");
QueryStringParameters.Add("rcmatch", "1");
QueryStringParameters.Add("pid", new Random().Next(100, 9999).ToString());
QueryStringParameters.Add("rchash", BitConverter.ToString(HashAlgorithm.Create("sha256").ComputeHash(sha256bytes)));
QueryStringParameters.Add("anhash", BitConverter.ToString(HashAlgorithm.Create("md5").ComputeHash(sha256bytes)));
QueryStringParameters.Add("extexist", "1");
QueryStringParameters.Add("extstate", "1");
QueryStringParameters.Add("mcc", pn.MCC);
QueryStringParameters.Add("mnc", mnc);
QueryStringParameters.Add("sim_mcc", pn.MCC);
QueryStringParameters.Add("sim_mnc", mnc);
QueryStringParameters.Add("method", method);
NameValueCollection RequestHttpHeaders = new NameValueCollection();
RequestHttpHeaders.Add("User-Agent", WhatsConstants.UserAgent);
RequestHttpHeaders.Add("Accept", "text/json");
response = GetResponse("https://" + WhatsConstants.WhatsAppRequestHost, QueryStringParameters, RequestHttpHeaders);
password = response.GetJsonValue("pw");
if (!string.IsNullOrEmpty(password))
{
return true;
}
return (response.GetJsonValue("status") == "sent");
}
catch (Exception e)
{
response = e.Message;
return false;
}
}
public static string RegisterCode(string phoneNumber, string code, string id = null)
{
string response = string.Empty;
return WhatsRegisterV2.RegisterCode(phoneNumber, code, out response, id);
}
public static string RegisterCode(string phoneNumber, string code, out string response, string id = null)
{
response = string.Empty;
try
{
if (string.IsNullOrEmpty(id))
{
//Auto Generate
id = GenerateIdentity(phoneNumber);
}
PhoneNumber pn = new PhoneNumber(phoneNumber);
String countryCode = (pn.ISO3166 != "") ? pn.ISO3166 : "US";
String langCode = (pn.ISO639 != "") ? pn.ISO639 : "en";
byte[] sha256bytes = new byte[20];
new Random().NextBytes(sha256bytes);
NameValueCollection QueryStringParameters = new NameValueCollection();
QueryStringParameters.Add("cc", pn.CC);
QueryStringParameters.Add("in", pn.Number);
QueryStringParameters.Add("lg", langCode);
QueryStringParameters.Add("lc", countryCode);
QueryStringParameters.Add("id", id);
QueryStringParameters.Add("mistyped", "6");
QueryStringParameters.Add("network_radio_type", "1");
QueryStringParameters.Add("simnum", "1");
QueryStringParameters.Add("s", "");
QueryStringParameters.Add("copiedrc", "1");
QueryStringParameters.Add("hasinrc", "1");
QueryStringParameters.Add("rcmatch", "1");
QueryStringParameters.Add("pid", new Random().Next(100, 9999).ToString());
QueryStringParameters.Add("rchash", BitConverter.ToString(HashAlgorithm.Create("sha256").ComputeHash(sha256bytes)));
QueryStringParameters.Add("anhash", BitConverter.ToString(HashAlgorithm.Create("md5").ComputeHash(sha256bytes)));
QueryStringParameters.Add("extexist", "1");
QueryStringParameters.Add("extstate", "1");
QueryStringParameters.Add("code", code);
NameValueCollection RequestHttpHeaders = new NameValueCollection();
RequestHttpHeaders.Add("User-Agent", WhatsConstants.UserAgent);
RequestHttpHeaders.Add("Accept", "text/json");
response = GetResponse("https://" + WhatsConstants.WhatsAppRegisterHost, QueryStringParameters, RequestHttpHeaders);
if (response.GetJsonValue("status") == "ok")
{
return response.GetJsonValue("pw");
}
return null;
}
catch
{
return null;
}
}
public static string RequestExist(string phoneNumber, string id = null)
{
string response = string.Empty;
return RequestExist(phoneNumber, out response, id);
}
public static string RequestExist(string phoneNumber, out string response, string id = null)
{
response = string.Empty;
try
{
if (String.IsNullOrEmpty(id))
{
id = GenerateIdentity(phoneNumber);
}
PhoneNumber pn = new PhoneNumber(phoneNumber);
String countryCode = (pn.ISO3166 != "") ? pn.ISO3166 : "US";
String langCode = (pn.ISO639 != "") ? pn.ISO639 : "en";
byte[] sha256bytes = new byte[20];
new Random().NextBytes(sha256bytes);
NameValueCollection QueryStringParameters = new NameValueCollection();
QueryStringParameters.Add("cc", pn.CC);
QueryStringParameters.Add("in", pn.Number);
QueryStringParameters.Add("lg", langCode);
QueryStringParameters.Add("lc", countryCode);
QueryStringParameters.Add("id", id);
QueryStringParameters.Add("mistyped", "6");
QueryStringParameters.Add("network_radio_type", "1");
QueryStringParameters.Add("simnum", "1");
QueryStringParameters.Add("s", "");
QueryStringParameters.Add("copiedrc", "1");
QueryStringParameters.Add("hasinrc", "1");
QueryStringParameters.Add("rcmatch", "1");
QueryStringParameters.Add("pid", new Random().Next(100, 9999).ToString());
QueryStringParameters.Add("extexist", "1");
QueryStringParameters.Add("extstate", "1");
NameValueCollection RequestHttpHeaders = new NameValueCollection();
RequestHttpHeaders.Add("User-Agent", WhatsConstants.UserAgent);
RequestHttpHeaders.Add("Accept", "text/json");
response = GetResponse("https://" + WhatsConstants.WhatsAppCheckHost, QueryStringParameters, RequestHttpHeaders);
if (response.GetJsonValue("status") == "ok")
{
return response.GetJsonValue("pw");
}
return null;
}
catch
{
return null;
}
}
private static string GetResponse(string url, NameValueCollection QueryStringParameters = null, NameValueCollection RequestHeaders = null)
{
string ResponseText = null;
using (WebClient client = new WebClient())
{
try
{
if (RequestHeaders != null)
{
if (RequestHeaders.Count > 0)
{
foreach (string header in RequestHeaders.AllKeys)
client.Headers.Add(header, RequestHeaders[header]);
}
}
if (QueryStringParameters != null)
{
if (QueryStringParameters.Count > 0)
{
foreach (string parm in QueryStringParameters.AllKeys)
client.QueryString.Add(parm, QueryStringParameters[parm]);
}
}
byte[] ResponseBytes = client.DownloadData(url);
ResponseText = Encoding.UTF8.GetString(ResponseBytes);
}
catch (WebException exception)
{
if (exception.Response != null)
{
Stream responseStream = exception.Response.GetResponseStream();
if (responseStream != null)
{
using (StreamReader reader = new System.IO.StreamReader(responseStream))
{
return reader.ReadToEnd();
}
}
}
}
}
return ResponseText;
}
private static string GetResponse(string uri)
{
HttpWebRequest request = HttpWebRequest.Create(new Uri(uri)) as HttpWebRequest;
request.KeepAlive = false;
request.UserAgent = WhatsConstants.UserAgent;
request.Accept = "text/json";
using (StreamReader reader = new System.IO.StreamReader(request.GetResponse().GetResponseStream()))
{
return reader.ReadLine();
}
}
private static string ToSHAString(this IEnumerable<char> s)
{
return new string(s.ToArray()).ToSHAString();
}
public static string UrlEncode(string data)
{
StringBuilder sb = new StringBuilder();
foreach (char c in data.ToCharArray())
{
int i = (int)c;
if (
(
i >= 0 && i <= 31
)
||
(
i >= 32 && i <= 47
)
||
(
i >= 58 && i <= 64
)
||
(
i >= 91 && i <= 96
)
||
(
i >= 123 && i <= 126
)
||
i > 127
)
{
//encode
sb.Append('%');
sb.AppendFormat("{0:x2}", (byte)c);
}
else
{
//do not encode
sb.Append(c);
}
}
return sb.ToString();
}
private static string ToSHAString(this string s)
{
byte[] data = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(s));
string str = Encoding.GetEncoding("iso-8859-1").GetString(data);
str = WhatsRegisterV2.UrlEncode(str).ToLower();
return str;
}
private static string ToMD5String(this IEnumerable<char> s)
{
return new string(s.ToArray()).ToMD5String();
}
private static string ToMD5String(this string s)
{
return string.Join(string.Empty, MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(s)).Select(item => item.ToString("x2")).ToArray());
}
private static void GetLanguageAndLocale(this CultureInfo self, out string language, out string locale)
{
string name = self.Name;
int n1 = name.IndexOf('-');
if (n1 > 0)
{
int n2 = name.LastIndexOf('-');
language = name.Substring(0, n1);
locale = name.Substring(n2 + 1);
}
else
{
language = name;
switch (language)
{
case "cs":
locale = "CZ";
return;
case "da":
locale = "DK";
return;
case "el":
locale = "GR";
return;
case "ja":
locale = "JP";
return;
case "ko":
locale = "KR";
return;
case "sv":
locale = "SE";
return;
case "sr":
locale = "RS";
return;
}
locale = language.ToUpper();
}
}
private static string GetJsonValue(this string s, string parameter)
{
Match match;
if ((match = Regex.Match(s, string.Format("\"?{0}\"?:\"(?<Value>.+?)\"", parameter), RegexOptions.Singleline | RegexOptions.IgnoreCase)).Success)
{
return match.Groups["Value"].Value;
}
return null;
}
}
}
| |
using System;
using System.Text;
using StackingEntities.Model.Enums;
using StackingEntities.Model.Metadata;
using StackingEntities.Model.Objects.SimpleTypes;
using DoubleList = System.Collections.ObjectModel.ObservableCollection<StackingEntities.Model.Objects.SimpleTypes.SimpleDouble>;
namespace StackingEntities.Model.Entities.Mobs.Friendly
{
[Serializable]
internal class ArmorStand : MobBase
{
public ArmorStand() : base(2)
{
Type = EntityType.ArmorStand;
}
#region Pose
[EntityDescriptor("Pose", "Body Pose", fixedSize: true, dgRowPath: "Name")]
public DoubleList BodyPose { get; } = new DoubleList { new SimpleDouble("X"), new SimpleDouble("Y"), new SimpleDouble("Z") };
[EntityDescriptor("Pose", "Head Pose", fixedSize: true, dgRowPath: "Name")]
public DoubleList HeadPose { get; } = new DoubleList { new SimpleDouble("X"), new SimpleDouble("Y"), new SimpleDouble("Z") };
[EntityDescriptor("Pose", "Left Arm Pose", fixedSize: true, dgRowPath: "Name")]
public DoubleList LeftArmPose { get; } = new DoubleList { new SimpleDouble("X"), new SimpleDouble("Y"), new SimpleDouble("Z") };
[EntityDescriptor("Pose", "Right Arm Pose", fixedSize: true, dgRowPath: "Name")]
public DoubleList RightArmPose { get; } = new DoubleList { new SimpleDouble("X"), new SimpleDouble("Y"), new SimpleDouble("Z") };
[EntityDescriptor("Pose", "Left Leg Pose", fixedSize: true, dgRowPath: "Name")]
public DoubleList LeftLegPose { get; } = new DoubleList { new SimpleDouble("X"), new SimpleDouble("Y"), new SimpleDouble("Z") };
[EntityDescriptor("Pose", "Right Leg Pose", fixedSize: true, dgRowPath: "Name")]
public DoubleList RightLegPose { get; } = new DoubleList { new SimpleDouble("X"), new SimpleDouble("Y"), new SimpleDouble("Z") };
#endregion
#region Slots
[EntityDescriptor("Disabled Slots", "Hands")]
public DisabledSlots HandsDisabledSlots { get; set; } = DisabledSlots.All;
[EntityDescriptor("Disabled Slots", "Fee")]
public DisabledSlots FeetDisabledSlots { get; set; }
[EntityDescriptor("Disabled Slots", "Legs")]
public DisabledSlots LegsDisabledSlots { get; set; }
[EntityDescriptor("Disabled Slots", "Chest")]
public DisabledSlots ChestDisabledSlots { get; set; }
[EntityDescriptor("Disabled Slots", "Head")]
public DisabledSlots HeadDisabledSlots { get; set; }
#endregion
#region Bools
private bool _marker;
[EntityDescriptor("Armor Stand Options", "Marker")]
public bool Marker
{
get { return _marker; }
set
{
_marker = value;
PropChanged("Display");
}
}
private bool _invisible;
[EntityDescriptor("Armor Stand Options", "Invisible")]
public bool Invisible
{
get { return _invisible; }
set
{
_invisible = value;
PropChanged("Display");
}
}
private bool _noBasePlate;
[EntityDescriptor("Armor Stand Options", "No Baseplate")]
public bool NoBasePlate
{
get { return _noBasePlate; }
set
{
_noBasePlate = value;
PropChanged("Display");
}
}
private bool _noGravity;
[EntityDescriptor("Armor Stand Options", "No Gravity")]
public bool NoGravity
{
get { return _noGravity; }
set
{
_noGravity = value;
PropChanged("Display");
}
}
private bool _showArms;
[EntityDescriptor("Armor Stand Options", "Show Arms")]
public bool ShowArms
{
get { return _showArms; }
set
{
_showArms = value;
PropChanged("Display");
}
}
private bool _small;
[EntityDescriptor("Armor Stand Options", "Small")]
public bool Small
{
get { return _small; }
set
{
_small = value;
PropChanged("Display");
}
}
#endregion
public override string Display
{
get
{
var b = new StringBuilder(base.Display);
if (Small)
b.Append("Small ");
if (ShowArms)
b.Append("Armed ");
if (Invisible)
b.Append("Invisible ");
if (Marker)
b.Append("Marker ");
if (NoBasePlate)
b.Append("w/o Baseplate ");
if (NoBasePlate && NoGravity)
b.Append("or Gravity");
else if (NoGravity)
b.Append("w/o Gravity");
//b.Append("Armor Stand");
return b.ToString();
}
}
public override string DisplayImage => "/StackingEntities.Resources;component/Images/Other/ArmorStand.png";
public override string GenerateJson(bool topLevel)
{
var b = new StringBuilder(base.GenerateJson(topLevel));
//DisabledSlots
if (Marker)
b.Append("Marker:1b,");
if (Invisible)
b.Append("Invisible:1b,");
if (NoBasePlate)
b.Append("NoBasePlate:1b,");
if (NoGravity)
b.Append("NoGravity:1b,");
if (ShowArms)
b.Append("ShowArms:1b,");
if (Small)
b.Append("Small:1b,");
uint slots = 0;
if ((HandsDisabledSlots & DisabledSlots.Remove) == DisabledSlots.Remove)
slots |= 1;
if ((HandsDisabledSlots & DisabledSlots.Replace) == DisabledSlots.Replace)
slots |= 1 << 8;
if ((HandsDisabledSlots & DisabledSlots.Place) == DisabledSlots.Place)
slots |= 1 << 16;
if ((FeetDisabledSlots & DisabledSlots.Remove) == DisabledSlots.Remove)
slots |= 1<<1;
if ((FeetDisabledSlots & DisabledSlots.Replace) == DisabledSlots.Replace)
slots |= 1 << 9;
if ((FeetDisabledSlots & DisabledSlots.Place) == DisabledSlots.Place)
slots |= 1 << 17;
if ((LegsDisabledSlots & DisabledSlots.Remove) == DisabledSlots.Remove)
slots |= 1 << 2;
if ((LegsDisabledSlots & DisabledSlots.Replace) == DisabledSlots.Replace)
slots |= 1 << 10;
if ((LegsDisabledSlots & DisabledSlots.Place) == DisabledSlots.Place)
slots |= 1 << 18;
if ((ChestDisabledSlots & DisabledSlots.Remove) == DisabledSlots.Remove)
slots |= 1 << 3;
if ((ChestDisabledSlots & DisabledSlots.Replace) == DisabledSlots.Replace)
slots |= 1 << 11;
if ((ChestDisabledSlots & DisabledSlots.Place) == DisabledSlots.Place)
slots |= 1 << 19;
if ((HeadDisabledSlots & DisabledSlots.Remove) == DisabledSlots.Remove)
slots |= 1 << 4;
if ((HeadDisabledSlots & DisabledSlots.Replace) == DisabledSlots.Replace)
slots |= 1 << 12;
if ((HeadDisabledSlots & DisabledSlots.Place) == DisabledSlots.Place)
slots |= 1 << 20;
if (slots != 65793)
b.Append(string.Format("DisabledSlots:{0},", slots));
var poseInner = new StringBuilder();
const float tol = 0.001f;
if (Math.Abs(BodyPose[0].Value) > tol || Math.Abs(BodyPose[1].Value) > tol || Math.Abs(BodyPose[2].Value) > tol)
poseInner.AppendFormat("Body:[{0:0.##}f,{1:0.##}f,{2:0.##}f],", BodyPose[0].Value, BodyPose[1].Value, BodyPose[2].Value);
if (Math.Abs(LeftArmPose[0].Value) > tol || Math.Abs(LeftArmPose[1].Value) > tol || Math.Abs(LeftArmPose[2].Value) > tol)
poseInner.AppendFormat("LeftArm:[{0:0.##}f,{1:0.##}f,{2:0.##}f],", LeftArmPose[0].Value, LeftArmPose[1].Value, LeftArmPose[2].Value);
if (Math.Abs(RightArmPose[0].Value) > tol || Math.Abs(RightArmPose[1].Value) > tol || Math.Abs(RightArmPose[2].Value) > tol)
poseInner.AppendFormat("RightArm:[{0:0.##}f,{1:0.##}f,{2:0.##}f],", RightArmPose[0].Value, RightArmPose[1].Value, RightArmPose[2].Value);
if (Math.Abs(LeftLegPose[0].Value) > tol || Math.Abs(LeftLegPose[1].Value) > tol || Math.Abs(LeftLegPose[2].Value) > tol)
poseInner.AppendFormat("LeftLeg:[{0:0.##}f,{1:0.##}f,{2:0.##}f],", LeftLegPose[0].Value, LeftLegPose[1].Value, LeftLegPose[2].Value);
if (Math.Abs(RightLegPose[0].Value) > tol || Math.Abs(RightLegPose[1].Value) > tol || Math.Abs(RightLegPose[2].Value) > tol)
poseInner.AppendFormat("RightLeg:[{0:0.##}f,{1:0.##}f,{2:0.##}f],", RightLegPose[0].Value, RightLegPose[1].Value, RightLegPose[2].Value);
if (Math.Abs(HeadPose[0].Value) > tol || Math.Abs(HeadPose[1].Value) > tol || Math.Abs(HeadPose[2].Value) > tol)
poseInner.AppendFormat("Head:[{0:0.##}f,{1:0.##}f,{2:0.##}f],", HeadPose[0].Value, HeadPose[1].Value, HeadPose[2].Value);
if (poseInner.Length <= 0) return b.ToString();
poseInner.Remove(poseInner.Length - 1, 1);
poseInner.Insert(0, "Pose:{");
poseInner.Append("},");
b.Append(poseInner);
return b.ToString();
}
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009, 2010 Oracle and/or its affiliates. All rights reserved.
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using BerkeleyDB.Internal;
namespace BerkeleyDB {
/// <summary>
/// A class representing a QueueDatabase. The Queue format supports fast
/// access to fixed-length records accessed sequentially or by logical
/// record number.
/// </summary>
public class QueueDatabase : Database {
#region Constructors
private QueueDatabase(DatabaseEnvironment env, uint flags)
: base(env, flags) { }
internal QueueDatabase(BaseDatabase clone) : base(clone) { }
private void Config(QueueDatabaseConfig cfg) {
base.Config(cfg);
/*
* Database.Config calls set_flags, but that doesn't get the Queue
* specific flags. No harm in calling it again.
*/
db.set_flags(cfg.flags);
db.set_re_len(cfg.Length);
if (cfg.padIsSet)
db.set_re_pad(cfg.PadByte);
if (cfg.extentIsSet)
db.set_q_extentsize(cfg.ExtentSize);
}
/// <summary>
/// Instantiate a new QueueDatabase object and open the database
/// represented by <paramref name="Filename"/>.
/// </summary>
/// <remarks>
/// <para>
/// If <paramref name="Filename"/> is null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe.
/// </para>
/// <para>
/// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation
/// will be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <returns>A new, open database object</returns>
public static QueueDatabase Open(
string Filename, QueueDatabaseConfig cfg) {
return Open(Filename, cfg, null);
}
/// <summary>
/// Instantiate a new QueueDatabase object and open the database
/// represented by <paramref name="Filename"/>.
/// </summary>
/// <remarks>
/// <para>
/// If <paramref name="Filename"/> is null, the database is strictly
/// temporary and cannot be opened by any other thread of control, thus
/// the database can only be accessed by sharing the single database
/// object that created it, in circumstances where doing so is safe.
/// </para>
/// <para>
/// If <paramref name="txn"/> is null, but
/// <see cref="DatabaseConfig.AutoCommit"/> is set, the operation will
/// be implicitly transaction protected. Note that transactionally
/// protected operations on a datbase object requires the object itself
/// be transactionally protected during its open. Also note that the
/// transaction must be committed before the object is closed.
/// </para>
/// </remarks>
/// <param name="Filename">
/// The name of an underlying file that will be used to back the
/// database. In-memory databases never intended to be preserved on disk
/// may be created by setting this parameter to null.
/// </param>
/// <param name="cfg">The database's configuration</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>A new, open database object</returns>
public static QueueDatabase Open(
string Filename, QueueDatabaseConfig cfg, Transaction txn) {
QueueDatabase ret = new QueueDatabase(cfg.Env, 0);
ret.Config(cfg);
ret.db.open(Transaction.getDB_TXN(txn),
Filename, null, DBTYPE.DB_QUEUE, cfg.openFlags, 0);
ret.isOpen = true;
return ret;
}
#endregion Constructors
#region Properties
/// <summary>
/// The size of the extents used to hold pages in a
/// <see cref="QueueDatabase"/>, specified as a number of pages.
/// </summary>
public uint ExtentSize {
get {
uint ret = 0;
db.get_q_extentsize(ref ret);
return ret;
}
}
/// <summary>
/// If true, modify the operation of <see cref="QueueDatabase.Consume"/>
/// to return key/data pairs in order. That is, they will always return
/// the key/data item from the head of the queue.
/// </summary>
public bool InOrder {
get {
uint flags = 0;
db.get_flags(ref flags);
return (flags & DbConstants.DB_INORDER) != 0;
}
}
/// <summary>
/// The length of records in the database.
/// </summary>
public uint Length {
get {
uint ret = 0;
db.get_re_len(ref ret);
return ret;
}
}
/// <summary>
/// The padding character for short, fixed-length records.
/// </summary>
public int PadByte {
get {
int ret = 0;
db.get_re_pad(ref ret);
return ret;
}
}
#endregion Properties
#region Methods
/// <summary>
/// Append the data item to the end of the database.
/// </summary>
/// <param name="data">The data item to store in the database</param>
/// <returns>The record number allocated to the record</returns>
public uint Append(DatabaseEntry data) {
return Append(data, null);
}
/// <summary>
/// Append the data item to the end of the database.
/// </summary>
/// <remarks>
/// There is a minor behavioral difference between
/// <see cref="RecnoDatabase.Append"/> and
/// <see cref="QueueDatabase.Append"/>. If a transaction enclosing an
/// Append operation aborts, the record number may be reallocated in a
/// subsequent <see cref="RecnoDatabase.Append"/> operation, but it will
/// not be reallocated in a subsequent
/// <see cref="QueueDatabase.Append"/> operation.
/// </remarks>
/// <param name="data">The data item to store in the database</param>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>The record number allocated to the record</returns>
public uint Append(DatabaseEntry data, Transaction txn) {
DatabaseEntry key = new DatabaseEntry();
Put(key, data, txn, DbConstants.DB_APPEND);
return BitConverter.ToUInt32(key.Data, 0);
}
/// <summary>
/// Return the record number and data from the available record closest
/// to the head of the queue, and delete the record.
/// </summary>
/// <param name="wait">
/// If true and the Queue database is empty, the thread of control will
/// wait until there is data in the queue before returning.
/// </param>
/// <exception cref="LockNotGrantedException">
/// If lock or transaction timeouts have been specified, a
/// <see cref="LockNotGrantedException"/> may be thrown. This failure,
/// by itself, does not require the enclosing transaction be aborted.
/// </exception>
/// <returns>
/// A <see cref="KeyValuePair{T,T}"/> whose Key
/// parameter is the record number and whose Value parameter is the
/// retrieved data.
/// </returns>
public KeyValuePair<uint, DatabaseEntry> Consume(bool wait) {
return Consume(wait, null, null);
}
/// <summary>
/// Return the record number and data from the available record closest
/// to the head of the queue, and delete the record.
/// </summary>
/// <param name="wait">
/// If true and the Queue database is empty, the thread of control will
/// wait until there is data in the queue before returning.
/// </param>
/// <param name="txn">
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <exception cref="LockNotGrantedException">
/// If lock or transaction timeouts have been specified, a
/// <see cref="LockNotGrantedException"/> may be thrown. This failure,
/// by itself, does not require the enclosing transaction be aborted.
/// </exception>
/// <returns>
/// A <see cref="KeyValuePair{T,T}"/> whose Key
/// parameter is the record number and whose Value parameter is the
/// retrieved data.
/// </returns>
public KeyValuePair<uint, DatabaseEntry> Consume(
bool wait, Transaction txn) {
return Consume(wait, txn, null);
}
/// <summary>
/// Return the record number and data from the available record closest
/// to the head of the queue, and delete the record.
/// </summary>
/// <param name="wait">
/// If true and the Queue database is empty, the thread of control will
/// wait until there is data in the queue before returning.
/// </param>
/// <param name="txn">
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <param name="info">The locking behavior to use.</param>
/// <exception cref="LockNotGrantedException">
/// If lock or transaction timeouts have been specified, a
/// <see cref="LockNotGrantedException"/> may be thrown. This failure,
/// by itself, does not require the enclosing transaction be aborted.
/// </exception>
/// <returns>
/// A <see cref="KeyValuePair{T,T}"/> whose Key
/// parameter is the record number and whose Value parameter is the
/// retrieved data.
/// </returns>
public KeyValuePair<uint, DatabaseEntry> Consume(
bool wait, Transaction txn, LockingInfo info) {
KeyValuePair<DatabaseEntry, DatabaseEntry> record;
record = Get(null, null, txn, info,
wait ? DbConstants.DB_CONSUME_WAIT : DbConstants.DB_CONSUME);
return new KeyValuePair<uint, DatabaseEntry>(
BitConverter.ToUInt32(record.Key.Data, 0), record.Value);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public QueueStats FastStats() {
return Stats(null, true, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public QueueStats FastStats(Transaction txn) {
return Stats(txn, true, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information which does not require
/// traversal of the database.
/// </summary>
/// <overloads>
/// <para>
/// Among other things, this method makes it possible for applications
/// to request key and record counts without incurring the performance
/// penalty of traversing the entire database.
/// </para>
/// <para>
/// The statistical information is described by the
/// <see cref="BTreeStats"/>, <see cref="HashStats"/>,
/// <see cref="QueueStats"/>, and <see cref="RecnoStats"/> classes.
/// </para>
/// </overloads>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <param name="isoDegree">
/// The level of isolation for database reads.
/// <see cref="Isolation.DEGREE_ONE"/> will be silently ignored for
/// databases which did not specify
/// <see cref="DatabaseConfig.ReadUncommitted"/>.
/// </param>
/// <returns>
/// The database statistical information which does not require
/// traversal of the database.
/// </returns>
public QueueStats FastStats(Transaction txn, Isolation isoDegree) {
return Stats(txn, true, isoDegree);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <returns>Database statistical information.</returns>
public QueueStats Stats() {
return Stats(null, false, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <returns>Database statistical information.</returns>
public QueueStats Stats(Transaction txn) {
return Stats(txn, false, Isolation.DEGREE_THREE);
}
/// <summary>
/// Return the database statistical information for this database.
/// </summary>
/// <overloads>
/// The statistical information is described by
/// <see cref="BTreeStats"/>.
/// </overloads>
/// <param name="txn">
/// If the operation is part of an application-specified transaction,
/// <paramref name="txn"/> is a Transaction object returned from
/// <see cref="DatabaseEnvironment.BeginTransaction"/>; if
/// the operation is part of a Berkeley DB Concurrent Data Store group,
/// <paramref name="txn"/> is a handle returned from
/// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null.
/// </param>
/// <param name="isoDegree">
/// The level of isolation for database reads.
/// <see cref="Isolation.DEGREE_ONE"/> will be silently ignored for
/// databases which did not specify
/// <see cref="DatabaseConfig.ReadUncommitted"/>.
/// </param>
/// <returns>Database statistical information.</returns>
public QueueStats Stats(Transaction txn, Isolation isoDegree) {
return Stats(txn, false, isoDegree);
}
private QueueStats Stats(Transaction txn, bool fast, Isolation isoDegree) {
uint flags = 0;
flags |= fast ? DbConstants.DB_FAST_STAT : 0;
switch (isoDegree) {
case Isolation.DEGREE_ONE:
flags |= DbConstants.DB_READ_UNCOMMITTED;
break;
case Isolation.DEGREE_TWO:
flags |= DbConstants.DB_READ_COMMITTED;
break;
}
QueueStatStruct st = db.stat_qam(Transaction.getDB_TXN(txn), flags);
return new QueueStats(st);
}
#endregion Methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
namespace ZocMonLib
{
public class StorageCommandsSqlServer : IStorageCommands
{
//TODO: Instead of passing in tableName pass in configName?
private readonly ISystemLogger _logger;
private readonly IStorageFactory _dbFactory;
private const string _sqlIdentity = "select @@IDENTITY id";
public StorageCommandsSqlServer(IStorageFactory dbFactory, ISettings settings)
{
_logger = settings.LoggerProvider.CreateLogger(typeof(StorageCommandsSqlServer));
_dbFactory = dbFactory;
}
public virtual void InsertRecords(IEnumerable<Record<double>> records, IDbConnection conn, IDbTransaction transaction = null)
{
foreach (var record in records)
InsertRecord(record, conn, transaction);
}
public virtual void UpdateRecords(IEnumerable<Record<double>> records, IDbConnection conn, IDbTransaction transaction = null)
{
foreach (var record in records)
UpdateRecord(record, conn, transaction);
}
public virtual void InsertRecord(Record<double> record, IDbConnection conn, IDbTransaction transaction = null)
{
const string sql = "INSERT INTO Record (ReduceLevelId, TimeStamp, Value, Number, IntervalSum, IntervalSumOfSquares) VALUES (@ReduceLevelId, @TimeStamp, @Value, @Number, @IntervalSum, @IntervalSumOfSquares)";
Execute(record, sql, conn, transaction);
}
public virtual void UpdateRecord(Record<double> record, IDbConnection conn, IDbTransaction transaction = null)
{
const string sql = "UPDATE Record SET Value = @Value, Number = @Number, IntervalSum = @IntervalSum, IntervalSumOfSquares = @IntervalSumOfSquares WHERE ReduceLevelId = @ReduceLevelId and TimeStamp = @TimeStamp";
Execute(record, sql, conn, transaction);
}
protected virtual void Execute(object data, string sql, IDbConnection conn, IDbTransaction transaction = null)
{
DatabaseSqlHelper.Execute(conn, sql, transaction, data);
}
public virtual bool UpdateRecordIfExists(int reduceLevelId, Record<double> update, bool knownToExist, IDbConnection conn)
{
const string sqlCount = "SELECT count(1) FROM Record WHERE ReduceLevelId = @reduceLevelId AND TimeStamp = @timeStamp";
const string sqlUpdate = "UPDATE Record SET Value = @Value, Number = @Number, IntervalSum = @IntervalSum, IntervalSumOfSquares = @IntervalSumOfSquares WHERE ReduceLevelId = @ReduceLevelId and TimeStamp = @TimeStamp";
var updated = false;
var rowCount = 0;
if (!knownToExist)
rowCount = DatabaseSqlHelper.Query<int>(conn, sqlCount, param : new { reduceLevelId, timeStamp = update.TimeStamp }).First();
if (knownToExist || rowCount == 1)
{
var result = DatabaseSqlHelper.Execute(conn, sqlUpdate, param : update);
if (result != 1)
throw new DataException("Expected to update 1 row, but updated " + result + " for sql: \"" + sqlUpdate + "\"");
updated = true;
}
else if (rowCount > 1)
throw new DataException("Too many rows (" + rowCount + ") for: \"" + sqlCount + "\" trying to insert: " + update);
else
_logger.Warn("Zero Rows in UpdateRecordIfExists for \"" + sqlCount + "\""); // In principal, this is ok; but in practice, it should hardly ever happen, so I want to know about it
return updated;
}
public virtual void FlushRecords(IEnumerable<Record<double>> updateList, IDbConnection conn)
{
using (var trans = conn.BeginTransaction())
{
InsertRecords(updateList, conn, trans);
trans.Commit();
}
}
public virtual IEnumerable<Record<double>> SelectRecordsForUpdateExisting(int reduceLevelId, DateTime timeStamp, IDbConnection conn, IDbTransaction transaction = null)
{
const string sql = "SELECT * FROM Record WHERE ReduceLevelId = @reduceLevelId AND TimeStamp >= @timeStamp ORDER BY TimeStamp";
return DatabaseSqlHelper.Query<Record<double>>(conn, sql, transaction, new { reduceLevelId, timeStamp });
}
public virtual IEnumerable<Record<double>> SelectRecordsForLastReduced(int reduceLevelId, IDbConnection conn)
{
const string sql = "SELECT * FROM Record WHERE ReduceLevelId = @reduceLevelId AND TimeStamp = (SELECT MAX(t2.TimeStamp) FROM Record t2 WHERE ReduceLevelId = @reduceLevelId)";
return DatabaseSqlHelper.Query<Record<double>>(conn, sql, param: new { reduceLevelId });
}
public virtual StorageLastReduced SelectInfoForLastReduce(int reduceLevelId, long resolution, IDbConnection conn)
{
const string sql = "DELETE FROM Record WHERE ReduceLevelId = @reduceLevelId and TimeStamp = @timeStamp";
//Pull out the records that where last reduced
var lastReducedList = SelectRecordsForLastReduced(reduceLevelId, conn);
var lastReducedListCount = lastReducedList.Count();
var lastReducedUpdate = lastReducedList.FirstOrDefault();
var lastReductionTime = Constant.MinDbDateTime;
//0 means we have no reduced data yet and 1 means we've loaded the last reduced update, many means we have a problem
if (lastReducedListCount > 0)
{
lastReductionTime = lastReducedUpdate.TimeStamp - TimeSpan.FromMilliseconds((long)(resolution / 2));
if (lastReducedListCount > 1)
{
//No primary key on these table, so have to delete all with that timestamp and insert one back in
DatabaseSqlHelper.Execute(conn, sql, param : new { timeStamp = lastReducedUpdate.TimeStamp, reduceLevelId });
DatabaseSqlHelper.Insert(conn, lastReducedUpdate, "Record");
_logger.Warn("Expected 0 or 1 updates, but got: " + lastReducedListCount + " for reduceLevelId \"" + reduceLevelId + "\"");
}
}
return new StorageLastReduced { Record = lastReducedUpdate, Time = lastReductionTime };
}
public virtual IEnumerable<Record<double>> SelectRecordsForReduction(int reduceLevelId, bool hasTargetReducedRecord, DateTime lastReductionTime, IDbConnection conn)
{
var where = !hasTargetReducedRecord ? "" : " AND TimeStamp > @lastReductionTime";
var sql = String.Format("SELECT * FROM Record WHERE ReduceLevelId = @reduceLevelId {0} ORDER BY TimeStamp", where);
return DatabaseSqlHelper.Query<Record<double>>(conn, sql, param : new { reduceLevelId, lastReductionTime });
}
public virtual void DeleteReducedRecords(string configName, DateTime reducedTo, ReduceLevel reduceLevel, IDbConnection conn)
{
const string sql = "DELETE FROM Record t1 WHERE t1.ReduceLevelId = @reduceLevelId AND t1.TimeStamp < @timeStamp";
var history = DateTime.Now - TimeSpan.FromMilliseconds(reduceLevel.HistoryLength);
var deleteBeforeDate = reducedTo < history ? reducedTo : history;
DatabaseSqlHelper.Execute(conn, sql, param : new { reduceLevelId = reduceLevel.ReduceLevelId, timeStamp = deleteBeforeDate });
}
public virtual void DetectDuplicateRecordsForReduce(int reduceLevelId, IDbConnection conn)
{
const string sql = "SELECT rl.TimeStamp as TimeStamp, count(1) as Count FROM Record rl WHERE ReduceLevelId = @reduceLevelId GROUP BY TimeStamp HAVING count(1) > 1";
var dups = DatabaseSqlHelper.Query<DupInfo>(conn, sql, param: new { reduceLevelId });
if (dups.Any())
{
var msg = "";
foreach (var dupInfo in dups)
msg += "TimeStamp: " + dupInfo.TimeStamp.ToString("yyyyMMdd HH:mm:ss") + "; Count: " + dupInfo.Count + Environment.NewLine;
throw new Exception("Duplicates found for reduceLevelId " + reduceLevelId + ": " + msg);
}
}
public virtual void CreateConfigAndReduceLevels(Bucket bucket, IEnumerable<ReduceLevel> reduceLevels, IDbConnection conn)
{
const string sqlConfig = "INSERT INTO Bucket (Name, MonitorReductionType, ReduceMethodClassName) VALUES (@name, @monitorReductionType, @reduceMethodClassName)";
const string sqlLevel = "INSERT into ReduceLevel (BucketId, Resolution, HistoryLength) VALUES (@bucketId, @resolution, @historyLength)";
using (var transaction = conn.BeginTransaction())
{
//The "if this doesn't already exist" check is inside the query string
DatabaseSqlHelper.Execute(conn, sqlConfig, transaction, new { name = bucket.Name, monitorReductionType = bucket.MonitorReductionType, reduceMethodClassName = bucket.ReduceMethodClassName });
bucket.BucketId = (int)DatabaseSqlHelper.Query<dynamic>(conn, _sqlIdentity, transaction).First().id;
//Go through and insert the various reduce levels
foreach (var reduceLevel in reduceLevels)
{
reduceLevel.BucketId = bucket.BucketId;
DatabaseSqlHelper.Execute(conn, sqlLevel, transaction, new { id = reduceLevel.ReduceLevelId, bucketId = reduceLevel.BucketId, resolution = reduceLevel.Resolution, historyLength = reduceLevel.HistoryLength });
reduceLevel.ReduceLevelId = (int)DatabaseSqlHelper.Query<dynamic>(conn, _sqlIdentity, transaction).First().id;
}
transaction.Commit();
}
}
#region Support Types
private class DupInfo
{
public DateTime TimeStamp { get; set; }
public int Count { get; set; }
}
#endregion
}
}
| |
// ***********************************************************************
// Copyright (c) 2010 Charlie Poole
//
// 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.Threading;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
namespace NUnit.Framework.Attributes
{
[TestFixture]
public class ApplyToTestTests
{
Test test;
[SetUp]
public void SetUp()
{
test = new TestDummy();
test.RunState = RunState.Runnable;
}
#region CategoryAttribute
[Test]
public void CategoryAttributeSetsCategory()
{
new CategoryAttribute("database").ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.Category), Is.EqualTo("database"));
}
[Test]
public void CategoryAttributeSetsCategoryOnNonRunnableTest()
{
test.RunState = RunState.NotRunnable;
new CategoryAttribute("database").ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.Category), Is.EqualTo("database"));
}
[Test]
public void CategoryAttributeSetsMultipleCategories()
{
new CategoryAttribute("group1").ApplyToTest(test);
new CategoryAttribute("group2").ApplyToTest(test);
Assert.That(test.Properties[PropertyNames.Category],
Is.EquivalentTo( new string[] { "group1", "group2" } ));
}
#endregion
#region DescriptionAttribute
[Test]
public void DescriptionAttributeSetsDescription()
{
new DescriptionAttribute("Cool test!").ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.Description), Is.EqualTo("Cool test!"));
}
[Test]
public void DescriptionAttributeSetsDescriptionOnNonRunnableTest()
{
test.RunState = RunState.NotRunnable;
new DescriptionAttribute("Cool test!").ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.Description), Is.EqualTo("Cool test!"));
}
#endregion
#region IgnoreAttribute
[Test]
public void IgnoreAttributeIgnoresTest()
{
new IgnoreAttribute("BECAUSE").ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Ignored));
}
[Test]
public void IgnoreAttributeSetsIgnoreReason()
{
new IgnoreAttribute("BECAUSE").ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Ignored));
Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("BECAUSE"));
}
[Test]
public void IgnoreAttributeDoesNotAffectNonRunnableTest()
{
test.MakeInvalid("UNCHANGED");
new IgnoreAttribute("BECAUSE").ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("UNCHANGED"));
}
[Test]
public void IgnoreAttributeIgnoresTestUntilDateSpecified()
{
var ignoreAttribute = new IgnoreAttribute("BECAUSE");
ignoreAttribute.Until = "4242-01-01";
ignoreAttribute.ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Ignored));
}
[Test]
public void IgnoreAttributeIgnoresTestUntilDateTimeSpecified()
{
var ignoreAttribute = new IgnoreAttribute("BECAUSE");
ignoreAttribute.Until = "4242-01-01 12:00:00Z";
ignoreAttribute.ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Ignored));
}
[Test]
public void IgnoreAttributeMarksTestAsRunnableAfterUntilDatePasses()
{
var ignoreAttribute = new IgnoreAttribute("BECAUSE");
ignoreAttribute.Until = "1492-01-01";
ignoreAttribute.ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Runnable));
}
[TestCase("4242-01-01")]
[TestCase("4242-01-01 00:00:00Z")]
[TestCase("4242-01-01 00:00:00")]
public void IgnoreAttributeUntilSetsTheReason(string date)
{
var ignoreAttribute = new IgnoreAttribute("BECAUSE");
ignoreAttribute.Until = date;
ignoreAttribute.ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Ignoring until 4242-01-01 00:00:00Z. BECAUSE"));
}
[Test]
public void IgnoreAttributeWithInvalidDateThrowsException()
{
var ignoreAttribute = new IgnoreAttribute("BECAUSE");
Assert.Throws<FormatException>(() => ignoreAttribute.Until = "Thursday the twenty fifth of December");
}
[Test]
public void IgnoreAttributeWithUntilAddsIgnoreUntilDateProperty()
{
var ignoreAttribute = new IgnoreAttribute("BECAUSE");
ignoreAttribute.Until = "4242-01-01";
ignoreAttribute.ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.IgnoreUntilDate), Is.EqualTo("4242-01-01 00:00:00Z"));
}
[Test]
public void IgnoreAttributeWithUntilAddsIgnoreUntilDatePropertyPastUntilDate()
{
var ignoreAttribute = new IgnoreAttribute("BECAUSE");
ignoreAttribute.Until = "1242-01-01";
ignoreAttribute.ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.IgnoreUntilDate), Is.EqualTo("1242-01-01 00:00:00Z"));
}
[Test]
public void IgnoreAttributeWithExplicitIgnoresTest()
{
new IgnoreAttribute("BECAUSE").ApplyToTest(test);
new ExplicitAttribute().ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Ignored));
}
#endregion
#region ExplicitAttribute
[Test]
public void ExplicitAttributeMakesTestExplicit()
{
new ExplicitAttribute().ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Explicit));
}
[Test]
public void ExplicitAttributeSetsIgnoreReason()
{
new ExplicitAttribute("BECAUSE").ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Explicit));
Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("BECAUSE"));
}
[Test]
public void ExplicitAttributeDoesNotAffectNonRunnableTest()
{
test.MakeInvalid("UNCHANGED");
new ExplicitAttribute("BECAUSE").ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("UNCHANGED"));
}
[Test]
public void ExplicitAttributeWithIgnoreIgnoresTest()
{
new ExplicitAttribute().ApplyToTest(test);
new IgnoreAttribute("BECAUSE").ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Ignored));
}
#endregion
#region CombinatorialAttribute
[Test]
public void CombinatorialAttributeSetsJoinType()
{
new CombinatorialAttribute().ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Combinatorial"));
}
[Test]
public void CombinatorialAttributeSetsJoinTypeOnNonRunnableTest()
{
test.RunState = RunState.NotRunnable;
new CombinatorialAttribute().ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Combinatorial"));
}
#endregion
#region CultureAttribute
[Test]
public void CultureAttributeIncludingCurrentCultureRunsTest()
{
string name = System.Globalization.CultureInfo.CurrentCulture.Name;
new CultureAttribute(name).ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Runnable));
}
[Test]
public void CultureAttributeDoesNotAffectNonRunnableTest()
{
test.RunState = RunState.NotRunnable;
string name = System.Globalization.CultureInfo.CurrentCulture.Name;
new CultureAttribute(name).ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable));
}
[Test]
public void CultureAttributeExcludingCurrentCultureSkipsTest()
{
string name = System.Globalization.CultureInfo.CurrentCulture.Name;
CultureAttribute attr = new CultureAttribute(name);
attr.Exclude = name;
attr.ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(test.Properties.Get(PropertyNames.SkipReason),
Is.EqualTo("Not supported under culture " + name));
}
[Test]
public void CultureAttributeIncludingOtherCultureSkipsTest()
{
string name = "fr-FR";
if (System.Globalization.CultureInfo.CurrentCulture.Name == name)
name = "en-US";
new CultureAttribute(name).ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(test.Properties.Get(PropertyNames.SkipReason),
Is.EqualTo("Only supported under culture " + name));
}
[Test]
public void CultureAttributeExcludingOtherCultureRunsTest()
{
string other = "fr-FR";
if (System.Globalization.CultureInfo.CurrentCulture.Name == other)
other = "en-US";
CultureAttribute attr = new CultureAttribute();
attr.Exclude = other;
attr.ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Runnable));
}
[Test]
public void CultureAttributeWithMultipleCulturesIncluded()
{
string current = System.Globalization.CultureInfo.CurrentCulture.Name;
string other = current == "fr-FR" ? "en-US" : "fr-FR";
string cultures = current + "," + other;
new CultureAttribute(cultures).ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Runnable));
}
#endregion
#region MaxTimeAttribute
[Test]
public void MaxTimeAttributeSetsMaxTime()
{
new MaxTimeAttribute(2000).ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.MaxTime), Is.EqualTo(2000));
}
[Test]
public void MaxTimeAttributeSetsMaxTimeOnNonRunnableTest()
{
test.RunState = RunState.NotRunnable;
new MaxTimeAttribute(2000).ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.MaxTime), Is.EqualTo(2000));
}
#endregion
#region PairwiseAttribute
[Test]
public void PairwiseAttributeSetsJoinType()
{
new PairwiseAttribute().ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Pairwise"));
}
[Test]
public void PairwiseAttributeSetsJoinTypeOnNonRunnableTest()
{
test.RunState = RunState.NotRunnable;
new PairwiseAttribute().ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Pairwise"));
}
#endregion
#region PlatformAttribute
#if !PORTABLE && !NETSTANDARD1_6
[Test]
public void PlatformAttributeRunsTest()
{
string myPlatform = GetMyPlatform();
new PlatformAttribute(myPlatform).ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Runnable));
}
[Test]
public void PlatformAttributeSkipsTest()
{
string notMyPlatform = System.IO.Path.DirectorySeparatorChar == '/'
? "Win" : "Linux";
new PlatformAttribute(notMyPlatform).ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.Skipped));
}
[Test]
public void PlatformAttributeDoesNotAffectNonRunnableTest()
{
test.RunState = RunState.NotRunnable;
string myPlatform = GetMyPlatform();
new PlatformAttribute(myPlatform).ApplyToTest(test);
Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable));
}
string GetMyPlatform()
{
if (System.IO.Path.DirectorySeparatorChar == '/')
{
return OSPlatform.CurrentPlatform.IsMacOSX ? "MacOSX" : "Linux";
}
return "Win";
}
#endif
#endregion
#region RepeatAttribute
[Test]
public void RepeatAttributeSetsRepeatCount()
{
new RepeatAttribute(5).ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.RepeatCount), Is.EqualTo(5));
}
[Test]
public void RepeatAttributeSetsRepeatCountOnNonRunnableTest()
{
test.RunState = RunState.NotRunnable;
new RepeatAttribute(5).ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.RepeatCount), Is.EqualTo(5));
}
#endregion
#if !PORTABLE && !NETSTANDARD1_6
#region RequiresMTAAttribute
[Test]
public void RequiresMTAAttributeSetsApartmentState()
{
new ApartmentAttribute(ApartmentState.MTA).ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.ApartmentState),
Is.EqualTo(ApartmentState.MTA));
}
[Test]
public void RequiresMTAAttributeSetsApartmentStateOnNonRunnableTest()
{
test.RunState = RunState.NotRunnable;
new ApartmentAttribute(ApartmentState.MTA).ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.ApartmentState),
Is.EqualTo(ApartmentState.MTA));
}
#endregion
#region RequiresSTAAttribute
[Test]
public void RequiresSTAAttributeSetsApartmentState()
{
new ApartmentAttribute(ApartmentState.STA).ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.ApartmentState),
Is.EqualTo(ApartmentState.STA));
}
[Test]
public void RequiresSTAAttributeSetsApartmentStateOnNonRunnableTest()
{
test.RunState = RunState.NotRunnable;
new ApartmentAttribute(ApartmentState.STA).ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.ApartmentState),
Is.EqualTo(ApartmentState.STA));
}
#endregion
#endif
#region RequiresThreadAttribute
#if !PORTABLE && !NETSTANDARD1_6
[Test]
public void RequiresThreadAttributeSetsRequiresThread()
{
new RequiresThreadAttribute().ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.RequiresThread), Is.EqualTo(true));
}
[Test]
public void RequiresThreadAttributeSetsRequiresThreadOnNonRunnableTest()
{
test.RunState = RunState.NotRunnable;
new RequiresThreadAttribute().ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.RequiresThread), Is.EqualTo(true));
}
#endif
#if !PORTABLE && !NETSTANDARD1_6
[Test]
public void RequiresThreadAttributeMaySetApartmentState()
{
new RequiresThreadAttribute(ApartmentState.STA).ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.RequiresThread), Is.EqualTo(true));
Assert.That(test.Properties.Get(PropertyNames.ApartmentState),
Is.EqualTo(ApartmentState.STA));
}
#endif
#endregion
#region SequentialAttribute
[Test]
public void SequentialAttributeSetsJoinType()
{
new SequentialAttribute().ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Sequential"));
}
[Test]
public void SequentialAttributeSetsJoinTypeOnNonRunnableTest()
{
test.RunState = RunState.NotRunnable;
new SequentialAttribute().ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Sequential"));
}
#endregion
#if !PORTABLE && !NETSTANDARD1_6
#region SetCultureAttribute
public void SetCultureAttributeSetsSetCultureProperty()
{
new SetCultureAttribute("fr-FR").ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.SetCulture), Is.EqualTo("fr-FR"));
}
public void SetCultureAttributeSetsSetCulturePropertyOnNonRunnableTest()
{
test.RunState = RunState.NotRunnable;
new SetCultureAttribute("fr-FR").ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.SetCulture), Is.EqualTo("fr-FR"));
}
#endregion
#region SetUICultureAttribute
public void SetUICultureAttributeSetsSetUICultureProperty()
{
new SetUICultureAttribute("fr-FR").ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.SetUICulture), Is.EqualTo("fr-FR"));
}
public void SetUICultureAttributeSetsSetUICulturePropertyOnNonRunnableTest()
{
test.RunState = RunState.NotRunnable;
new SetUICultureAttribute("fr-FR").ApplyToTest(test);
Assert.That(test.Properties.Get(PropertyNames.SetUICulture), Is.EqualTo("fr-FR"));
}
#endregion
#endif
}
}
| |
#region Includes
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Daishi.Microservices.Web.Areas.HelpPage.ModelDescriptions;
using Daishi.Microservices.Web.Areas.HelpPage.Models;
#endregion
namespace Daishi.Microservices.Web.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 media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration" />.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) {
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), 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 description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator" /></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) {
return (ModelDescriptionGenerator) config.Properties.GetOrAdd(
typeof (ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <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) {
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel) model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) {
HelpPageApiModel apiModel = new HelpPageApiModel() {
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) {
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) {
if (apiParameter.Source == ApiParameterSource.FromUri) {
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null) {
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType)) {
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) {
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null) {
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional) {
uriParameter.Annotations.Add(new ParameterAnnotation() {Documentation = "Required"});
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null) {
uriParameter.Annotations.Add(new ParameterAnnotation() {Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture)});
}
}
else {
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof (string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType) {
if (parameterType == null) {
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof (string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription) {
ParameterDescription parameterDescription = new ParameterDescription {
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) {
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) {
if (apiParameter.Source == ApiParameterSource.FromBody) {
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof (HttpRequestMessage)) {
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null) {
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) {
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof (void)) {
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) {
try {
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) {
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.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}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) {
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof (HttpRequestMessage)));
if (parameterDescription == null) {
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof (HttpRequestMessage)) {
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null) {
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) {
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis) {
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) {
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) {
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null) {
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace MyTermsetCreator
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Forms;
using EIDSS.Reports.BaseControls.Form;
using EIDSS.Reports.BaseControls.Keeper;
using EIDSS.Reports.BaseControls.Report;
using EIDSS.Reports.Document.ActiveSurveillance;
using EIDSS.Reports.Document.Human.Aggregate;
using EIDSS.Reports.Document.Human.CaseInvestigation;
using EIDSS.Reports.Document.Human.EmergencyNotification;
using EIDSS.Reports.Document.Human.TZ;
using EIDSS.Reports.Document.Lim.Batch;
using EIDSS.Reports.Document.Lim.Case;
using EIDSS.Reports.Document.Lim.ContainerContent;
using EIDSS.Reports.Document.Lim.ContainerDetails;
using EIDSS.Reports.Document.Lim.TestResult;
using EIDSS.Reports.Document.Lim.Transfer;
using EIDSS.Reports.Document.Uni.AccessionIn;
using EIDSS.Reports.Document.Uni.Outbreak;
using EIDSS.Reports.Document.Veterinary.Aggregate;
using EIDSS.Reports.Document.Veterinary.AvianInvestigation;
using EIDSS.Reports.Document.Veterinary.LivestockInvestigation;
using EIDSS.Reports.OperationContext;
using EIDSS.Reports.Parameterized.ActiveSurveillance;
using EIDSS.Reports.Parameterized.Human.AJ.Keepers;
using EIDSS.Reports.Parameterized.Human.AJ.Reports;
using EIDSS.Reports.Parameterized.Human.ARM.Report;
using EIDSS.Reports.Parameterized.Human.DSummary;
using EIDSS.Reports.Parameterized.Human.DToChangedD;
using EIDSS.Reports.Parameterized.Human.GG.Keeper;
using EIDSS.Reports.Parameterized.Human.GG.Report;
using EIDSS.Reports.Parameterized.Human.IQ.Keepers;
using EIDSS.Reports.Parameterized.Human.MMM;
using EIDSS.Reports.Parameterized.Uni.EventLog;
using EIDSS.Reports.Parameterized.Veterinary.KZ;
using EIDSS.Reports.Parameterized.Veterinary.KZ.Keepers;
using EIDSS.Reports.Parameterized.Veterinary.SamplesCount;
using EIDSS.Reports.Parameterized.Veterinary.SamplesType;
using EIDSS.Reports.Parameterized.Veterinary.Situation;
using EIDSS.Reports.Parameterized.Veterinary.TestType;
using eidss.model.Core;
using eidss.model.Enums;
using eidss.model.Reports;
namespace EIDSS.Reports.Factory
{
internal delegate IReportForm CreateReportFormDelegate();
public class ReportFactory : IReportFactory
{
private static CreateReportFormDelegate m_CreateReportFormHandler = () => new ReportForm();
private static readonly List<IReportForm> m_ReportForms = new List<IReportForm>();
public void ResetLanguage()
{
foreach (IReportForm form in m_ReportForms)
{
form.Close();
}
m_ReportForms.Clear();
}
#region Human reports
#region Human Document report
public void HumAggregateCase(AggregateReportParameters parameters)
{
Dictionary<string, string> parameterList = ReportHelper.CreateHumAggregateCaseParameters(parameters);
InitDocumentReport<CaseAggregateReport>(parameterList);
}
public void HumAggregateCaseSummary(AggregateSummaryReportParameters aggrParams)
{
Dictionary<string, string> parameters = ReportHelper.CreateAggrParameters(aggrParams.AggrXml);
ReportHelper.AddObservationListToParameters(aggrParams.ObservationList, parameters, "@observationId");
InitDocumentReport<SummaryAggregateReport>(parameters);
}
public void HumCaseInvestigation(long caseId, long epiId, long csId, long diagnosisId)
{
Dictionary<string, string> parameters = ReportHelper.CreateHumCaseInvestigationParameters(caseId, epiId, csId, diagnosisId);
InitDocumentReport<CaseInvestigationReport>(parameters);
}
public void HumUrgentyNotification(long caseId)
{
if (EidssSiteContext.Instance.CountryID == 2250000000)
{
InitDocumentReport<TanzaniaCaseInvestigation>(ReportHelper.CreateParameters(caseId));
}
else
{
InitDocumentReport<EmergencyNotificationReport>(ReportHelper.CreateParameters(caseId));
}
}
#endregion
#region Human common reports
public void HumDiagnosisToChangedDiagnosis()
{
InitIntervalReport<DToChangedDReport>();
}
public void HumMonthlyMorbidityAndMortality()
{
InitDateReport<MMMReport>();
}
public void HumSummaryOfInfectiousDiseases()
{
InitIntervalReport<DSummaryReport>();
}
#endregion
#region Human GG reports
public void Hum60BJournal()
{
BaseReportKeeper reportKeeper = new Journal60BKeeper();
PlaceReportKeeper(reportKeeper);
}
public void HumMonthInfectiousDiseaseNew()
{
BaseReportKeeper reportKeeper = new InfectiousDiseasesMonthKeeper(true);
PlaceReportKeeper(reportKeeper);
}
public void HumIntermediateMonthInfectiousDiseaseNew()
{
BaseReportKeeper reportKeeper = new InfectiousDiseasesIntermediateMonthKeeper(true);
PlaceReportKeeper(reportKeeper);
}
public void HumAnnualInfectiousDisease()
{
BaseReportKeeper reportKeeper = new InfectiousDiseasesYearKeeper();
PlaceReportKeeper(reportKeeper);
}
public void HumIntermediateAnnualInfectiousDisease()
{
BaseReportKeeper reportKeeper = new InfectiousDiseasesIntermediateYearKeeper();
PlaceReportKeeper(reportKeeper);
}
public void HumMonthInfectiousDisease()
{
BaseReportKeeper reportKeeper = new InfectiousDiseasesMonthKeeper(false);
PlaceReportKeeper(reportKeeper);
}
public void HumIntermediateMonthInfectiousDisease()
{
BaseReportKeeper reportKeeper = new InfectiousDiseasesIntermediateMonthKeeper(false);
PlaceReportKeeper(reportKeeper);
}
#endregion
#region Lab GG reports
public void HumSerologyResearchCard()
{
InitGGSampleReport<SerologyResearchCardReport>();
}
public void HumMicrobiologyResearchCard()
{
InitGGSampleReport<MicrobiologyResearchCardReport>();
}
public void HumAntibioticResistanceCard()
{
InitGGSampleReport<AntibioticResistanceCardReport>();
}
#endregion
#region Human AZ reports
public void HumFormN1A3()
{
InitFormN1Report(true);
}
public void HumFormN1A4()
{
InitFormN1Report(false);
}
public void HumDataQualityIndicators()
{
var reportKeeper = new DataQualityIndicatorsKeeper(false);
PlaceReportKeeper(reportKeeper);
}
public void HumDataQualityIndicatorsRayons()
{
var reportKeeper = new DataQualityIndicatorsKeeper(true);
PlaceReportKeeper(reportKeeper);
}
public void HumComparativeAZReport()
{
var reportKeeper = new ComparativeAZReportKeeper();
PlaceReportKeeper(reportKeeper);
}
public void HumSummaryByRayonDiagnosisAgeGroups()
{
var reportKeeper = new SummaryReportKeeper();
PlaceReportKeeper(reportKeeper);
}
public void HumExternalComparativeReport()
{
var reportKeeper = new ExternalComparativeReportKeeper();
PlaceReportKeeper(reportKeeper);
}
public void HumMainIndicatorsOfAFPSurveillance()
{
var reportKeeper = new AFPIndicatorsReportKeeper(true);
PlaceReportKeeper(reportKeeper);
}
public void HumAdditionalIndicatorsOfAFPSurveillance()
{
var reportKeeper = new AFPIndicatorsReportKeeper(false);
PlaceReportKeeper(reportKeeper);
}
public void HumWhoMeaslesRubellaReport()
{
InitDateReport<WhoMeaslesRubellaReport>();
}
public void HumComparativeReportOfTwoYears()
{
var reportKeeper = new ComparativeTwoYearsAZReportKeeper();
PlaceReportKeeper(reportKeeper);
}
#endregion
#region Human ARM reports
public void HumFormN85Annual()
{
InitYearReport<FormN85AnnualReport>();
}
public void HumFormN85Monthly()
{
BaseDateKeeper keeper = InitDateReport<FormN85MonthlyReport>();
keeper.SetMandatory();
}
#endregion
#region Human IQ reports
public void WeeklySituationDiseasesByDistricts()
{
var reportKeeper = new WeeklySituationDiseasesKeeper(true);
PlaceReportKeeper(reportKeeper);
}
public void WeeklySituationDiseasesByAgeGroupAndSex()
{
var reportKeeper = new WeeklySituationDiseasesKeeper(false);
PlaceReportKeeper(reportKeeper);
}
public void HumComparativeIQReport()
{
var reportKeeper = new ComparativeIQReportKeeper();
PlaceReportKeeper(reportKeeper);
}
#endregion
#endregion
#region Veterinary Reports
#region Veterinary Document report
public void VetAggregateCaseSummary(AggregateSummaryReportParameters aggrParams)
{
Dictionary<string, string> parameters = ReportHelper.CreateAggrParameters(aggrParams.AggrXml);
ReportHelper.AddObservationListToParameters(aggrParams.ObservationList, parameters, "@observationId");
InitDocumentReport<VetAggregateCaseSummaryReport>(parameters);
}
public void VetAggregateCaseActions(AggregateActionsParameters aggrParams)
{
Dictionary<string, string> ps = ReportHelper.CreateVetAggregateCaseActionsParameters(aggrParams);
InitDocumentReport<VetAggregateActionsReport>(ps);
}
public void VetAggregateCaseActionsSummary(AggregateActionsSummaryParameters aggrParams)
{
Dictionary<string, string> ps = ReportHelper.CreateVetAggregateCaseActionsSummaryPs(aggrParams);
InitDocumentReport<VetAggregateActionsSummaryReport>(ps);
}
public void VetAvianInvestigation(long caseId, long diagnosisId)
{
Dictionary<string, string> parameters = ReportHelper.CreateParameters(caseId);
parameters.Add("@DiagnosisID", diagnosisId.ToString(CultureInfo.InvariantCulture));
InitDocumentReport<AvianInvestigationReport>(parameters);
}
public void VetLivestockInvestigation(long caseId, long diagnosisId)
{
Dictionary<string, string> parameters = ReportHelper.CreateParameters(caseId);
parameters.Add("@DiagnosisID", diagnosisId.ToString(CultureInfo.InvariantCulture));
InitDocumentReport<LivestockInvestigationReport>(parameters);
}
public void VetActiveSurveillanceSampleCollected(long id)
{
InitDocumentReport<SessionReport>(ReportHelper.CreateParameters(id));
}
#endregion
#region Vet common reports
public void VetSamplesCount()
{
InitYearReport<VetSamplesCountReport>();
}
public void VetSamplesBySampleType()
{
InitYearReport<VetSamplesTypeReport>();
}
public void VetSamplesBySampleTypesWithinRegions()
{
InitYearReport<VetTestTypeReport>();
}
public void VetYearlySituation()
{
InitYearReport<VetSituationReport>();
}
public void VetActiveSurveillance()
{
InitYearReport<ActiveSurveillanceReport>();
}
#endregion
#region KZ Vet reports
public void VetCountryPlannedDiagnosticTests()
{
BaseReportKeeper reportKeeper = new VetPlannedDiagnosticKeeper(typeof (VetCountryPlannedDiagnostic));
PlaceReportKeeper(reportKeeper);
}
public void VetOblastPlannedDiagnosticTests()
{
BaseReportKeeper reportKeeper = new VetPlannedDiagnosticKeeper(typeof (VetRegionPlannedDiagnostic));
PlaceReportKeeper(reportKeeper);
}
public void VetCountryPreventiveMeasures()
{
BaseReportKeeper reportKeeper = new VetPrevMeasuresKeeper(typeof (VetCountryPreventiveMeasures));
PlaceReportKeeper(reportKeeper);
}
public void VetOblastPreventiveMeasures()
{
BaseReportKeeper reportKeeper = new VetPrevMeasuresKeeper(typeof (VetRegionPreventiveMeasures));
PlaceReportKeeper(reportKeeper);
}
public void VetCountrySanitaryMeasures()
{
BaseReportKeeper reportKeeper = new VetProphMeasuresKeeper(typeof (VetCountryProphilacticMeasures));
PlaceReportKeeper(reportKeeper);
}
public void VetOblastSanitaryMeasures()
{
BaseReportKeeper reportKeeper = new VetProphMeasuresKeeper(typeof (VetRegionProphilacticMeasures));
PlaceReportKeeper(reportKeeper);
}
#endregion
#region Vet AZ reports
public void VeterinaryCasesReportAZ()
{
BaseReportKeeper reportKeeper = new VetKeeper();
PlaceReportKeeper(reportKeeper);
}
public void VeterinaryLaboratoriesAZ()
{
BaseReportKeeper reportKeeper = new VetLabKeeper();
PlaceReportKeeper(reportKeeper);
}
#endregion
#endregion
#region Lab module Reports
public void LimSampleTransfer(long id)
{
InitDocumentReport<TransferReport>(ReportHelper.CreateParameters(id));
}
public void LimTestResult(long id, long csId, long typeId)
{
Dictionary<string, string> parameters = ReportHelper.CreateLimTestResultParameters(id, csId, typeId);
InitDocumentReport<TestResultReport>(parameters);
}
public void LimTest(long id, bool isHuman)
{
Dictionary<string, string> parameters = ReportHelper.CreateParameters(id);
parameters.Add("@IsHuman", isHuman.ToString(CultureInfo.InvariantCulture));
InitDocumentReport<TestReport>(parameters);
}
public void LimBatchTest(long id, long typeId)
{
Dictionary<string, string> parameters = ReportHelper.CreateParameters(id);
parameters.Add("@TypeID", typeId.ToString(CultureInfo.InvariantCulture));
InitDocumentReport<BatchTestReport>(parameters);
}
public void LimContainerDetails(long id)
{
InitDocumentReport<ContainerDetailsReport>(ReportHelper.CreateParameters(id));
}
public void LimContainerContent(long? contId, long? freeserId)
{
Dictionary<string, string> parameters = ReportHelper.CreateLimContainerContentParameters(contId, freeserId);
InitDocumentReport<ContainerContentReport>(parameters);
}
public void VetAggregateCase(AggregateReportParameters parameters)
{
Dictionary<string, string> parameterList = ReportHelper.CreateVetAggregateCaseParameters(parameters);
InitDocumentReport<VetAggregateReport>(parameterList);
}
public void LimAccessionIn(long caseId)
{
InitDocumentReport<AccessionInReport>(ReportHelper.CreateParameters(caseId));
}
#endregion
#region Outbreaks Reports
public void Outbreak(long id)
{
InitDocumentReport<OutbreakReport>(ReportHelper.CreateParameters(id));
}
#endregion
#region Vector Surveillance Reports
public void VectorSurveillanceSessionSummary(long id)
{
InitDocumentReport<Document.VectorSurveillance.SessionReport>(ReportHelper.CreateParameters(id));
}
#endregion
#region Administrative Parameterized Reports
public void AdmEventLog()
{
InitIntervalReport<EventLogReport>();
}
#endregion
#region Helper methods
internal static CreateReportFormDelegate CreateReportFormHandler
{
get { return m_CreateReportFormHandler; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
m_CreateReportFormHandler = value;
}
}
private static void InitDocumentReport<TR>(Dictionary<string, string> parameters)
where TR : BaseDocumentReport
{
BaseReportKeeper reportKeeper = new BaseDocumentKeeper(typeof (TR), parameters);
PlaceReportKeeper(reportKeeper);
}
private static void InitYearReport<TR>()
where TR : BaseYearReport
{
BaseReportKeeper reportKeeper = new BaseYearKeeper(typeof (TR));
PlaceReportKeeper(reportKeeper);
}
private static void InitIntervalReport<TR>()
where TR : BaseIntervalReport
{
BaseReportKeeper reportKeeper = new BaseIntervalKeeper(typeof (TR));
PlaceReportKeeper(reportKeeper);
}
private static BaseDateKeeper InitDateReport<TR>()
where TR : BaseDateReport
{
var reportKeeper = new BaseDateKeeper(typeof (TR));
PlaceReportKeeper(reportKeeper);
return reportKeeper;
}
private static void InitFormN1Report(bool isA3Format)
{
var reportKeeper = new FormN1Keeper {IsA3Format = isA3Format};
PlaceReportKeeper(reportKeeper);
}
private static void InitGGSampleReport<TR>()
where TR : BaseSampleReport
{
BaseReportKeeper reportKeeper = new BaseSampleKeeper(typeof (TR));
PlaceReportKeeper(reportKeeper);
}
private static void PlaceReportKeeper(BaseReportKeeper reportKeeper)
{
using (reportKeeper.ContextKeeper.CreateNewContext(ContextValue.ReportFormLoading))
{
IReportForm reportForm = CreateReportFormHandler();
m_ReportForms.Add(reportForm);
reportForm.FormClosed += reportForm_FormClosed;
reportForm.ShowReport(reportKeeper);
Application.DoEvents();
}
using (reportKeeper.ContextKeeper.CreateNewContext(ContextValue.ReportFirstLoading))
{
reportKeeper.ReloadReport(true);
}
}
private static void reportForm_FormClosed(object sender, FormClosedEventArgs e)
{
if (!(sender is IReportForm))
{
return;
}
m_ReportForms.Remove((IReportForm) sender);
}
#endregion
}
}
| |
// Copyright 2003 Eric Marchesin - <[email protected]>
//
// This source file(s) may be redistributed by any means PROVIDING they
// are not sold for profit without the authors expressed written consent,
// and providing that this notice and the authors name and all copyright
// notices remain intact.
// THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED. USE IT AT YOUR OWN RISK. THE AUTHOR ACCEPTS NO
// LIABILITY FOR ANY DATA DAMAGE/LOSS THAT THIS PRODUCT MAY CAUSE.
//-----------------------------------------------------------------------
using System;
namespace EMK.LightGeometry
{
/// <summary>
/// Basic geometry class : easy to replace
/// Written so as to be generalized
/// </summary>
[Serializable]
public class Point3D
{
double[] _Coordinates = new double[3];
/// <summary>
/// Point3D constructor.
/// </summary>
/// <exception cref="ArgumentNullException">Argument array must not be null.</exception>
/// <exception cref="ArgumentException">The Coordinates' array must contain exactly 3 elements.</exception>
/// <param name="Coordinates">An array containing the three coordinates' values.</param>
public Point3D(double[] Coordinates)
{
if ( Coordinates == null ) throw new ArgumentNullException();
if ( Coordinates.Length!=3 ) throw new ArgumentException("The Coordinates' array must contain exactly 3 elements.");
X = Coordinates[0]; Y = Coordinates[1]; Z = Coordinates[2];
}
/// <summary>
/// Point3D constructor.
/// </summary>
/// <param name="CoordinateX">X coordinate.</param>
/// <param name="CoordinateY">Y coordinate.</param>
/// <param name="CoordinateZ">Z coordinate.</param>
public Point3D(double CoordinateX, double CoordinateY, double CoordinateZ)
{
X = CoordinateX; Y = CoordinateY; Z = CoordinateZ;
}
/// <summary>
/// Accede to coordinates by indexes.
/// </summary>
/// <exception cref="IndexOutOfRangeException">Index must belong to [0;2].</exception>
public double this[int CoordinateIndex]
{
get { return _Coordinates[CoordinateIndex]; }
set { _Coordinates[CoordinateIndex] = value; }
}
/// <summary>
/// Gets/Set X coordinate.
/// </summary>
public double X { set { _Coordinates[0] = value; } get { return _Coordinates[0]; } }
/// <summary>
/// Gets/Set Y coordinate.
/// </summary>
public double Y { set { _Coordinates[1] = value; } get { return _Coordinates[1]; } }
/// <summary>
/// Gets/Set Z coordinate.
/// </summary>
public double Z { set { _Coordinates[2] = value; } get { return _Coordinates[2]; } }
/// <summary>
/// Returns the distance between two points.
/// </summary>
/// <param name="P1">First point.</param>
/// <param name="P2">Second point.</param>
/// <returns>Distance value.</returns>
public static double DistanceBetween(Point3D P1, Point3D P2)
{
return Math.Sqrt((P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y) + (P1.Z - P2.Z) * (P1.Z - P2.Z));
}
public static double DistanceBetweenX2(Point3D P1, Point3D P2)
{
return (P1.X - P2.X) * (P1.X - P2.X) + (P1.Y - P2.Y) * (P1.Y - P2.Y) + (P1.Z - P2.Z) * (P1.Z - P2.Z);
}
public double DOTP( Point3D other )
{
return this.X * other.X + this.Y * other.Y + this.Z * other.Z;
}
public double InterceptPercent( Point3D x2, Point3D x0) // % along the path THIS(x1)->X2 that a vector from X0 perpendicular meets it
{
double dotp = (this.X - x0.X) * (x2.X - this.X) + (this.Y - x0.Y) * (x2.Y - this.Y) + (this.Z - x0.Z) * (x2.Z - this.Z);
double mag2 = ((x2.X - this.X) * (x2.X - this.X) + (x2.Y - this.Y) * (x2.Y - this.Y) + (x2.Z - this.Z) * (x2.Z - this.Z));
return -dotp / mag2; // its -((x1-x0) dotp (x2-x1) / |x2-x1|^2)
}
public Point3D PointAlongPath(Point3D x1, double i) // i = 0 to 1.0, on the path. Negative before the path, >1 after the path
{
return new Point3D(this.X + (x1.X - this.X) * i, this.Y + (x1.Y - this.Y) * i, this.Z + (x1.Z - this.Z) * i);
}
public Point3D InterceptPoint( Point3D x2, Point3D x0 ) // from this(x1) to X2, given a point x0, where do the perpendiclar intercept?
{
return PointAlongPath(x2, InterceptPercent(x2, x0));
}
public Point3D Subtract(Point3D other )
{
return new Point3D(this.X - other.X, this.Y - other.Y, this.Z - other.Z);
}
public static double InterceptPercent000(Point3D x2, Point3D x0) // % along the path 0,0,0->X2 that a vector from X0 perpendicular meets it
{
double dotp = (-x0.X) * (x2.X) + (-x0.Y) * (x2.Y) + (-x0.Z) * (x2.Z); // this is 0,0,0 in effect, so remove terms
double mag2 = ((x2.X) * (x2.X) + (x2.Y) * (x2.Y) + (x2.Z) * (x2.Z));
return -dotp / mag2; // its -((x1-x0) dotp (x2-x1) / |x2-x1|^2) where x0 =0,0,0
}
public static Point3D PointAlongVector(Point3D x1, double i) // i = 0 to 1.0, on the vector from 000
{
return new Point3D(x1.X * i, x1.Y * i, x1.Z * i);
}
/// <summary>
/// Returns the projection of a point on the line defined with two other points.
/// When the projection is out of the segment, then the closest extremity is returned.
/// </summary>
/// <exception cref="ArgumentNullException">None of the arguments can be null.</exception>
/// <exception cref="ArgumentException">P1 and P2 must be different.</exception>
/// <param name="Pt">Point to project.</param>
/// <param name="P1">First point of the line.</param>
/// <param name="P2">Second point of the line.</param>
/// <returns>The projected point if it is on the segment / The closest extremity otherwise.</returns>
public static Point3D ProjectOnLine(Point3D Pt, Point3D P1, Point3D P2)
{
if ( Pt==null || P1==null || P2==null ) throw new ArgumentNullException("None of the arguments can be null.");
if ( P1.Equals(P2) ) throw new ArgumentException("P1 and P2 must be different.");
Vector3D VLine = new Vector3D(P1, P2);
Vector3D V1Pt = new Vector3D(P1, Pt);
Vector3D Translation = VLine*(VLine|V1Pt)/VLine.SquareNorm;
Point3D Projection = P1+Translation;
Vector3D V1Pjt = new Vector3D(P1, Projection);
double D1 = V1Pjt|VLine;
if ( D1<0 ) return P1;
Vector3D V2Pjt = new Vector3D(P2, Projection);
double D2 = V2Pjt|VLine;
if ( D2>0 ) return P2;
return Projection;
}
/// <summary>
/// Object.Equals override.
/// Tells if two points are equal by comparing coordinates.
/// </summary>
/// <exception cref="ArgumentException">Cannot compare Point3D with another type.</exception>
/// <param name="Point">The other 3DPoint to compare with.</param>
/// <returns>'true' if points are equal.</returns>
public override bool Equals(object Point)
{
Point3D P = (Point3D)Point;
if ( P==null ) throw new ArgumentException("Object must be of type "+GetType());
bool Resultat = true;
for (int i=0; i<3; i++) Resultat &= P[i].Equals(this[i]);
return Resultat;
}
/// <summary>
/// Object.GetHashCode override.
/// </summary>
/// <returns>HashCode value.</returns>
public override int GetHashCode()
{
double HashCode = 0;
for (int i=0; i<3; i++) HashCode += this[i];
return (int)HashCode;
}
/// <summary>
/// Object.GetHashCode override.
/// Returns a textual description of the point.
/// </summary>
/// <returns>String describing this point.</returns>
public override string ToString()
{
string Deb = "{";
string Sep = ";";
string Fin = "}";
string Resultat = Deb;
int Dimension = 3;
for (int i=0; i<Dimension; i++)
Resultat += _Coordinates[i].ToString() + (i!=Dimension-1 ? Sep : Fin);
return Resultat;
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Threading.Tasks;
using Windows.Data.Json;
using Windows.Embedded.DeviceLockdown;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;
namespace SDKTemplate
{
public sealed partial class Scenario1_SignIn : Page
{
private MainPage rootPage = MainPage.Current;
bool canSignOut;
// Note: 'tenant' and 'clientId' will need to be updated based on your particular Azure Active Directory configuration.
// See the README for more information.
readonly string tenant = "contoso.onmicrosoft.com";
readonly string clientId = "{...}";
readonly Uri RedirectURI = Windows.Security.Authentication.Web.WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
readonly string resource = "https://graph.windows.net";
readonly string apiversion = "?api-version=2013-04-05";
readonly AuthenticationContext authenticationContext;
public Scenario1_SignIn()
{
this.InitializeComponent();
// Initialize the authentication context for Azure Authentication.
string authority = "https://login.windows.net/" + tenant;
authenticationContext = new AuthenticationContext(authority);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (tenant == "contoso.onmicrosoft.com" || clientId == "{...}")
{
// The user has not configured the sample for Azure Authentication.
UseAzureAuthenticationCheckBox.IsEnabled = false;
UseAzureAuthenticationCheckBox.IsChecked = false;
rootPage.NotifyUser("This sample has not been configured for Azure Authentication.", NotifyType.ErrorMessage);
}
try
{
// If the current role is Guid.Empty, then the user is not signed in.
Guid currentRole = DeviceLockdownProfile.GetCurrentLockdownProfile();
if (currentRole == Guid.Empty)
{
SignInStatus.Text = "You are not signed in.";
canSignOut = false;
}
else
{
DeviceLockdownProfileInformation currentProfile = DeviceLockdownProfile.GetLockdownProfileInformation(currentRole);
SignInStatus.Text = "You are signed in as " + currentProfile.Name;
canSignOut = true;
}
SignOutButton.IsEnabled = canSignOut;
LoadApplicationUsers();
}
catch (System.IO.FileNotFoundException)
{
rootPage.NotifyUser("Assigned Access is not configured on this device.", NotifyType.ErrorMessage);
}
}
private void LoadApplicationUsers()
{
// Add the available roles.
foreach (Guid roleId in DeviceLockdownProfile.GetSupportedLockdownProfiles())
{
DeviceLockdownProfileInformation profile = DeviceLockdownProfile.GetLockdownProfileInformation(roleId);
UserRoles.Items.Add(new ListBoxItem() { Content = profile.Name, Tag = roleId });
}
// If there are roles available, then pre-select the first one and enable the Sign In button.
if (UserRoles.Items.Count > 0)
{
UserRoles.SelectedIndex = 0;
SignInButton.IsEnabled = true;
}
}
private void DisableUI()
{
// Clear any previous error message.
rootPage.NotifyUser("", NotifyType.StatusMessage);
// Disable all the buttons while we sign the user in or out.
SignInButton.IsEnabled = false;
SignOutButton.IsEnabled = false;
// Display the progress control so the user knows that we are working.
ProgressControl.IsActive = true;
}
private void EnableUI()
{
// Hide the progress control.
ProgressControl.IsActive = false;
// Restore the buttons.
SignOutButton.IsEnabled = canSignOut;
SignInButton.IsEnabled = true;
}
private async void SignIn()
{
DisableUI();
await SignInAsync();
EnableUI();
}
private async Task SignInAsync()
{
// Extract the name and role of the item the user selected.
ListBoxItem selectedItem = (ListBoxItem)UserRoles.SelectedItem;
string selectedName = (string)selectedItem.Content;
Guid selectedRole = (Guid)selectedItem.Tag;
bool canSignIn;
if (UseAzureAuthenticationCheckBox.IsChecked.Value)
{
canSignIn = await AuthenticateAzureRole(selectedRole, selectedName);
}
else
{
// If the sample should use local authentication,
// then do some app-specific authentication here.
// For this sample, we just assume anybody can sign in as any role.
canSignIn = true;
}
if (canSignIn)
{
// Note that successfully applying the profile will result in the termination of all running apps, including this sample.
await DeviceLockdownProfile.ApplyLockdownProfileAsync(selectedRole);
}
}
private async Task<bool> AuthenticateAzureRole(Guid selectedRole, string selectedName)
{
// Display the Azure authentication dialog to gather user credentials.
AuthenticationResult authResult = await this.authenticationContext.AcquireTokenAsync(
this.resource,
this.clientId,
this.RedirectURI,
PromptBehavior.Always);
if (authResult.Status != AuthenticationStatus.Success)
{
// Report the failure to the user.
string details = string.Format("Error: {0}\nDetails: {1}", authResult.Error, authResult.ErrorDescription);
switch (authResult.Status)
{
case AuthenticationStatus.ClientError:
details = "Could not contact the server. Check that you have Internet access.\n" + details;
break;
case AuthenticationStatus.ServiceError:
details = "The server could not sign you in.\n" + details;
break;
}
rootPage.NotifyUser(details, NotifyType.ErrorMessage);
return false;
}
// Formulate an http query using the graph API to determine what roles (also known as groups)
// the user belongs to.
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add(
"Authorization",
string.Format("Bearer {0}", authResult.AccessToken));
Uri requestUri = new Uri(
this.resource + "/" +
this.tenant +
"/users/" + authResult.UserInfo.DisplayableId +
"/memberOf" + this.apiversion);
// Perform the query.
HttpResponseMessage httpResponse = await httpClient.GetAsync(requestUri);
if (!httpResponse.IsSuccessStatusCode)
{
rootPage.NotifyUser(string.Format("Sorry, an error occured. Please sign-in again. Error: {0}", httpResponse.StatusCode), NotifyType.ErrorMessage);
return false;
}
// The graph API response contains the GUIDs of all the roles the user is a member of.
string graphResponse = await httpResponse.Content.ReadAsStringAsync();
// See whether the user belongs to the selected role.
// The "value" array contains a list of objects. The "objectId" tells us the role.
try
{
foreach (JsonValue value in JsonObject.Parse(graphResponse).GetNamedArray("value"))
{
Guid role = Guid.Parse(value.GetObject().GetNamedValue("objectId").GetString());
if (role == selectedRole)
{
return true;
}
}
}
catch (Exception)
{
// There was a problem parsing the JSON. It wasn't in the format we expected.
rootPage.NotifyUser("Invalid response from server.", NotifyType.ErrorMessage);
}
rootPage.NotifyUser(string.Format("User '{0}' is not a member of '{1}'", authResult.UserInfo.DisplayableId, selectedName), NotifyType.ErrorMessage);
return false;
}
private async void SignOut()
{
DisableUI();
await SignOutAsync();
EnableUI();
}
private async Task SignOutAsync()
{
// Apply the Default role, which is represented by Guid.Empty.
// The Default role is the one that is used when nobody is signed in.
// Note that successfully applying the profile will result in the termination of all running apps, including this sample.
await DeviceLockdownProfile.ApplyLockdownProfileAsync(Guid.Empty);
}
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: [email protected]
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Model
{
/// <summary>
/// ListView
/// </summary>
[DataContract(Name = "ListView")]
public partial class ListView : IEquatable<ListView>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="ListView" /> class.
/// </summary>
/// <param name="_class">_class.</param>
/// <param name="description">description.</param>
/// <param name="jobs">jobs.</param>
/// <param name="name">name.</param>
/// <param name="url">url.</param>
public ListView(string _class = default(string), string description = default(string), List<FreeStyleProject> jobs = default(List<FreeStyleProject>), string name = default(string), string url = default(string))
{
this.Class = _class;
this.Description = description;
this.Jobs = jobs;
this.Name = name;
this.Url = url;
}
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name = "_class", EmitDefaultValue = false)]
public string Class { get; set; }
/// <summary>
/// Gets or Sets Description
/// </summary>
[DataMember(Name = "description", EmitDefaultValue = false)]
public string Description { get; set; }
/// <summary>
/// Gets or Sets Jobs
/// </summary>
[DataMember(Name = "jobs", EmitDefaultValue = false)]
public List<FreeStyleProject> Jobs { get; set; }
/// <summary>
/// Gets or Sets Name
/// </summary>
[DataMember(Name = "name", EmitDefaultValue = false)]
public string Name { get; set; }
/// <summary>
/// Gets or Sets Url
/// </summary>
[DataMember(Name = "url", EmitDefaultValue = false)]
public string Url { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append("class ListView {\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" Jobs: ").Append(Jobs).Append("\n");
sb.Append(" Name: ").Append(Name).Append("\n");
sb.Append(" Url: ").Append(Url).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as ListView);
}
/// <summary>
/// Returns true if ListView instances are equal
/// </summary>
/// <param name="input">Instance of ListView to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ListView input)
{
if (input == null)
{
return false;
}
return
(
this.Class == input.Class ||
(this.Class != null &&
this.Class.Equals(input.Class))
) &&
(
this.Description == input.Description ||
(this.Description != null &&
this.Description.Equals(input.Description))
) &&
(
this.Jobs == input.Jobs ||
this.Jobs != null &&
input.Jobs != null &&
this.Jobs.SequenceEqual(input.Jobs)
) &&
(
this.Name == input.Name ||
(this.Name != null &&
this.Name.Equals(input.Name))
) &&
(
this.Url == input.Url ||
(this.Url != null &&
this.Url.Equals(input.Url))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Class != null)
{
hashCode = (hashCode * 59) + this.Class.GetHashCode();
}
if (this.Description != null)
{
hashCode = (hashCode * 59) + this.Description.GetHashCode();
}
if (this.Jobs != null)
{
hashCode = (hashCode * 59) + this.Jobs.GetHashCode();
}
if (this.Name != null)
{
hashCode = (hashCode * 59) + this.Name.GetHashCode();
}
if (this.Url != null)
{
hashCode = (hashCode * 59) + this.Url.GetHashCode();
}
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Diagnostics.AddBraces;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddBraces
{
public partial class AddBracesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpAddBracesDiagnosticAnalyzer(), new CSharpAddBracesCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForIfWithBraces()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
[|if|] (true)
{
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForElseWithBraces()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
if (true)
{
return;
}
[|else|]
{
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForElseWithChildIf()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
if (true)
return;
[|else|] if (false)
return;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForForWithBraces()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
[|for|] (var i = 0; i < 5; i++)
{
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForForEachWithBraces()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
[|foreach|] (var c in ""test"")
{
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForWhileWithBraces()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
[|while|] (true)
{
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForDoWhileWithBraces()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
[|do|]
{
return;
}
while (true);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForUsingWithBraces()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
[|using|] (var f = new Fizz())
{
return;
}
}
}
class Fizz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForUsingWithChildUsing()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
[|using|] (var f = new Fizz())
using (var b = new Buzz())
return;
}
}
class Fizz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
class Buzz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForLockWithBraces()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
var str = ""test"";
[|lock|] (str)
{
return;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task DoNotFireForLockWithChildLock()
{
await TestMissingInRegularAndScriptAsync(
@"class Program
{
static void Main()
{
var str1 = ""test"";
var str2 = ""test"";
[|lock|] (str1)
lock (str2)
return;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForIfWithoutBraces()
{
await TestInRegularAndScriptAsync(
@"
class Program
{
static void Main()
{
[|if|] (true) return;
}
}",
@"
class Program
{
static void Main()
{
if (true)
{
return;
}
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForElseWithoutBraces()
{
await TestInRegularAndScriptAsync(
@"
class Program
{
static void Main()
{
if (true) { return; }
[|else|] return;
}
}",
@"
class Program
{
static void Main()
{
if (true) { return; }
else
{
return;
}
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForIfNestedInElseWithoutBraces()
{
await TestInRegularAndScriptAsync(
@"
class Program
{
static void Main()
{
if (true) return;
else [|if|] (false) return;
}
}",
@"
class Program
{
static void Main()
{
if (true) return;
else if (false)
{
return;
}
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForForWithoutBraces()
{
await TestInRegularAndScriptAsync(
@"
class Program
{
static void Main()
{
[|for|] (var i = 0; i < 5; i++) return;
}
}",
@"
class Program
{
static void Main()
{
for (var i = 0; i < 5; i++)
{
return;
}
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForForEachWithoutBraces()
{
await TestInRegularAndScriptAsync(
@"
class Program
{
static void Main()
{
[|foreach|] (var c in ""test"") return;
}
}",
@"
class Program
{
static void Main()
{
foreach (var c in ""test"")
{
return;
}
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForWhileWithoutBraces()
{
await TestInRegularAndScriptAsync(
@"
class Program
{
static void Main()
{
[|while|] (true) return;
}
}",
@"
class Program
{
static void Main()
{
while (true)
{
return;
}
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForDoWhileWithoutBraces()
{
await TestInRegularAndScriptAsync(
@"
class Program
{
static void Main()
{
[|do|] return; while (true);
}
}",
@"
class Program
{
static void Main()
{
do
{
return;
}
while (true);
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForUsingWithoutBraces()
{
await TestInRegularAndScriptAsync(
@"
class Program
{
static void Main()
{
[|using|] (var f = new Fizz())
return;
}
}
class Fizz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}",
@"
class Program
{
static void Main()
{
using (var f = new Fizz())
{
return;
}
}
}
class Fizz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForUsingWithoutBracesNestedInUsing()
{
await TestInRegularAndScriptAsync(
@"
class Program
{
static void Main()
{
using (var f = new Fizz())
[|using|] (var b = new Buzz())
return;
}
}
class Fizz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
class Buzz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}",
@"
class Program
{
static void Main()
{
using (var f = new Fizz())
using (var b = new Buzz())
{
return;
}
}
}
class Fizz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}
class Buzz : IDisposable
{
public void Dispose()
{
throw new NotImplementedException();
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForLockWithoutBraces()
{
await TestInRegularAndScriptAsync(
@"
class Program
{
static void Main()
{
var str = ""test"";
[|lock|] (str)
return;
}
}",
@"
class Program
{
static void Main()
{
var str = ""test"";
lock (str)
{
return;
}
}
}",
ignoreTrivia: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddBraces)]
public async Task FireForLockWithoutBracesNestedInLock()
{
await TestInRegularAndScriptAsync(
@"
class Program
{
static void Main()
{
var str1 = ""test"";
var str2 = ""test"";
lock (str1)
[|lock|] (str2) // VS thinks this should be indented one more level
return;
}
}",
@"
class Program
{
static void Main()
{
var str1 = ""test"";
var str2 = ""test"";
lock (str1)
lock (str2) // VS thinks this should be indented one more level
{
return;
}
}
}",
ignoreTrivia: false);
}
}
}
| |
// 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.
using System.Collections.Immutable;
namespace System.Reflection.Metadata.Ecma335
{
// TODO: debug metadata blobs
// TODO: revisit ctors (public vs internal vs static factories)?
public struct BlobEncoder
{
public BlobBuilder Builder { get; }
public BlobEncoder(BlobBuilder builder)
{
if (builder == null)
{
Throw.BuilderArgumentNull();
}
Builder = builder;
}
/// <summary>
/// Encodes Field Signature blob.
/// </summary>
/// <returns>Encoder of the field type.</returns>
public SignatureTypeEncoder FieldSignature()
{
Builder.WriteByte((byte)SignatureKind.Field);
return new SignatureTypeEncoder(Builder);
}
/// <summary>
/// Encodes Method Specification Signature blob.
/// </summary>
/// <param name="genericArgumentCount">Number of generic arguments.</param>
/// <returns>Encoder of generic arguments.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="genericArgumentCount"/> is not in range [0, 0xffff].</exception>
public GenericTypeArgumentsEncoder MethodSpecificationSignature(int genericArgumentCount)
{
if (unchecked((uint)genericArgumentCount) > ushort.MaxValue)
{
Throw.ArgumentOutOfRange(nameof(genericArgumentCount));
}
Builder.WriteByte((byte)SignatureKind.MethodSpecification);
Builder.WriteCompressedInteger(genericArgumentCount);
return new GenericTypeArgumentsEncoder(Builder);
}
/// <summary>
/// Encodes Method Signature blob.
/// </summary>
/// <param name="convention">Calling convention.</param>
/// <param name="genericParameterCount">Number of generic parameters.</param>
/// <param name="isInstanceMethod">True to encode an instance method signature, false to encode a static method signature.</param>
/// <returns>An Encoder of the rest of the signature including return value and parameters.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="genericParameterCount"/> is not in range [0, 0xffff].</exception>
public MethodSignatureEncoder MethodSignature(
SignatureCallingConvention convention = SignatureCallingConvention.Default,
int genericParameterCount = 0,
bool isInstanceMethod = false)
{
if (unchecked((uint)genericParameterCount) > ushort.MaxValue)
{
Throw.ArgumentOutOfRange(nameof(genericParameterCount));
}
var attributes =
(genericParameterCount != 0 ? SignatureAttributes.Generic : 0) |
(isInstanceMethod ? SignatureAttributes.Instance : 0);
Builder.WriteByte(new SignatureHeader(SignatureKind.Method, convention, attributes).RawValue);
if (genericParameterCount != 0)
{
Builder.WriteCompressedInteger(genericParameterCount);
}
return new MethodSignatureEncoder(Builder, hasVarArgs: convention == SignatureCallingConvention.VarArgs);
}
/// <summary>
/// Encodes Property Signature blob.
/// </summary>
/// <param name="isInstanceProperty">True to encode an instance property signature, false to encode a static property signature.</param>
/// <returns>An Encoder of the rest of the signature including return value and parameters, which has the same structure as Method Signature.</returns>
public MethodSignatureEncoder PropertySignature(bool isInstanceProperty = false)
{
Builder.WriteByte(new SignatureHeader(SignatureKind.Property, SignatureCallingConvention.Default, (isInstanceProperty ? SignatureAttributes.Instance : 0)).RawValue);
return new MethodSignatureEncoder(Builder, hasVarArgs: false);
}
/// <summary>
/// Encodes Custom Attribute Signature blob.
/// Returns a pair of encoders that must be used in the order they appear in the parameter list.
/// </summary>
/// <param name="fixedArguments">Use first, to encode fixed arguments.</param>
/// <param name="namedArguments">Use second, to encode named arguments.</param>
public void CustomAttributeSignature(out FixedArgumentsEncoder fixedArguments, out CustomAttributeNamedArgumentsEncoder namedArguments)
{
Builder.WriteUInt16(0x0001);
fixedArguments = new FixedArgumentsEncoder(Builder);
namedArguments = new CustomAttributeNamedArgumentsEncoder(Builder);
}
/// <summary>
/// Encodes Custom Attribute Signature blob.
/// </summary>
/// <param name="fixedArguments">Called first, to encode fixed arguments.</param>
/// <param name="namedArguments">Called second, to encode named arguments.</param>
/// <exception cref="ArgumentNullException"><paramref name="fixedArguments"/> or <paramref name="namedArguments"/> is null.</exception>
public void CustomAttributeSignature(Action<FixedArgumentsEncoder> fixedArguments, Action<CustomAttributeNamedArgumentsEncoder> namedArguments)
{
if (fixedArguments == null) Throw.ArgumentNull(nameof(fixedArguments));
if (namedArguments == null) Throw.ArgumentNull(nameof(namedArguments));
FixedArgumentsEncoder fixedArgumentsEncoder;
CustomAttributeNamedArgumentsEncoder namedArgumentsEncoder;
CustomAttributeSignature(out fixedArgumentsEncoder, out namedArgumentsEncoder);
fixedArguments(fixedArgumentsEncoder);
namedArguments(namedArgumentsEncoder);
}
/// <summary>
/// Encodes Local Variable Signature.
/// </summary>
/// <param name="variableCount">Number of local variables.</param>
/// <returns>Encoder of a sequence of local variables.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="variableCount"/> is not in range [0, 0x1fffffff].</exception>
public LocalVariablesEncoder LocalVariableSignature(int variableCount)
{
if (unchecked((uint)variableCount) > BlobWriterImpl.MaxCompressedIntegerValue)
{
Throw.ArgumentOutOfRange(nameof(variableCount));
}
Builder.WriteByte((byte)SignatureKind.LocalVariables);
Builder.WriteCompressedInteger(variableCount);
return new LocalVariablesEncoder(Builder);
}
/// <summary>
/// Encodes Type Specification Signature.
/// </summary>
/// <returns>
/// Type encoder of the structured type represented by the Type Specification (it shall not encode a primitive type).
/// </returns>
public SignatureTypeEncoder TypeSpecificationSignature()
{
return new SignatureTypeEncoder(Builder);
}
/// <summary>
/// Encodes a Permission Set blob.
/// </summary>
/// <param name="attributeCount">Number of attributes in the set.</param>
/// <returns>Permission Set encoder.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="attributeCount"/> is not in range [0, 0x1fffffff].</exception>
public PermissionSetEncoder PermissionSetBlob(int attributeCount)
{
if (unchecked((uint)attributeCount) > BlobWriterImpl.MaxCompressedIntegerValue)
{
Throw.ArgumentOutOfRange(nameof(attributeCount));
}
Builder.WriteByte((byte)'.');
Builder.WriteCompressedInteger(attributeCount);
return new PermissionSetEncoder(Builder);
}
/// <summary>
/// Encodes Permission Set arguments.
/// </summary>
/// <param name="argumentCount">Number of arguments in the set.</param>
/// <returns>Encoder of the arguments of the set.</returns>
public NamedArgumentsEncoder PermissionSetArguments(int argumentCount)
{
if (unchecked((uint)argumentCount) > BlobWriterImpl.MaxCompressedIntegerValue)
{
Throw.ArgumentOutOfRange(nameof(argumentCount));
}
Builder.WriteCompressedInteger(argumentCount);
return new NamedArgumentsEncoder(Builder);
}
}
public struct MethodSignatureEncoder
{
public BlobBuilder Builder { get; }
public bool HasVarArgs { get; }
public MethodSignatureEncoder(BlobBuilder builder, bool hasVarArgs)
{
Builder = builder;
HasVarArgs = hasVarArgs;
}
/// <summary>
/// Encodes return type and parameters.
/// Returns a pair of encoders that must be used in the order they appear in the parameter list.
/// </summary>
/// <param name="parameterCount">Number of parameters.</param>
/// <param name="returnType">Use first, to encode the return types.</param>
/// <param name="parameters">Use second, to encode the actual parameters.</param>
public void Parameters(int parameterCount, out ReturnTypeEncoder returnType, out ParametersEncoder parameters)
{
if (unchecked((uint)parameterCount) > BlobWriterImpl.MaxCompressedIntegerValue)
{
Throw.ArgumentOutOfRange(nameof(parameterCount));
}
Builder.WriteCompressedInteger(parameterCount);
returnType = new ReturnTypeEncoder(Builder);
parameters = new ParametersEncoder(Builder, hasVarArgs: HasVarArgs);
}
/// <summary>
/// Encodes return type and parameters.
/// </summary>
/// <param name="parameterCount">Number of parameters.</param>
/// <param name="returnType">Called first, to encode the return type.</param>
/// <param name="parameters">Called second, to encode the actual parameters.</param>
/// <exception cref="ArgumentNullException"><paramref name="returnType"/> or <paramref name="parameters"/> is null.</exception>
public void Parameters(int parameterCount, Action<ReturnTypeEncoder> returnType, Action<ParametersEncoder> parameters)
{
if (returnType == null) Throw.ArgumentNull(nameof(returnType));
if (parameters == null) Throw.ArgumentNull(nameof(parameters));
ReturnTypeEncoder returnTypeEncoder;
ParametersEncoder parametersEncoder;
Parameters(parameterCount, out returnTypeEncoder, out parametersEncoder);
returnType(returnTypeEncoder);
parameters(parametersEncoder);
}
}
public struct LocalVariablesEncoder
{
public BlobBuilder Builder { get; }
public LocalVariablesEncoder(BlobBuilder builder)
{
Builder = builder;
}
public LocalVariableTypeEncoder AddVariable()
{
return new LocalVariableTypeEncoder(Builder);
}
}
public struct LocalVariableTypeEncoder
{
public BlobBuilder Builder { get; }
public LocalVariableTypeEncoder(BlobBuilder builder)
{
Builder = builder;
}
public CustomModifiersEncoder CustomModifiers()
{
return new CustomModifiersEncoder(Builder);
}
public SignatureTypeEncoder Type(bool isByRef = false, bool isPinned = false)
{
if (isPinned)
{
Builder.WriteByte((byte)SignatureTypeCode.Pinned);
}
if (isByRef)
{
Builder.WriteByte((byte)SignatureTypeCode.ByReference);
}
return new SignatureTypeEncoder(Builder);
}
public void TypedReference()
{
Builder.WriteByte((byte)SignatureTypeCode.TypedReference);
}
}
public struct ParameterTypeEncoder
{
public BlobBuilder Builder { get; }
public ParameterTypeEncoder(BlobBuilder builder)
{
Builder = builder;
}
public CustomModifiersEncoder CustomModifiers()
{
return new CustomModifiersEncoder(Builder);
}
public SignatureTypeEncoder Type(bool isByRef = false)
{
if (isByRef)
{
Builder.WriteByte((byte)SignatureTypeCode.ByReference);
}
return new SignatureTypeEncoder(Builder);
}
public void TypedReference()
{
Builder.WriteByte((byte)SignatureTypeCode.TypedReference);
}
}
public struct PermissionSetEncoder
{
public BlobBuilder Builder { get; }
public PermissionSetEncoder(BlobBuilder builder)
{
Builder = builder;
}
public PermissionSetEncoder AddPermission(string typeName, ImmutableArray<byte> encodedArguments)
{
if (typeName == null)
{
Throw.ArgumentNull(nameof(typeName));
}
if (encodedArguments.IsDefault)
{
Throw.ArgumentNull(nameof(encodedArguments));
}
if (encodedArguments.Length > BlobWriterImpl.MaxCompressedIntegerValue)
{
Throw.BlobTooLarge(nameof(encodedArguments));
}
Builder.WriteSerializedString(typeName);
Builder.WriteCompressedInteger(encodedArguments.Length);
Builder.WriteBytes(encodedArguments);
return this;
}
public PermissionSetEncoder AddPermission(string typeName, BlobBuilder encodedArguments)
{
if (typeName == null)
{
Throw.ArgumentNull(nameof(typeName));
}
if (encodedArguments == null)
{
Throw.ArgumentNull(nameof(encodedArguments));
}
if (encodedArguments.Count > BlobWriterImpl.MaxCompressedIntegerValue)
{
Throw.BlobTooLarge(nameof(encodedArguments));
}
Builder.WriteSerializedString(typeName);
Builder.WriteCompressedInteger(encodedArguments.Count);
encodedArguments.WriteContentTo(Builder);
return this;
}
}
public struct GenericTypeArgumentsEncoder
{
public BlobBuilder Builder { get; }
public GenericTypeArgumentsEncoder(BlobBuilder builder)
{
Builder = builder;
}
public SignatureTypeEncoder AddArgument()
{
return new SignatureTypeEncoder(Builder);
}
}
public struct FixedArgumentsEncoder
{
public BlobBuilder Builder { get; }
public FixedArgumentsEncoder(BlobBuilder builder)
{
Builder = builder;
}
public LiteralEncoder AddArgument()
{
return new LiteralEncoder(Builder);
}
}
public struct LiteralEncoder
{
public BlobBuilder Builder { get; }
public LiteralEncoder(BlobBuilder builder)
{
Builder = builder;
}
public VectorEncoder Vector()
{
return new VectorEncoder(Builder);
}
/// <summary>
/// Encodes the type and the items of a vector literal.
/// Returns a pair of encoders that must be used in the order they appear in the parameter list.
/// </summary>
/// <param name="arrayType">Use first, to encode the type of the vector.</param>
/// <param name="vector">Use second, to encode the items of the vector.</param>
public void TaggedVector(out CustomAttributeArrayTypeEncoder arrayType, out VectorEncoder vector)
{
arrayType = new CustomAttributeArrayTypeEncoder(Builder);
vector = new VectorEncoder(Builder);
}
/// <summary>
/// Encodes the type and the items of a vector literal.
/// </summary>
/// <param name="arrayType">Called first, to encode the type of the vector.</param>
/// <param name="vector">Called second, to encode the items of the vector.</param>
/// <exception cref="ArgumentNullException"><paramref name="arrayType"/> or <paramref name="vector"/> is null.</exception>
public void TaggedVector(Action<CustomAttributeArrayTypeEncoder> arrayType, Action<VectorEncoder> vector)
{
if (arrayType == null) Throw.ArgumentNull(nameof(arrayType));
if (vector == null) Throw.ArgumentNull(nameof(vector));
CustomAttributeArrayTypeEncoder arrayTypeEncoder;
VectorEncoder vectorEncoder;
TaggedVector(out arrayTypeEncoder, out vectorEncoder);
arrayType(arrayTypeEncoder);
vector(vectorEncoder);
}
/// <summary>
/// Encodes a scalar literal.
/// </summary>
/// <returns>Encoder of the literal value.</returns>
public ScalarEncoder Scalar()
{
return new ScalarEncoder(Builder);
}
/// <summary>
/// Encodes the type and the value of a literal.
/// Returns a pair of encoders that must be used in the order they appear in the parameter list.
/// </summary>
/// <param name="type">Called first, to encode the type of the literal.</param>
/// <param name="scalar">Called second, to encode the value of the literal.</param>
public void TaggedScalar(out CustomAttributeElementTypeEncoder type, out ScalarEncoder scalar)
{
type = new CustomAttributeElementTypeEncoder(Builder);
scalar = new ScalarEncoder(Builder);
}
/// <summary>
/// Encodes the type and the value of a literal.
/// </summary>
/// <param name="type">Called first, to encode the type of the literal.</param>
/// <param name="scalar">Called second, to encode the value of the literal.</param>
/// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="scalar"/> is null.</exception>
public void TaggedScalar(Action<CustomAttributeElementTypeEncoder> type, Action<ScalarEncoder> scalar)
{
if (type == null) Throw.ArgumentNull(nameof(type));
if (scalar == null) Throw.ArgumentNull(nameof(scalar));
CustomAttributeElementTypeEncoder typeEncoder;
ScalarEncoder scalarEncoder;
TaggedScalar(out typeEncoder, out scalarEncoder);
type(typeEncoder);
scalar(scalarEncoder);
}
}
public struct ScalarEncoder
{
public BlobBuilder Builder { get; }
public ScalarEncoder(BlobBuilder builder)
{
Builder = builder;
}
/// <summary>
/// Encodes <c>null</c> literal of type <see cref="Array"/>.
/// </summary>
public void NullArray()
{
Builder.WriteInt32(-1);
}
/// <summary>
/// Encodes constant literal.
/// </summary>
/// <param name="value">
/// Constant of type
/// <see cref="bool"/>,
/// <see cref="byte"/>,
/// <see cref="sbyte"/>,
/// <see cref="short"/>,
/// <see cref="ushort"/>,
/// <see cref="int"/>,
/// <see cref="uint"/>,
/// <see cref="long"/>,
/// <see cref="ulong"/>,
/// <see cref="float"/>,
/// <see cref="double"/>,
/// <see cref="char"/> (encoded as two-byte Unicode character),
/// <see cref="string"/> (encoded as SerString), or
/// <see cref="Enum"/> (encoded as the underlying integer value).
/// </param>
/// <exception cref="ArgumentException">Unexpected constant type.</exception>
public void Constant(object value)
{
string str = value as string;
if (str != null || value == null)
{
String(str);
}
else
{
Builder.WriteConstant(value);
}
}
/// <summary>
/// Encodes literal of type <see cref="Type"/> (possibly null).
/// </summary>
/// <param name="serializedTypeName">The name of the type, or null.</param>
/// <exception cref="ArgumentException"><paramref name="serializedTypeName"/> is empty.</exception>
public void SystemType(string serializedTypeName)
{
if (serializedTypeName != null && serializedTypeName.Length == 0)
{
Throw.ArgumentEmptyString(nameof(serializedTypeName));
}
String(serializedTypeName);
}
private void String(string value)
{
Builder.WriteSerializedString(value);
}
}
public struct LiteralsEncoder
{
public BlobBuilder Builder { get; }
public LiteralsEncoder(BlobBuilder builder)
{
Builder = builder;
}
public LiteralEncoder AddLiteral()
{
return new LiteralEncoder(Builder);
}
}
public struct VectorEncoder
{
public BlobBuilder Builder { get; }
public VectorEncoder(BlobBuilder builder)
{
Builder = builder;
}
public LiteralsEncoder Count(int count)
{
if (count < 0)
{
Throw.ArgumentOutOfRange(nameof(count));
}
Builder.WriteUInt32((uint)count);
return new LiteralsEncoder(Builder);
}
}
public struct NameEncoder
{
public BlobBuilder Builder { get; }
public NameEncoder(BlobBuilder builder)
{
Builder = builder;
}
public void Name(string name)
{
if (name == null) Throw.ArgumentNull(nameof(name));
if (name.Length == 0) Throw.ArgumentEmptyString(nameof(name));
Builder.WriteSerializedString(name);
}
}
public struct CustomAttributeNamedArgumentsEncoder
{
public BlobBuilder Builder { get; }
public CustomAttributeNamedArgumentsEncoder(BlobBuilder builder)
{
Builder = builder;
}
public NamedArgumentsEncoder Count(int count)
{
if (unchecked((uint)count) > ushort.MaxValue)
{
Throw.ArgumentOutOfRange(nameof(count));
}
Builder.WriteUInt16((ushort)count);
return new NamedArgumentsEncoder(Builder);
}
}
public struct NamedArgumentsEncoder
{
public BlobBuilder Builder { get; }
public NamedArgumentsEncoder(BlobBuilder builder)
{
Builder = builder;
}
/// <summary>
/// Encodes a named argument (field or property).
/// Returns a triplet of encoders that must be used in the order they appear in the parameter list.
/// </summary>
/// <param name="isField">True to encode a field, false to encode a property.</param>
/// <param name="type">Use first, to encode the type of the argument.</param>
/// <param name="name">Use second, to encode the name of the field or property.</param>
/// <param name="literal">Use third, to encode the literal value of the argument.</param>
public void AddArgument(bool isField, out NamedArgumentTypeEncoder type, out NameEncoder name, out LiteralEncoder literal)
{
Builder.WriteByte(isField ? (byte)CustomAttributeNamedArgumentKind.Field : (byte)CustomAttributeNamedArgumentKind.Property);
type = new NamedArgumentTypeEncoder(Builder);
name = new NameEncoder(Builder);
literal = new LiteralEncoder(Builder);
}
/// <summary>
/// Encodes a named argument (field or property).
/// </summary>
/// <param name="isField">True to encode a field, false to encode a property.</param>
/// <param name="type">Called first, to encode the type of the argument.</param>
/// <param name="name">Called second, to encode the name of the field or property.</param>
/// <param name="literal">Called third, to encode the literal value of the argument.</param>
/// <exception cref="ArgumentNullException"><paramref name="type"/>, <paramref name="name"/> or <paramref name="literal"/> is null.</exception>
public void AddArgument(bool isField, Action<NamedArgumentTypeEncoder> type, Action<NameEncoder> name, Action<LiteralEncoder> literal)
{
if (type == null) Throw.ArgumentNull(nameof(type));
if (name == null) Throw.ArgumentNull(nameof(name));
if (literal == null) Throw.ArgumentNull(nameof(literal));
NamedArgumentTypeEncoder typeEncoder;
NameEncoder nameEncoder;
LiteralEncoder literalEncoder;
AddArgument(isField, out typeEncoder, out nameEncoder, out literalEncoder);
type(typeEncoder);
name(nameEncoder);
literal(literalEncoder);
}
}
public struct NamedArgumentTypeEncoder
{
public BlobBuilder Builder { get; }
public NamedArgumentTypeEncoder(BlobBuilder builder)
{
Builder = builder;
}
public CustomAttributeElementTypeEncoder ScalarType()
{
return new CustomAttributeElementTypeEncoder(Builder);
}
public void Object()
{
Builder.WriteByte((byte)SerializationTypeCode.TaggedObject);
}
public CustomAttributeArrayTypeEncoder SZArray()
{
return new CustomAttributeArrayTypeEncoder(Builder);
}
}
public struct CustomAttributeArrayTypeEncoder
{
public BlobBuilder Builder { get; }
public CustomAttributeArrayTypeEncoder(BlobBuilder builder)
{
Builder = builder;
}
public void ObjectArray()
{
Builder.WriteByte((byte)SerializationTypeCode.SZArray);
Builder.WriteByte((byte)SerializationTypeCode.TaggedObject);
}
public CustomAttributeElementTypeEncoder ElementType()
{
Builder.WriteByte((byte)SerializationTypeCode.SZArray);
return new CustomAttributeElementTypeEncoder(Builder);
}
}
public struct CustomAttributeElementTypeEncoder
{
public BlobBuilder Builder { get; }
public CustomAttributeElementTypeEncoder(BlobBuilder builder)
{
Builder = builder;
}
private void WriteTypeCode(SerializationTypeCode value)
{
Builder.WriteByte((byte)value);
}
public void Boolean() => WriteTypeCode(SerializationTypeCode.Boolean);
public void Char() => WriteTypeCode(SerializationTypeCode.Char);
public void SByte() => WriteTypeCode(SerializationTypeCode.SByte);
public void Byte() => WriteTypeCode(SerializationTypeCode.Byte);
public void Int16() => WriteTypeCode(SerializationTypeCode.Int16);
public void UInt16() => WriteTypeCode(SerializationTypeCode.UInt16);
public void Int32() => WriteTypeCode(SerializationTypeCode.Int32);
public void UInt32() => WriteTypeCode(SerializationTypeCode.UInt32);
public void Int64() => WriteTypeCode(SerializationTypeCode.Int64);
public void UInt64() => WriteTypeCode(SerializationTypeCode.UInt64);
public void Single() => WriteTypeCode(SerializationTypeCode.Single);
public void Double() => WriteTypeCode(SerializationTypeCode.Double);
public void String() => WriteTypeCode(SerializationTypeCode.String);
public void PrimitiveType(PrimitiveSerializationTypeCode type)
{
switch (type)
{
case PrimitiveSerializationTypeCode.Boolean:
case PrimitiveSerializationTypeCode.Byte:
case PrimitiveSerializationTypeCode.SByte:
case PrimitiveSerializationTypeCode.Char:
case PrimitiveSerializationTypeCode.Int16:
case PrimitiveSerializationTypeCode.UInt16:
case PrimitiveSerializationTypeCode.Int32:
case PrimitiveSerializationTypeCode.UInt32:
case PrimitiveSerializationTypeCode.Int64:
case PrimitiveSerializationTypeCode.UInt64:
case PrimitiveSerializationTypeCode.Single:
case PrimitiveSerializationTypeCode.Double:
case PrimitiveSerializationTypeCode.String:
WriteTypeCode((SerializationTypeCode)type);
return;
default:
Throw.ArgumentOutOfRange(nameof(type));
return;
}
}
public void SystemType()
{
WriteTypeCode(SerializationTypeCode.Type);
}
public void Enum(string enumTypeName)
{
if (enumTypeName == null) Throw.ArgumentNull(nameof(enumTypeName));
if (enumTypeName.Length == 0) Throw.ArgumentEmptyString(nameof(enumTypeName));
WriteTypeCode(SerializationTypeCode.Enum);
Builder.WriteSerializedString(enumTypeName);
}
}
public struct SignatureTypeEncoder
{
public BlobBuilder Builder { get; }
public SignatureTypeEncoder(BlobBuilder builder)
{
Builder = builder;
}
private void WriteTypeCode(SignatureTypeCode value)
{
Builder.WriteByte((byte)value);
}
private void ClassOrValue(bool isValueType)
{
Builder.WriteByte(isValueType ? (byte)SignatureTypeKind.ValueType : (byte)SignatureTypeKind.Class);
}
public void Boolean() => WriteTypeCode(SignatureTypeCode.Boolean);
public void Char() => WriteTypeCode(SignatureTypeCode.Char);
public void SByte() => WriteTypeCode(SignatureTypeCode.SByte);
public void Byte() => WriteTypeCode(SignatureTypeCode.Byte);
public void Int16() => WriteTypeCode(SignatureTypeCode.Int16);
public void UInt16() => WriteTypeCode(SignatureTypeCode.UInt16);
public void Int32() => WriteTypeCode(SignatureTypeCode.Int32);
public void UInt32() => WriteTypeCode(SignatureTypeCode.UInt32);
public void Int64() => WriteTypeCode(SignatureTypeCode.Int64);
public void UInt64() => WriteTypeCode(SignatureTypeCode.UInt64);
public void Single() => WriteTypeCode(SignatureTypeCode.Single);
public void Double() => WriteTypeCode(SignatureTypeCode.Double);
public void String() => WriteTypeCode(SignatureTypeCode.String);
public void IntPtr() => WriteTypeCode(SignatureTypeCode.IntPtr);
public void UIntPtr() => WriteTypeCode(SignatureTypeCode.UIntPtr);
public void Object() => WriteTypeCode(SignatureTypeCode.Object);
/// <summary>
/// Writes primitive type code.
/// </summary>
/// <param name="type">Any primitive type code except for <see cref="PrimitiveTypeCode.TypedReference"/> and <see cref="PrimitiveTypeCode.Void"/>.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="type"/> is not valid in this context.</exception>
public void PrimitiveType(PrimitiveTypeCode type)
{
switch (type)
{
case PrimitiveTypeCode.Boolean:
case PrimitiveTypeCode.Byte:
case PrimitiveTypeCode.SByte:
case PrimitiveTypeCode.Char:
case PrimitiveTypeCode.Int16:
case PrimitiveTypeCode.UInt16:
case PrimitiveTypeCode.Int32:
case PrimitiveTypeCode.UInt32:
case PrimitiveTypeCode.Int64:
case PrimitiveTypeCode.UInt64:
case PrimitiveTypeCode.Single:
case PrimitiveTypeCode.Double:
case PrimitiveTypeCode.IntPtr:
case PrimitiveTypeCode.UIntPtr:
case PrimitiveTypeCode.String:
case PrimitiveTypeCode.Object:
Builder.WriteByte((byte)type);
return;
case PrimitiveTypeCode.TypedReference:
case PrimitiveTypeCode.Void:
default:
Throw.ArgumentOutOfRange(nameof(type));
return;
}
}
/// <summary>
/// Encodes an array type.
/// Returns a pair of encoders that must be used in the order they appear in the parameter list.
/// </summary>
/// <param name="elementType">Use first, to encode the type of the element.</param>
/// <param name="arrayShape">Use second, to encode the shape of the array.</param>
public void Array(out SignatureTypeEncoder elementType, out ArrayShapeEncoder arrayShape)
{
Builder.WriteByte((byte)SignatureTypeCode.Array);
elementType = this;
arrayShape = new ArrayShapeEncoder(Builder);
}
/// <summary>
/// Encodes an array type.
/// </summary>
/// <param name="elementType">Called first, to encode the type of the element.</param>
/// <param name="arrayShape">Called second, to encode the shape of the array.</param>
/// <exception cref="ArgumentNullException"><paramref name="elementType"/> or <paramref name="arrayShape"/> is null.</exception>
public void Array(Action<SignatureTypeEncoder> elementType, Action<ArrayShapeEncoder> arrayShape)
{
if (elementType == null) Throw.ArgumentNull(nameof(elementType));
if (arrayShape == null) Throw.ArgumentNull(nameof(arrayShape));
SignatureTypeEncoder elementTypeEncoder;
ArrayShapeEncoder arrayShapeEncoder;
Array(out elementTypeEncoder, out arrayShapeEncoder);
elementType(elementTypeEncoder);
arrayShape(arrayShapeEncoder);
}
/// <summary>
/// Encodes a reference to a type.
/// </summary>
/// <param name="type"><see cref="TypeDefinitionHandle"/> or <see cref="TypeReferenceHandle"/>.</param>
/// <param name="isValueType">True to mark the type as value type, false to mark it as a reference type in the signature.</param>
/// <exception cref="ArgumentException"><paramref name="type"/> doesn't have the expected handle kind.</exception>
public void Type(EntityHandle type, bool isValueType)
{
// Get the coded index before we start writing anything (might throw argument exception):
// Note: We don't allow TypeSpec as per https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/Ecma-335-Issues.md#proposed-specification-change
int codedIndex = CodedIndex.TypeDefOrRef(type);
ClassOrValue(isValueType);
Builder.WriteCompressedInteger(codedIndex);
}
/// <summary>
/// Starts a function pointer signature.
/// </summary>
/// <param name="convention">Calling convention.</param>
/// <param name="attributes">Function pointer attributes.</param>
/// <param name="genericParameterCount">Generic parameter count.</param>
/// <exception cref="ArgumentException"><paramref name="attributes"/> is invalid.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="genericParameterCount"/> is not in range [0, 0xffff].</exception>
public MethodSignatureEncoder FunctionPointer(
SignatureCallingConvention convention = SignatureCallingConvention.Default,
FunctionPointerAttributes attributes = FunctionPointerAttributes.None,
int genericParameterCount = 0)
{
// Spec:
// The EXPLICITTHIS (0x40) bit can be set only in signatures for function pointers.
// If EXPLICITTHIS (0x40) in the signature is set, then HASTHIS (0x20) shall also be set.
if (attributes != FunctionPointerAttributes.None &&
attributes != FunctionPointerAttributes.HasThis &&
attributes != FunctionPointerAttributes.HasExplicitThis)
{
throw new ArgumentException(SR.InvalidSignature, nameof(attributes));
}
if (unchecked((uint)genericParameterCount) > ushort.MaxValue)
{
Throw.ArgumentOutOfRange(nameof(genericParameterCount));
}
Builder.WriteByte((byte)SignatureTypeCode.FunctionPointer);
Builder.WriteByte(new SignatureHeader(SignatureKind.Method, convention, (SignatureAttributes)attributes).RawValue);
if (genericParameterCount != 0)
{
Builder.WriteCompressedInteger(genericParameterCount);
}
return new MethodSignatureEncoder(Builder, hasVarArgs: convention == SignatureCallingConvention.VarArgs);
}
/// <summary>
/// Starts a generic instantiation signature.
/// </summary>
/// <param name="genericType"><see cref="TypeDefinitionHandle"/> or <see cref="TypeReferenceHandle"/>.</param>
/// <param name="genericArgumentCount">Generic argument count.</param>
/// <param name="isValueType">True to mark the type as value type, false to mark it as a reference type in the signature.</param>
/// <exception cref="ArgumentException"><paramref name="genericType"/> doesn't have the expected handle kind.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="genericArgumentCount"/> is not in range [1, 0xffff].</exception>
public GenericTypeArgumentsEncoder GenericInstantiation(EntityHandle genericType, int genericArgumentCount, bool isValueType)
{
if (unchecked((uint)(genericArgumentCount - 1)) > ushort.MaxValue - 1)
{
Throw.ArgumentOutOfRange(nameof(genericArgumentCount));
}
// Get the coded index before we start writing anything (might throw argument exception):
// Note: We don't allow TypeSpec as per https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/Ecma-335-Issues.md#proposed-specification-change
int codedIndex = CodedIndex.TypeDefOrRef(genericType);
Builder.WriteByte((byte)SignatureTypeCode.GenericTypeInstance);
ClassOrValue(isValueType);
Builder.WriteCompressedInteger(codedIndex);
Builder.WriteCompressedInteger(genericArgumentCount);
return new GenericTypeArgumentsEncoder(Builder);
}
/// <summary>
/// Encodes a reference to type parameter of a containing generic method.
/// </summary>
/// <param name="parameterIndex">Parameter index.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="parameterIndex"/> is not in range [0, 0xffff].</exception>
public void GenericMethodTypeParameter(int parameterIndex)
{
if (unchecked((uint)parameterIndex) > ushort.MaxValue)
{
Throw.ArgumentOutOfRange(nameof(parameterIndex));
}
Builder.WriteByte((byte)SignatureTypeCode.GenericMethodParameter);
Builder.WriteCompressedInteger(parameterIndex);
}
/// <summary>
/// Encodes a reference to type parameter of a containing generic type.
/// </summary>
/// <param name="parameterIndex">Parameter index.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="parameterIndex"/> is not in range [0, 0xffff].</exception>
public void GenericTypeParameter(int parameterIndex)
{
if (unchecked((uint)parameterIndex) > ushort.MaxValue)
{
Throw.ArgumentOutOfRange(nameof(parameterIndex));
}
Builder.WriteByte((byte)SignatureTypeCode.GenericTypeParameter);
Builder.WriteCompressedInteger(parameterIndex);
}
/// <summary>
/// Starts pointer signature.
/// </summary>
public SignatureTypeEncoder Pointer()
{
Builder.WriteByte((byte)SignatureTypeCode.Pointer);
return this;
}
/// <summary>
/// Encodes <code>void*</code>.
/// </summary>
public void VoidPointer()
{
Builder.WriteByte((byte)SignatureTypeCode.Pointer);
Builder.WriteByte((byte)SignatureTypeCode.Void);
}
/// <summary>
/// Starts SZ array (vector) signature.
/// </summary>
public SignatureTypeEncoder SZArray()
{
Builder.WriteByte((byte)SignatureTypeCode.SZArray);
return this;
}
/// <summary>
/// Starts a signature of a type with custom modifiers.
/// </summary>
public CustomModifiersEncoder CustomModifiers()
{
return new CustomModifiersEncoder(Builder);
}
}
public struct CustomModifiersEncoder
{
public BlobBuilder Builder { get; }
public CustomModifiersEncoder(BlobBuilder builder)
{
Builder = builder;
}
/// <summary>
/// Encodes a custom modifier.
/// </summary>
/// <param name="type"><see cref="TypeDefinitionHandle"/>, <see cref="TypeReferenceHandle"/> or <see cref="TypeSpecificationHandle"/>.</param>
/// <param name="isOptional">Is optional modifier.</param>
/// <returns>Encoder of subsequent modifiers.</returns>
/// <exception cref="ArgumentException"><paramref name="type"/> is nil or of an unexpected kind.</exception>
public CustomModifiersEncoder AddModifier(EntityHandle type, bool isOptional)
{
if (type.IsNil)
{
Throw.InvalidArgument_Handle(nameof(type));
}
if (isOptional)
{
Builder.WriteByte((byte)SignatureTypeCode.OptionalModifier);
}
else
{
Builder.WriteByte((byte)SignatureTypeCode.RequiredModifier);
}
Builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(type));
return this;
}
}
public struct ArrayShapeEncoder
{
public BlobBuilder Builder { get; }
public ArrayShapeEncoder(BlobBuilder builder)
{
Builder = builder;
}
/// <summary>
/// Encodes array shape.
/// </summary>
/// <param name="rank">The number of dimensions in the array (shall be 1 or more).</param>
/// <param name="sizes">
/// Dimension sizes. The array may be shorter than <paramref name="rank"/> but not longer.
/// </param>
/// <param name="lowerBounds">
/// Dimension lower bounds, or <c>default(<see cref="ImmutableArray{Int32}"/>)</c> to set all <paramref name="rank"/> lower bounds to 0.
/// The array may be shorter than <paramref name="rank"/> but not longer.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="rank"/> is outside of range [1, 0xffff],
/// smaller than <paramref name="sizes"/>.Length, or
/// smaller than <paramref name="lowerBounds"/>.Length.
/// </exception>
/// <exception cref="ArgumentNullException"><paramref name="sizes"/> is null.</exception>
public void Shape(int rank, ImmutableArray<int> sizes, ImmutableArray<int> lowerBounds)
{
// The specification doesn't impose a limit on the max number of array dimensions.
// The CLR supports <64. More than 0xffff is causing crashes in various tools (ildasm).
if (unchecked((uint)(rank - 1)) > ushort.MaxValue - 1)
{
Throw.ArgumentOutOfRange(nameof(rank));
}
if (sizes.IsDefault)
{
Throw.ArgumentNull(nameof(sizes));
}
// rank
Builder.WriteCompressedInteger(rank);
// sizes
if (sizes.Length > rank)
{
Throw.ArgumentOutOfRange(nameof(rank));
}
Builder.WriteCompressedInteger(sizes.Length);
foreach (int size in sizes)
{
Builder.WriteCompressedInteger(size);
}
// lower bounds
if (lowerBounds.IsDefault) // TODO: remove -- update Roslyn
{
Builder.WriteCompressedInteger(rank);
for (int i = 0; i < rank; i++)
{
Builder.WriteCompressedSignedInteger(0);
}
}
else
{
if (lowerBounds.Length > rank)
{
Throw.ArgumentOutOfRange(nameof(rank));
}
Builder.WriteCompressedInteger(lowerBounds.Length);
foreach (int lowerBound in lowerBounds)
{
Builder.WriteCompressedSignedInteger(lowerBound);
}
}
}
}
public struct ReturnTypeEncoder
{
public BlobBuilder Builder { get; }
public ReturnTypeEncoder(BlobBuilder builder)
{
Builder = builder;
}
public CustomModifiersEncoder CustomModifiers()
{
return new CustomModifiersEncoder(Builder);
}
public SignatureTypeEncoder Type(bool isByRef = false)
{
if (isByRef)
{
Builder.WriteByte((byte)SignatureTypeCode.ByReference);
}
return new SignatureTypeEncoder(Builder);
}
public void TypedReference()
{
Builder.WriteByte((byte)SignatureTypeCode.TypedReference);
}
public void Void()
{
Builder.WriteByte((byte)SignatureTypeCode.Void);
}
}
public struct ParametersEncoder
{
public BlobBuilder Builder { get; }
public bool HasVarArgs { get; }
public ParametersEncoder(BlobBuilder builder, bool hasVarArgs = false)
{
Builder = builder;
HasVarArgs = hasVarArgs;
}
public ParameterTypeEncoder AddParameter()
{
return new ParameterTypeEncoder(Builder);
}
public ParametersEncoder StartVarArgs()
{
if (!HasVarArgs)
{
Throw.SignatureNotVarArg();
}
Builder.WriteByte((byte)SignatureTypeCode.Sentinel);
return new ParametersEncoder(Builder, hasVarArgs: false);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Logging;
using Microsoft.VisualStudio.ComponentModelHost;
namespace Microsoft.PythonTools.EnvironmentsList {
public partial class ToolWindow : UserControl {
internal readonly ObservableCollection<EnvironmentView> _environments;
internal readonly ObservableCollection<object> _extensions;
private readonly CollectionViewSource _environmentsView, _extensionsView;
private IInterpreterRegistryService _interpreters;
private IInterpreterOptionsService _options;
private IServiceProvider _site;
public static readonly RoutedCommand UnhandledException = new RoutedCommand();
private static readonly object[] EmptyObjectArray = new object[0];
public ToolWindow() {
_environments = new ObservableCollection<EnvironmentView>();
_extensions = new ObservableCollection<object>();
_environmentsView = new CollectionViewSource { Source = _environments };
_extensionsView = new CollectionViewSource { Source = _extensions };
_extensionsView.SortDescriptions.Add(new SortDescription("SortPriority", ListSortDirection.Ascending));
_extensionsView.SortDescriptions.Add(new SortDescription("LocalizedDisplayName", ListSortDirection.Ascending));
_environmentsView.View.CurrentChanged += EnvironmentsView_CurrentChanged;
DataContext = this;
InitializeComponent();
SizeChanged += ToolWindow_SizeChanged;
}
private void EnvironmentsView_CurrentChanged(object sender, EventArgs e) {
var item = _environmentsView.View.CurrentItem as EnvironmentView;
if (item == null) {
lock (_extensions) {
_extensions.Clear();
}
return;
}
OnViewSelected(item);
var oldSelect = _extensionsView.View.CurrentItem?.GetType();
var newSelect = oldSelect == null ? null :
item.Extensions?.FirstOrDefault(ext => ext != null && ext.GetType().IsEquivalentTo(oldSelect));
lock (_extensions) {
_extensions.Clear();
foreach (var ext in item.Extensions.MaybeEnumerate()) {
_extensions.Add(ext);
}
if (newSelect != null) {
_extensionsView.View.MoveCurrentTo(newSelect);
} else {
_extensionsView.View.MoveCurrentToFirst();
}
}
}
public IServiceProvider Site {
get {
return _site;
}
set {
_site = value;
if (value != null) {
var compModel = _site.GetService(typeof(SComponentModel)) as IComponentModel;
InitializeEnvironments(compModel.GetService<IInterpreterRegistryService>(), compModel.GetService<IInterpreterOptionsService>());
} else {
InitializeEnvironments(null, null);
}
}
}
internal IPythonToolsLogger TelemetryLogger { get; set; }
internal static async void SendUnhandledException(UIElement element, ExceptionDispatchInfo edi) {
try {
await element.Dispatcher.InvokeAsync(() => {
UnhandledException.Execute(edi, element);
});
} catch (InvalidOperationException) {
UnhandledException.Execute(edi, element);
}
}
void ToolWindow_SizeChanged(object sender, SizeChangedEventArgs e) {
if (!e.WidthChanged) {
return;
}
UpdateLayout(e.NewSize.Width, e.NewSize.Height);
}
void UpdateLayout(double width, double height) {
if (double.IsNaN(width) || double.IsNaN(height)) {
return;
}
if (width < 500) {
SwitchToVerticalLayout();
} else if (width >= 600) {
SwitchToHorizontalLayout();
} else if (VerticalLayout.Visibility != Visibility.Visible) {
SwitchToVerticalLayout();
}
}
void SwitchToHorizontalLayout() {
if (HorizontalLayout.Visibility == Visibility.Visible) {
return;
}
VerticalLayout.Visibility = Visibility.Collapsed;
BindingOperations.ClearBinding(ContentView_Vertical, ContentControl.ContentProperty);
BindingOperations.SetBinding(ContentView_Horizontal, ContentControl.ContentProperty, new Binding {
Path = new PropertyPath("CurrentItem.WpfObject"),
Source = Extensions
});
HorizontalLayout.Visibility = Visibility.Visible;
UpdateLayout();
}
void SwitchToVerticalLayout() {
if (VerticalLayout.Visibility == Visibility.Visible) {
return;
}
HorizontalLayout.Visibility = Visibility.Collapsed;
BindingOperations.ClearBinding(ContentView_Horizontal, ContentControl.ContentProperty);
BindingOperations.SetBinding(ContentView_Vertical, ContentControl.ContentProperty, new Binding {
Path = new PropertyPath("CurrentItem.WpfObject"),
Source = Extensions
});
VerticalLayout.Visibility = Visibility.Visible;
UpdateLayout();
}
public ICollectionView Environments => _environmentsView.View;
public ICollectionView Extensions => _extensionsView.View;
private void MakeGlobalDefault_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
var view = e.Parameter as EnvironmentView;
e.CanExecute = view != null && !view.IsDefault && view.Factory.CanBeDefault();
}
private void MakeGlobalDefault_Executed(object sender, ExecutedRoutedEventArgs e) {
_options.DefaultInterpreter = ((EnvironmentView)e.Parameter).Factory;
}
private void UpdateEnvironments(string select = null) {
if (_options == null) {
lock (_environments) {
_environments.Clear();
}
return;
}
lock (_environments) {
if (select == null) {
var selectView = _environmentsView.View.CurrentItem as EnvironmentView;
select = selectView?.Configuration?.Id;
}
// We allow up to three retries at this process to handle race
// conditions where an interpreter disappears between the
// point where we enumerate known configuration IDs and convert
// them into a view. The first time that happens, we insert a
// stub entry, and on the subsequent pass it will be removed.
bool anyMissing = true;
for (int retries = 3; retries > 0 && anyMissing; --retries) {
var configs = _interpreters.Configurations.Where(f => f.IsUIVisible()).ToList();
anyMissing = false;
_environments.Merge(
configs,
ev => ev.Configuration,
c => c,
c => {
var fact = _interpreters.FindInterpreter(c.Id);
EnvironmentView view = null;
try {
if (fact != null) {
view = new EnvironmentView(_options, _interpreters, fact, null);
}
} catch (ArgumentException) {
}
if (view == null) {
view = EnvironmentView.CreateMissingEnvironmentView(c.Id + "+Missing", c.Description);
anyMissing = true;
}
OnViewCreated(view);
return view;
},
InterpreterConfigurationComparer.Instance,
InterpreterConfigurationComparer.Instance
);
}
if (select != null) {
var selectView = _environments.FirstOrDefault(v => v.Factory != null &&
v.Factory.Configuration.Id == select);
if (selectView == null) {
select = null;
} else {
_environmentsView.View.MoveCurrentTo(selectView);
}
}
if (select == null) {
var defaultView = _environments.FirstOrDefault(v => v.IsDefault);
if (defaultView != null && _environmentsView.View.CurrentItem == null) {
_environmentsView.View.MoveCurrentTo(defaultView);
}
}
}
}
private void FirstUpdateEnvironments() {
UpdateEnvironments();
UpdateLayout();
UpdateLayout(ActualWidth, ActualHeight);
}
private void OnViewCreated(EnvironmentView view) {
ViewCreated?.Invoke(this, new EnvironmentViewEventArgs(view));
}
internal void OnViewSelected(EnvironmentView view) {
ViewSelected?.Invoke(this, new EnvironmentViewEventArgs(view));
}
public event EventHandler<EnvironmentViewEventArgs> ViewCreated;
public event EventHandler<EnvironmentViewEventArgs> ViewSelected;
internal IInterpreterOptionsService OptionsService => _options;
public void InitializeEnvironments(IInterpreterRegistryService interpreters, IInterpreterOptionsService options, bool synchronous = false) {
if (_interpreters != null) {
_interpreters.InterpretersChanged -= Service_InterpretersChanged;
}
_interpreters = interpreters;
if (_interpreters != null) {
_interpreters.InterpretersChanged += Service_InterpretersChanged;
}
if (_options != null) {
_options.DefaultInterpreterChanged -= Service_DefaultInterpreterChanged;
}
_options = options;
if (_options != null) {
_options.DefaultInterpreterChanged += Service_DefaultInterpreterChanged;
}
if (_interpreters != null && _options != null) {
if (synchronous) {
Dispatcher.Invoke(FirstUpdateEnvironments);
} else {
Dispatcher.InvokeAsync(FirstUpdateEnvironments).Task.DoNotWait();
}
}
}
private async void Service_InterpretersChanged(object sender, EventArgs e) {
try {
await Dispatcher.InvokeAsync(() => UpdateEnvironments());
} catch (OperationCanceledException) {
}
}
private async void Service_DefaultInterpreterChanged(object sender, EventArgs e) {
var newDefault = _options.DefaultInterpreter;
try {
await Dispatcher.InvokeAsync(() => {
lock (_environments) {
foreach (var view in _environments) {
if (view.Factory == newDefault) {
view.IsDefault = true;
} else if (view.IsDefault == true) {
view.IsDefault = false;
}
}
}
});
} catch (OperationCanceledException) {
}
}
private void ConfigurableViewAdded_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = e.Parameter is string;
e.Handled = true;
}
private async void ConfigurableViewAdded_Executed(object sender, ExecutedRoutedEventArgs e) {
var id = (string)e.Parameter;
e.Handled = true;
for (int retries = 10; retries > 0; --retries) {
var env = _environments.FirstOrDefault(ev => ev.Factory?.Configuration?.Id == id);
if (env != null) {
Environments.MoveCurrentTo(env);
return;
}
await Task.Delay(50).ConfigureAwait(continueOnCapturedContext: true);
}
Debug.Fail("Failed to switch to added environment");
}
private void ConfigureEnvironment_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
e.CanExecute = (e.Parameter as EnvironmentView)?.IsConfigurable ?? false;
e.Handled = true;
}
private void ConfigureEnvironment_Executed(object sender, ExecutedRoutedEventArgs e) {
e.Handled = true;
var env = (EnvironmentView)e.Parameter;
if (Environments.CurrentItem != env) {
Environments.MoveCurrentTo(env);
if (Environments.CurrentItem != env) {
return;
}
}
var ext = env.Extensions.OfType<ConfigurationExtensionProvider>().FirstOrDefault();
if (ext != null) {
Extensions.MoveCurrentTo(ext);
}
}
private void EnvironmentsList_SelectionChanged(object sender, SelectionChangedEventArgs e) {
var list = sender as ListBox;
if (list != null && e.AddedItems.Count > 0) {
list.ScrollIntoView(e.AddedItems[0]);
e.Handled = true;
}
}
private void OnlineHelpListItem_GotFocus(object sender, RoutedEventArgs e) {
for (var child = sender as DependencyObject;
child != null;
child = VisualTreeHelper.GetParent(child)
) {
var lbi = child as ListBoxItem;
if (lbi != null) {
lbi.IsSelected = true;
return;
}
}
}
private class InterpreterConfigurationComparer : IEqualityComparer<InterpreterConfiguration>, IComparer<InterpreterConfiguration> {
public static readonly InterpreterConfigurationComparer Instance = new InterpreterConfigurationComparer();
public bool Equals(InterpreterConfiguration x, InterpreterConfiguration y) => x == y;
public int GetHashCode(InterpreterConfiguration obj) => obj.GetHashCode();
public int Compare(InterpreterConfiguration x, InterpreterConfiguration y) {
if (object.ReferenceEquals(x, y)) {
return 0;
}
if (x == null) {
return y == null ? 0 : 1;
} else if (y == null) {
return -1;
}
int result = StringComparer.CurrentCultureIgnoreCase.Compare(
x.Description,
y.Description
);
if (result == 0) {
result = StringComparer.Ordinal.Compare(
x.Id,
y.Id
);
}
return result;
}
}
}
/// <summary>
/// Contains the newly created view.
/// </summary>
public class EnvironmentViewEventArgs : EventArgs {
public EnvironmentViewEventArgs(EnvironmentView view) {
View = view;
}
public EnvironmentView View { get; private set; }
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using FileHelpers.Helpers;
namespace FileHelpers
{
/// <summary>
/// Record read from the file for processing
/// </summary>
/// <remarks>
/// The data inside the LIneInfo may be reset during processing,
/// for example on read next line. Do not rely on this class
/// containing all data from a record for all time. It is designed
/// to read data sequentially.
/// </remarks>
[DebuggerDisplay("{DebuggerDisplayStr()}")]
internal sealed class LineInfo
{
//public static readonly LineInfo Empty = new LineInfo(string.Empty);
#region " Constructor "
//static readonly char[] mEmptyChars = new char[] {};
/// <summary>
/// Create a line info with data from line
/// </summary>
/// <param name="line"></param>
public LineInfo(string line)
{
mReader = null;
mLineStr = line;
//mLine = line == null ? mEmptyChars : line.ToCharArray();
mCurrentPos = 0;
}
#endregion
/// <summary>
/// Return part of line, Substring
/// </summary>
/// <param name="from">Start position (zero offset)</param>
/// <param name="count">Number of characters to extract</param>
/// <returns>substring from line</returns>
public string Substring(int from, int count)
{
return mLineStr.Substring(from, count);
}
#region " Internal Fields "
//internal string mLine;
//internal char[] mLine;
/// <summary>
/// Record read from reader
/// </summary>
internal string mLineStr;
/// <summary>
/// Reader that got the string
/// </summary>
internal ForwardReader mReader;
/// <summary>
/// Where we are processing records from
/// </summary>
internal int mCurrentPos;
/// <summary>
/// List of whitespace characters that we want to skip
/// </summary>
internal static readonly char[] WhitespaceChars = new char[] {
'\t', '\n', '\v', '\f', '\r', ' ', '\x00a0', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005',
'\u2006', '\u2007', '\u2008',
'\u2009', '\u200a', '\u200b', '\u3000', '\ufeff'
};
#endregion
/// <summary>
/// Debugger display string
/// </summary>
/// <returns></returns>
private string DebuggerDisplayStr()
{
if (IsEOL())
return "<EOL>";
else
return CurrentString;
}
/// <summary>
/// Extract a single field from the system
/// </summary>
public string CurrentString
{
get { return mLineStr.Substring(mCurrentPos, mLineStr.Length - mCurrentPos); }
}
/// <summary>
/// If we have extracted more that the field contains.
/// </summary>
/// <returns>True if end of line</returns>
public bool IsEOL()
{
return mCurrentPos >= mLineStr.Length;
}
/// <summary>
/// Amount of data left to process
/// </summary>
public int CurrentLength
{
get { return mLineStr.Length - mCurrentPos; }
}
/// <summary>
/// Is there only whitespace left in the record?
/// </summary>
/// <returns>True if only whitespace</returns>
public bool EmptyFromPos()
{
// Check if the chars at pos or right are empty ones
int length = mLineStr.Length;
int pos = mCurrentPos;
while (pos < length &&
Array.BinarySearch(WhitespaceChars, mLineStr[pos]) >= 0)
pos++;
return pos >= length;
}
/// <summary>
/// delete leading whitespace from record
/// </summary>
public void TrimStart()
{
TrimStartSorted(WhitespaceChars);
}
/// <summary>
/// Delete any of these characters from beginning of the record
/// </summary>
/// <param name="toTrim"></param>
public void TrimStart(char[] toTrim)
{
Array.Sort(toTrim);
TrimStartSorted(toTrim);
}
/// <summary>
/// Move the record pointer along skipping these characters
/// </summary>
/// <param name="toTrim">Sorted array of character to skip</param>
private void TrimStartSorted(char[] toTrim)
{
// Move the pointer to the first non to Trim char
int length = mLineStr.Length;
while (mCurrentPos < length &&
Array.BinarySearch(toTrim, mLineStr[mCurrentPos]) >= 0)
mCurrentPos++;
}
public bool StartsWith(string str)
{
// Returns true if the string begin with str
if (mCurrentPos >= mLineStr.Length)
return false;
else {
return
mCompare.Compare(mLineStr,
mCurrentPos,
str.Length,
str,
0,
str.Length,
CompareOptions.OrdinalIgnoreCase) == 0;
}
}
/// <summary>
/// Check that the record begins with a value ignoring whitespace
/// </summary>
/// <param name="str">String to check for</param>
/// <returns>True if record begins with</returns>
public bool StartsWithTrim(string str)
{
int length = mLineStr.Length;
int pos = mCurrentPos;
while (pos < length &&
Array.BinarySearch(WhitespaceChars, mLineStr[pos]) >= 0)
pos++;
return mCompare.Compare(mLineStr, pos, str, 0, CompareOptions.OrdinalIgnoreCase) == 0;
}
/// <summary>
/// get The next line from the system and reset the line pointer to zero
/// </summary>
public void ReadNextLine()
{
mLineStr = mReader.ReadNextLine();
//mLine = mLineStr.ToCharArray();
mCurrentPos = 0;
}
private static readonly CompareInfo mCompare = StringHelper.CreateComparer();
/// <summary>
/// Find the location of the next string in record
/// </summary>
/// <param name="foundThis">String we are looking for</param>
/// <returns>Position of the next one</returns>
public int IndexOf(string foundThis)
{
// Bad performance with custom IndexOf
// if (foundThis.Length == 1)
// {
// char delimiter = foundThis[0];
// int pos = mCurrentPos;
// int length = mLine.Length;
//
// while (pos < length)
// {
// if (mLine[pos] == delimiter)
// return pos;
//
// pos++;
// }
// return -1;
// }
// else
// if (mLineStr == null)
// return -1;
// else
return mCompare.IndexOf(mLineStr, foundThis, mCurrentPos, CompareOptions.Ordinal);
}
/// <summary>
/// Reset the string back to the original line and reset the line pointer
/// </summary>
/// <remarks>If the input is multi line, this will read next record and remove the original data</remarks>
/// <param name="line">Line to use</param>
internal void ReLoad(string line)
{
//mLine = line == null ? mEmptyChars : line.ToCharArray();
mLineStr = line;
mCurrentPos = 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Marten.Linq.SoftDeletes;
using Marten.Testing.Documents;
using Marten.Testing.Harness;
using Marten.Util;
using Shouldly;
using Xunit;
namespace Marten.Testing.Acceptance
{
public class SoftDeletedFixture: StoreFixture
{
public SoftDeletedFixture() : base("softdelete")
{
Options.Schema.For<User>().SoftDeletedWithIndex();
Options.Schema.For<File>().SoftDeleted();
Options.Schema.For<User>()
.SoftDeleted()
.AddSubClass<AdminUser>()
.AddSubClass<SuperUser>();
}
}
public class soft_deletes: StoreContext<SoftDeletedFixture>, IClassFixture<SoftDeletedFixture>
{
public soft_deletes(SoftDeletedFixture fixture): base(fixture)
{
theStore.Advanced.Clean.DeleteAllDocuments();
}
[Fact]
public void initial_state_of_deleted_columns()
{
using (var session = theStore.OpenSession())
{
var user = new User();
session.Store(user);
session.SaveChanges();
userIsNotMarkedAsDeleted(session, user.Id);
}
}
private static void userIsNotMarkedAsDeleted(IDocumentSession session, Guid userId)
{
var cmd = session.Connection.CreateCommand()
.Sql("select mt_deleted, mt_deleted_at from softdelete.mt_doc_user where id = :id")
.With("id", userId);
using (var reader = cmd.ExecuteReader())
{
reader.Read();
reader.GetFieldValue<bool>(0).ShouldBeFalse();
reader.IsDBNull(1).ShouldBeTrue();
}
}
[Fact]
public void soft_delete_a_document_row_state()
{
using (var session = theStore.OpenSession())
{
var user = new User();
session.Store(user);
session.SaveChanges();
session.Delete(user);
session.SaveChanges();
userIsMarkedAsDeleted(session, user.Id);
}
}
private static void userIsMarkedAsDeleted(IDocumentSession session, Guid userId)
{
var cmd = session.Connection.CreateCommand()
.Sql("select mt_deleted, mt_deleted_at from softdelete.mt_doc_user where id = :id")
.With("id", userId);
using (var reader = cmd.ExecuteReader())
{
reader.Read();
reader.GetFieldValue<bool>(0).ShouldBeTrue();
reader.IsDBNull(1).ShouldBeFalse();
}
}
[Fact]
public void soft_delete_a_document_by_where_row_state()
{
var user1 = new User { UserName = "foo" };
var user2 = new User { UserName = "bar" };
var user3 = new User { UserName = "baz" };
using (var session = theStore.OpenSession())
{
session.Store(user1, user2, user3);
session.SaveChanges();
session.DeleteWhere<User>(x => x.UserName.StartsWith("b"));
session.SaveChanges();
userIsNotMarkedAsDeleted(session, user1.Id);
userIsMarkedAsDeleted(session, user2.Id);
userIsMarkedAsDeleted(session, user3.Id);
}
}
// SAMPLE: query_soft_deleted_docs
[Fact]
public void query_soft_deleted_docs()
{
var user1 = new User { UserName = "foo" };
var user2 = new User { UserName = "bar" };
var user3 = new User { UserName = "baz" };
var user4 = new User { UserName = "jack" };
using (var session = theStore.OpenSession())
{
session.Store(user1, user2, user3, user4);
session.SaveChanges();
// Deleting 'bar' and 'baz'
session.DeleteWhere<User>(x => x.UserName.StartsWith("b"));
session.SaveChanges();
// no where clause, deleted docs should be filtered out
session.Query<User>().OrderBy(x => x.UserName).Select(x => x.UserName)
.ToList().ShouldHaveTheSameElementsAs("foo", "jack");
// with a where clause
session.Query<User>().Where(x => x.UserName != "jack")
.ToList().Single().UserName.ShouldBe("foo");
}
}
// ENDSAMPLE
// SAMPLE: query_maybe_soft_deleted_docs
[Fact]
public void query_maybe_soft_deleted_docs()
{
var user1 = new User { UserName = "foo" };
var user2 = new User { UserName = "bar" };
var user3 = new User { UserName = "baz" };
var user4 = new User { UserName = "jack" };
using (var session = theStore.OpenSession())
{
session.Store(user1, user2, user3, user4);
session.SaveChanges();
session.DeleteWhere<User>(x => x.UserName.StartsWith("b"));
session.SaveChanges();
// no where clause, all documents are returned
session.Query<User>().Where(x => x.MaybeDeleted()).OrderBy(x => x.UserName).Select(x => x.UserName)
.ToList().ShouldHaveTheSameElementsAs("bar", "baz", "foo", "jack");
// with a where clause, all documents are returned
session.Query<User>().Where(x => x.UserName != "jack" && x.MaybeDeleted())
.OrderBy(x => x.UserName)
.ToList()
.Select(x => x.UserName)
.ShouldHaveTheSameElementsAs("bar", "baz", "foo");
}
}
// ENDSAMPLE
// SAMPLE: query_is_soft_deleted_docs
[Fact]
public void query_is_soft_deleted_docs()
{
var user1 = new User { UserName = "foo" };
var user2 = new User { UserName = "bar" };
var user3 = new User { UserName = "baz" };
var user4 = new User { UserName = "jack" };
using (var session = theStore.OpenSession())
{
session.Store(user1, user2, user3, user4);
session.SaveChanges();
session.DeleteWhere<User>(x => x.UserName.StartsWith("b"));
session.SaveChanges();
// no where clause
session.Query<User>().Where(x => x.IsDeleted()).OrderBy(x => x.UserName).Select(x => x.UserName)
.ToList().ShouldHaveTheSameElementsAs("bar", "baz");
// with a where clause
session.Query<User>().Where(x => x.UserName != "baz" && x.IsDeleted())
.OrderBy(x => x.UserName)
.ToList()
.Select(x => x.UserName)
.Single().ShouldBe("bar");
}
}
// ENDSAMPLE
// SAMPLE: query_soft_deleted_since
[Fact]
public void query_is_soft_deleted_since_docs()
{
var user1 = new User { UserName = "foo" };
var user2 = new User { UserName = "bar" };
var user3 = new User { UserName = "baz" };
var user4 = new User { UserName = "jack" };
using (var session = theStore.OpenSession())
{
session.Store(user1, user2, user3, user4);
session.SaveChanges();
session.Delete(user3);
session.SaveChanges();
var epoch = session.MetadataFor(user3).DeletedAt;
session.Delete(user4);
session.SaveChanges();
session.Query<User>().Where(x => x.DeletedSince(epoch.Value)).Select(x => x.UserName)
.ToList().ShouldHaveTheSameElementsAs("jack");
}
}
// ENDSAMPLE
[Fact]
public void query_is_soft_deleted_before_docs()
{
var user1 = new User { UserName = "foo" };
var user2 = new User { UserName = "bar" };
var user3 = new User { UserName = "baz" };
var user4 = new User { UserName = "jack" };
using (var session = theStore.OpenSession())
{
session.Store(user1, user2, user3, user4);
session.SaveChanges();
session.Delete(user3);
session.SaveChanges();
session.Delete(user4);
session.SaveChanges();
var epoch = session.MetadataFor(user4).DeletedAt;
session.Query<User>().Where(x => x.DeletedBefore(epoch.Value)).Select(x => x.UserName)
.ToList().ShouldHaveTheSameElementsAs("baz");
}
}
[Fact]
public void top_level_of_hierarchy()
{
var user1 = new User { UserName = "foo" };
var user2 = new User { UserName = "bar" };
var user3 = new User { UserName = "baz" };
var user4 = new User { UserName = "jack" };
using (var session = theStore.OpenSession())
{
session.Store(user1, user2, user3, user4);
session.SaveChanges();
session.DeleteWhere<User>(x => x.UserName.StartsWith("b"));
session.SaveChanges();
// no where clause
session.Query<User>().OrderBy(x => x.UserName).Select(x => x.UserName)
.ToList().ShouldHaveTheSameElementsAs("foo", "jack");
// with a where clause
session.Query<User>().Where(x => x.UserName != "jack")
.ToList().Single().UserName.ShouldBe("foo");
}
}
[Fact]
public void sub_level_of_hierarchy()
{
var user1 = new SuperUser { UserName = "foo" };
var user2 = new SuperUser { UserName = "bar" };
var user3 = new SuperUser { UserName = "baz" };
var user4 = new SuperUser { UserName = "jack" };
var user5 = new AdminUser { UserName = "admin" };
using (var session = theStore.OpenSession())
{
session.StoreObjects(new User[] { user1, user2, user3, user4, user5 });
session.SaveChanges();
session.DeleteWhere<SuperUser>(x => x.UserName.StartsWith("b"));
session.SaveChanges();
// no where clause
session.Query<SuperUser>().OrderBy(x => x.UserName).Select(x => x.UserName)
.ToList().ShouldHaveTheSameElementsAs("foo", "jack");
// with a where clause
session.Query<SuperUser>().Where(x => x.UserName != "jack")
.ToList().Single().UserName.ShouldBe("foo");
}
}
[Fact]
public void sub_level_of_hierarchy_maybe_deleted()
{
var user1 = new SuperUser { UserName = "foo" };
var user2 = new SuperUser { UserName = "bar" };
var user3 = new SuperUser { UserName = "baz" };
var user4 = new SuperUser { UserName = "jack" };
var user5 = new AdminUser { UserName = "admin" };
using (var session = theStore.OpenSession())
{
session.StoreObjects(new User[] { user1, user2, user3, user4, user5 });
session.SaveChanges();
session.DeleteWhere<SuperUser>(x => x.UserName.StartsWith("b"));
session.SaveChanges();
// no where clause
session.Query<SuperUser>().Where(x => x.MaybeDeleted()).OrderBy(x => x.UserName).Select(x => x.UserName)
.ToList().ShouldHaveTheSameElementsAs("bar", "baz", "foo", "jack");
// with a where clause
session.Query<SuperUser>().Where(x => x.UserName != "jack" && x.MaybeDeleted())
.OrderBy(x => x.UserName)
.Select(x => x.UserName)
.ToList().ShouldHaveTheSameElementsAs("bar", "baz", "foo");
}
}
[Fact]
public void sub_level_of_hierarchy_is_deleted()
{
var user1 = new SuperUser { UserName = "foo" };
var user2 = new SuperUser { UserName = "bar" };
var user3 = new SuperUser { UserName = "baz" };
var user4 = new SuperUser { UserName = "jack" };
var user5 = new AdminUser { UserName = "admin" };
using (var session = theStore.OpenSession())
{
session.StoreObjects(new User[] { user1, user2, user3, user4, user5 });
session.SaveChanges();
session.DeleteWhere<SuperUser>(x => x.UserName.StartsWith("b"));
session.SaveChanges();
// no where clause
session.Query<SuperUser>().Where(x => x.IsDeleted()).OrderBy(x => x.UserName).Select(x => x.UserName)
.ToList().ShouldHaveTheSameElementsAs("bar", "baz");
// with a where clause
session.Query<SuperUser>().Where(x => x.UserName != "bar" && x.IsDeleted())
.OrderBy(x => x.UserName)
.Select(x => x.UserName)
.ToList().ShouldHaveTheSameElementsAs("baz");
}
}
[Fact]
public void soft_deleted_documents_work_with_linq_include()
{
theStore.Tenancy.Default.EnsureStorageExists(typeof(User));
theStore.Tenancy.Default.EnsureStorageExists(typeof(File));
using (var session = theStore.OpenSession())
{
var user = new User();
session.Store(user);
var file1 = new File() { UserId = user.Id };
session.Store(file1);
var file2 = new File() { UserId = user.Id };
session.Store(file2);
session.SaveChanges();
session.Delete(file2);
session.SaveChanges();
var users = new List<User>();
var files = session.Query<File>().Include(u => u.UserId, users).ToList();
files.Count.ShouldBe(1);
users.Count.ShouldBe(1);
files = session.Query<File>().Where(f => f.MaybeDeleted()).Include(u => u.UserId, users).ToList();
files.Count.ShouldBe(2);
files = session.Query<File>().Where(f => f.IsDeleted()).Include(u => u.UserId, users).ToList();
files.Count.ShouldBe(1);
}
}
}
public class File
{
public Guid Id { get; set; } = Guid.NewGuid();
public Guid UserId { get; set; }
public string Path { get; set; }
}
}
| |
// 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.
//
namespace System.Reflection
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_PropertyInfo))]
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class PropertyInfo : MemberInfo, _PropertyInfo
{
#region Constructor
protected PropertyInfo() { }
#endregion
public static bool operator ==(PropertyInfo left, PropertyInfo right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null ||
left is RuntimePropertyInfo || right is RuntimePropertyInfo)
{
return false;
}
return left.Equals(right);
}
public static bool operator !=(PropertyInfo left, PropertyInfo right)
{
return !(left == right);
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Property; } }
#endregion
#region Public Abstract\Virtual Members
public virtual object GetConstantValue()
{
throw new NotImplementedException();
}
public virtual object GetRawConstantValue()
{
throw new NotImplementedException();
}
public abstract Type PropertyType { get; }
public abstract void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture);
public abstract MethodInfo[] GetAccessors(bool nonPublic);
public abstract MethodInfo GetGetMethod(bool nonPublic);
public abstract MethodInfo GetSetMethod(bool nonPublic);
public abstract ParameterInfo[] GetIndexParameters();
public abstract PropertyAttributes Attributes { get; }
public abstract bool CanRead { get; }
public abstract bool CanWrite { get; }
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public Object GetValue(Object obj)
{
return GetValue(obj, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public virtual Object GetValue(Object obj,Object[] index)
{
return GetValue(obj, BindingFlags.Default, null, index, null);
}
public abstract Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture);
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public void SetValue(Object obj, Object value)
{
SetValue(obj, value, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public virtual void SetValue(Object obj, Object value, Object[] index)
{
SetValue(obj, value, BindingFlags.Default, null, index, null);
}
#endregion
#region Public Members
public virtual Type[] GetRequiredCustomModifiers() { return EmptyArray<Type>.Value; }
public virtual Type[] GetOptionalCustomModifiers() { return EmptyArray<Type>.Value; }
public MethodInfo[] GetAccessors() { return GetAccessors(false); }
public virtual MethodInfo GetMethod
{
get
{
return GetGetMethod(true);
}
}
public virtual MethodInfo SetMethod
{
get
{
return GetSetMethod(true);
}
}
public MethodInfo GetGetMethod() { return GetGetMethod(false); }
public MethodInfo GetSetMethod() { return GetSetMethod(false); }
public bool IsSpecialName { get { return(Attributes & PropertyAttributes.SpecialName) != 0; } }
#endregion
}
[Serializable]
internal unsafe sealed class RuntimePropertyInfo : PropertyInfo, ISerializable
{
#region Private Data Members
private int m_token;
private string m_name;
private void* m_utf8name;
private PropertyAttributes m_flags;
private RuntimeTypeCache m_reflectedTypeCache;
private RuntimeMethodInfo m_getterMethod;
private RuntimeMethodInfo m_setterMethod;
private MethodInfo[] m_otherMethod;
private RuntimeType m_declaringType;
private BindingFlags m_bindingFlags;
private Signature m_signature;
private ParameterInfo[] m_parameters;
#endregion
#region Constructor
internal RuntimePropertyInfo(
int tkProperty, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate)
{
Contract.Requires(declaredType != null);
Contract.Requires(reflectedTypeCache != null);
Debug.Assert(!reflectedTypeCache.IsGlobal);
MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
m_token = tkProperty;
m_reflectedTypeCache = reflectedTypeCache;
m_declaringType = declaredType;
ConstArray sig;
scope.GetPropertyProps(tkProperty, out m_utf8name, out m_flags, out sig);
RuntimeMethodInfo dummy;
Associates.AssignAssociates(scope, tkProperty, declaredType, reflectedTypeCache.GetRuntimeType(),
out dummy, out dummy, out dummy,
out m_getterMethod, out m_setterMethod, out m_otherMethod,
out isPrivate, out m_bindingFlags);
}
#endregion
#region Internal Members
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RuntimePropertyInfo m = o as RuntimePropertyInfo;
if ((object)m == null)
return false;
return m.m_token == m_token &&
RuntimeTypeHandle.GetModule(m_declaringType).Equals(
RuntimeTypeHandle.GetModule(m.m_declaringType));
}
internal Signature Signature
{
get
{
if (m_signature == null)
{
PropertyAttributes flags;
ConstArray sig;
void* name;
GetRuntimeModule().MetadataImport.GetPropertyProps(
m_token, out name, out flags, out sig);
m_signature = new Signature(sig.Signature.ToPointer(), (int)sig.Length, m_declaringType);
}
return m_signature;
}
}
internal bool EqualsSig(RuntimePropertyInfo target)
{
//@Asymmetry - Legacy policy is to remove duplicate properties, including hidden properties.
// The comparison is done by name and by sig. The EqualsSig comparison is expensive
// but forutnetly it is only called when an inherited property is hidden by name or
// when an interfaces declare properies with the same signature.
// Note that we intentionally don't resolve generic arguments so that we don't treat
// signatures that only match in certain instantiations as duplicates. This has the
// down side of treating overriding and overriden properties as different properties
// in some cases. But PopulateProperties in rttype.cs should have taken care of that
// by comparing VTable slots.
//
// Class C1(Of T, Y)
// Property Prop1(ByVal t1 As T) As Integer
// Get
// ... ...
// End Get
// End Property
// Property Prop1(ByVal y1 As Y) As Integer
// Get
// ... ...
// End Get
// End Property
// End Class
//
Contract.Requires(Name.Equals(target.Name));
Contract.Requires(this != target);
Contract.Requires(this.ReflectedType == target.ReflectedType);
return Signature.CompareSig(this.Signature, target.Signature);
}
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
#endregion
#region Object Overrides
public override String ToString()
{
return FormatNameAndSig(false);
}
private string FormatNameAndSig(bool serialization)
{
StringBuilder sbName = new StringBuilder(PropertyType.FormatTypeName(serialization));
sbName.Append(" ");
sbName.Append(Name);
RuntimeType[] arguments = Signature.Arguments;
if (arguments.Length > 0)
{
sbName.Append(" [");
sbName.Append(MethodBase.ConstructParameters(arguments, Signature.CallingConvention, serialization));
sbName.Append("]");
}
return sbName.ToString();
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return MemberTypes.Property; } }
public override String Name
{
get
{
if (m_name == null)
m_name = new Utf8String(m_utf8name).ToString();
return m_name;
}
}
public override Type DeclaringType
{
get
{
return m_declaringType;
}
}
public override Type ReflectedType
{
get
{
return ReflectedTypeInternal;
}
}
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
public override int MetadataToken { get { return m_token; } }
public override Module Module { get { return GetRuntimeModule(); } }
internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
#endregion
#region PropertyInfo Overrides
#region Non Dynamic
public override Type[] GetRequiredCustomModifiers()
{
return Signature.GetCustomModifiers(0, true);
}
public override Type[] GetOptionalCustomModifiers()
{
return Signature.GetCustomModifiers(0, false);
}
internal object GetConstantValue(bool raw)
{
Object defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw);
if (defaultValue == DBNull.Value)
// Arg_EnumLitValueNotFound -> "Literal value was not found."
throw new InvalidOperationException(Environment.GetResourceString("Arg_EnumLitValueNotFound"));
return defaultValue;
}
public override object GetConstantValue() { return GetConstantValue(false); }
public override object GetRawConstantValue() { return GetConstantValue(true); }
public override MethodInfo[] GetAccessors(bool nonPublic)
{
List<MethodInfo> accessorList = new List<MethodInfo>();
if (Associates.IncludeAccessor(m_getterMethod, nonPublic))
accessorList.Add(m_getterMethod);
if (Associates.IncludeAccessor(m_setterMethod, nonPublic))
accessorList.Add(m_setterMethod);
if ((object)m_otherMethod != null)
{
for(int i = 0; i < m_otherMethod.Length; i ++)
{
if (Associates.IncludeAccessor(m_otherMethod[i] as MethodInfo, nonPublic))
accessorList.Add(m_otherMethod[i]);
}
}
return accessorList.ToArray();
}
public override Type PropertyType
{
get { return Signature.ReturnType; }
}
public override MethodInfo GetGetMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_getterMethod, nonPublic))
return null;
return m_getterMethod;
}
public override MethodInfo GetSetMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_setterMethod, nonPublic))
return null;
return m_setterMethod;
}
public override ParameterInfo[] GetIndexParameters()
{
ParameterInfo[] indexParams = GetIndexParametersNoCopy();
int numParams = indexParams.Length;
if (numParams == 0)
return indexParams;
ParameterInfo[] ret = new ParameterInfo[numParams];
Array.Copy(indexParams, ret, numParams);
return ret;
}
internal ParameterInfo[] GetIndexParametersNoCopy()
{
// @History - Logic ported from RTM
// No need to lock because we don't guarantee the uniqueness of ParameterInfo objects
if (m_parameters == null)
{
int numParams = 0;
ParameterInfo[] methParams = null;
// First try to get the Get method.
MethodInfo m = GetGetMethod(true);
if (m != null)
{
// There is a Get method so use it.
methParams = m.GetParametersNoCopy();
numParams = methParams.Length;
}
else
{
// If there is no Get method then use the Set method.
m = GetSetMethod(true);
if (m != null)
{
methParams = m.GetParametersNoCopy();
numParams = methParams.Length - 1;
}
}
// Now copy over the parameter info's and change their
// owning member info to the current property info.
ParameterInfo[] propParams = new ParameterInfo[numParams];
for (int i = 0; i < numParams; i++)
propParams[i] = new RuntimeParameterInfo((RuntimeParameterInfo)methParams[i], this);
m_parameters = propParams;
}
return m_parameters;
}
public override PropertyAttributes Attributes
{
get
{
return m_flags;
}
}
public override bool CanRead
{
get
{
return m_getterMethod != null;
}
}
public override bool CanWrite
{
get
{
return m_setterMethod != null;
}
}
#endregion
#region Dynamic
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValue(Object obj,Object[] index)
{
return GetValue(obj, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
null, index, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
{
MethodInfo m = GetGetMethod(true);
if (m == null)
throw new ArgumentException(System.Environment.GetResourceString("Arg_GetMethNotFnd"));
return m.Invoke(obj, invokeAttr, binder, index, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, Object[] index)
{
SetValue(obj,
value,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
null,
index,
null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
{
MethodInfo m = GetSetMethod(true);
if (m == null)
throw new ArgumentException(System.Environment.GetResourceString("Arg_SetMethNotFnd"));
Object[] args = null;
if (index != null)
{
args = new Object[index.Length + 1];
for(int i=0;i<index.Length;i++)
args[i] = index[i];
args[index.Length] = value;
}
else
{
args = new Object[1];
args[0] = value;
}
m.Invoke(obj, invokeAttr, binder, args, culture);
}
#endregion
#endregion
#region ISerializable Implementation
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException(nameof(info));
Contract.EndContractBlock();
MemberInfoSerializationHolder.GetSerializationInfo(
info,
Name,
ReflectedTypeInternal,
ToString(),
SerializationToString(),
MemberTypes.Property,
null);
}
internal string SerializationToString()
{
return FormatNameAndSig(true);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.AspNetCore.Razor.TagHelpers.Testing;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Testing;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.TagHelpers
{
public class ValidationSummaryTagHelperTest
{
public static TheoryData<ModelStateDictionary> ProcessAsync_GeneratesExpectedOutput_WithNoErrorsData
{
get
{
var emptyModelState = new ModelStateDictionary();
var modelState = new ModelStateDictionary();
SetValidModelState(modelState);
return new TheoryData<ModelStateDictionary>
{
emptyModelState,
modelState,
};
}
}
[Theory]
[MemberData(nameof(ProcessAsync_GeneratesExpectedOutput_WithNoErrorsData))]
public async Task ProcessAsync_GeneratesExpectedOutput_WithNoErrors(ModelStateDictionary modelState)
{
// Arrange
var expectedTagName = "not-div";
var metadataProvider = new TestModelMetadataProvider();
var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
var expectedAttributes = new TagHelperAttributeList
{
new TagHelperAttribute("class", "form-control validation-summary-valid"),
new TagHelperAttribute("data-valmsg-summary", "true"),
};
var expectedPreContent = "original pre-content";
var expectedContent = "original content";
var tagHelperContext = new TagHelperContext(
tagName: "not-div",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
expectedTagName,
attributes: new TagHelperAttributeList
{
{ "class", "form-control" }
},
getChildContentAsync: (useCachedResult, encoder) =>
{
throw new InvalidOperationException("getChildContentAsync called unexpectedly");
});
output.PreContent.SetContent(expectedPreContent);
output.Content.SetContent(expectedContent);
output.PostContent.SetContent("Custom Content");
var model = new Model();
var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider, modelState);
var validationSummaryTagHelper = new ValidationSummaryTagHelper(htmlGenerator)
{
ValidationSummary = ValidationSummary.All,
ViewContext = viewContext,
};
// Act
await validationSummaryTagHelper.ProcessAsync(tagHelperContext, output);
// Assert
Assert.Equal(expectedAttributes, output.Attributes, CaseSensitiveTagHelperAttributeComparer.Default);
Assert.Equal(expectedPreContent, output.PreContent.GetContent());
Assert.Equal(expectedContent, output.Content.GetContent());
Assert.Equal(
$"Custom Content<ul><li style=\"display:none\"></li>{Environment.NewLine}</ul>",
output.PostContent.GetContent());
Assert.Equal(expectedTagName, output.TagName);
}
[Theory]
[MemberData(nameof(ProcessAsync_GeneratesExpectedOutput_WithNoErrorsData))]
public async Task ProcessAsync_SuppressesOutput_IfClientSideValidationDisabled_WithNoErrorsData(
ModelStateDictionary modelStateDictionary)
{
// Arrange
var metadataProvider = new TestModelMetadataProvider();
var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
var viewContext = CreateViewContext();
viewContext.ClientValidationEnabled = false;
var validationSummaryTagHelper = new ValidationSummaryTagHelper(htmlGenerator)
{
ValidationSummary = ValidationSummary.All,
ViewContext = viewContext,
};
var output = new TagHelperOutput(
"div",
new TagHelperAttributeList(),
(useCachedResult, encoder) =>
{
throw new InvalidOperationException("getChildContentAsync called unexpectedly.");
});
var context = new TagHelperContext(
tagName: "div",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act
await validationSummaryTagHelper.ProcessAsync(context, output);
// Assert
Assert.Null(output.TagName);
Assert.Empty(output.Attributes);
Assert.Empty(HtmlContentUtilities.HtmlContentToString(output));
}
public static TheoryData<string, ModelStateDictionary> ProcessAsync_SuppressesOutput_IfModelOnlyWithNoModelErrorData
{
get
{
var emptyModelState = new ModelStateDictionary();
var modelState = new ModelStateDictionary();
SetValidModelState(modelState);
var invalidModelState = new ModelStateDictionary();
SetValidModelState(invalidModelState);
invalidModelState.AddModelError($"{nameof(Model.Strings)}[1]", "This value is invalid.");
return new TheoryData<string, ModelStateDictionary>
{
{ string.Empty, emptyModelState },
{ string.Empty, modelState },
{ nameof(Model.Text), modelState },
{ "not-a-key", modelState },
{ string.Empty, invalidModelState },
{ $"{nameof(Model.Strings)}[2]", invalidModelState },
{ nameof(Model.Text), invalidModelState },
{ "not-a-key", invalidModelState },
};
}
}
[Theory]
[MemberData(nameof(ProcessAsync_SuppressesOutput_IfModelOnlyWithNoModelErrorData))]
public async Task ProcessAsync_SuppressesOutput_IfModelOnly_WithNoModelError(
string prefix,
ModelStateDictionary modelStateDictionary)
{
// Arrange
var metadataProvider = new TestModelMetadataProvider();
var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
var viewContext = CreateViewContext();
viewContext.ViewData.TemplateInfo.HtmlFieldPrefix = prefix;
var validationSummaryTagHelper = new ValidationSummaryTagHelper(htmlGenerator)
{
ValidationSummary = ValidationSummary.ModelOnly,
ViewContext = viewContext,
};
var output = new TagHelperOutput(
"div",
new TagHelperAttributeList(),
(useCachedResult, encoder) =>
{
throw new InvalidOperationException("getChildContentAsync called unexpectedly.");
});
var context = new TagHelperContext(
tagName: "div",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act
await validationSummaryTagHelper.ProcessAsync(context, output);
// Assert
Assert.Null(output.TagName);
Assert.Empty(output.Attributes);
Assert.Empty(HtmlContentUtilities.HtmlContentToString(output));
}
[Theory]
[InlineData(ValidationSummary.All)]
[InlineData(ValidationSummary.ModelOnly)]
public async Task ProcessAsync_GeneratesExpectedOutput_WithModelError(ValidationSummary validationSummary)
{
// Arrange
var expectedError = "I am an error.";
var expectedTagName = "not-div";
var metadataProvider = new TestModelMetadataProvider();
var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
var validationSummaryTagHelper = new ValidationSummaryTagHelper(htmlGenerator)
{
ValidationSummary = validationSummary,
};
var expectedPreContent = "original pre-content";
var expectedContent = "original content";
var tagHelperContext = new TagHelperContext(
tagName: "not-div",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
expectedTagName,
attributes: new TagHelperAttributeList
{
{ "class", "form-control" }
},
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
output.PreContent.SetContent(expectedPreContent);
output.Content.SetContent(expectedContent);
output.PostContent.SetContent("Custom Content");
var model = new Model();
var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider);
validationSummaryTagHelper.ViewContext = viewContext;
var modelState = viewContext.ModelState;
SetValidModelState(modelState);
modelState.AddModelError(string.Empty, expectedError);
// Act
await validationSummaryTagHelper.ProcessAsync(tagHelperContext, output);
// Assert
Assert.InRange(output.Attributes.Count, low: 1, high: 2);
var attribute = Assert.Single(output.Attributes, attr => attr.Name.Equals("class"));
Assert.Equal(
new TagHelperAttribute("class", "form-control validation-summary-errors"),
attribute,
CaseSensitiveTagHelperAttributeComparer.Default);
Assert.Equal(expectedPreContent, output.PreContent.GetContent());
Assert.Equal(expectedContent, output.Content.GetContent());
Assert.Equal(
$"Custom Content<ul><li>{expectedError}</li>{Environment.NewLine}</ul>",
output.PostContent.GetContent());
Assert.Equal(expectedTagName, output.TagName);
}
[Fact]
public async Task ProcessAsync_GeneratesExpectedOutput_WithPropertyErrors()
{
// Arrange
var expectedError0 = "I am an error.";
var expectedError2 = "I am also an error.";
var expectedTagName = "not-div";
var expectedAttributes = new TagHelperAttributeList
{
new TagHelperAttribute("class", "form-control validation-summary-errors"),
new TagHelperAttribute("data-valmsg-summary", "true"),
};
var metadataProvider = new TestModelMetadataProvider();
var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
var validationSummaryTagHelper = new ValidationSummaryTagHelper(htmlGenerator)
{
ValidationSummary = ValidationSummary.All,
};
var expectedPreContent = "original pre-content";
var expectedContent = "original content";
var tagHelperContext = new TagHelperContext(
tagName: "not-div",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
expectedTagName,
attributes: new TagHelperAttributeList
{
{ "class", "form-control" }
},
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
output.PreContent.SetContent(expectedPreContent);
output.Content.SetContent(expectedContent);
output.PostContent.SetContent("Custom Content");
var model = new Model();
var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider);
validationSummaryTagHelper.ViewContext = viewContext;
var modelState = viewContext.ModelState;
SetValidModelState(modelState);
modelState.AddModelError(key: $"{nameof(Model.Strings)}[0]", errorMessage: expectedError0);
modelState.AddModelError(key: $"{nameof(Model.Strings)}[2]", errorMessage: expectedError2);
// Act
await validationSummaryTagHelper.ProcessAsync(tagHelperContext, output);
// Assert
Assert.Equal(expectedAttributes, output.Attributes, CaseSensitiveTagHelperAttributeComparer.Default);
Assert.Equal(expectedPreContent, output.PreContent.GetContent());
Assert.Equal(expectedContent, output.Content.GetContent());
Assert.Equal(
$"Custom Content<ul><li>{expectedError0}</li>{Environment.NewLine}" +
$"<li>{expectedError2}</li>{Environment.NewLine}</ul>",
output.PostContent.GetContent());
Assert.Equal(expectedTagName, output.TagName);
}
[Theory]
[InlineData(ValidationSummary.All, false)]
[InlineData(ValidationSummary.ModelOnly, true)]
public async Task ProcessAsync_CallsIntoGenerateValidationSummaryWithExpectedParameters(
ValidationSummary validationSummary,
bool expectedExcludePropertyErrors)
{
// Arrange
var expectedViewContext = CreateViewContext();
var generator = new Mock<IHtmlGenerator>();
generator
.Setup(mock => mock.GenerateValidationSummary(
expectedViewContext,
expectedExcludePropertyErrors,
null, // message
null, // headerTag
null)) // htmlAttributes
.Returns(new TagBuilder("div"))
.Verifiable();
var validationSummaryTagHelper = new ValidationSummaryTagHelper(generator.Object)
{
ValidationSummary = validationSummary,
};
var expectedPreContent = "original pre-content";
var expectedContent = "original content";
var expectedPostContent = "original post-content";
var output = new TagHelperOutput(
tagName: "div",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(
new DefaultTagHelperContent()));
output.PreContent.SetContent(expectedPreContent);
output.Content.SetContent(expectedContent);
output.PostContent.SetContent(expectedPostContent);
validationSummaryTagHelper.ViewContext = expectedViewContext;
var context = new TagHelperContext(
tagName: "div",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act & Assert
await validationSummaryTagHelper.ProcessAsync(context, output);
generator.Verify();
Assert.Equal("div", output.TagName);
Assert.Empty(output.Attributes);
Assert.Equal(expectedPreContent, output.PreContent.GetContent());
Assert.Equal(expectedContent, output.Content.GetContent());
Assert.Equal(expectedPostContent, output.PostContent.GetContent());
}
[Fact]
public async Task ProcessAsync_MergesTagBuilderFromGenerateValidationSummary()
{
// Arrange
var tagBuilder = new TagBuilder("span2");
tagBuilder.InnerHtml.SetHtmlContent("New HTML");
tagBuilder.Attributes.Add("anything", "something");
tagBuilder.Attributes.Add("data-foo", "bar");
tagBuilder.Attributes.Add("data-hello", "world");
var generator = new Mock<IHtmlGenerator>(MockBehavior.Strict);
generator
.Setup(mock => mock.GenerateValidationSummary(
It.IsAny<ViewContext>(),
It.IsAny<bool>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<object>()))
.Returns(tagBuilder);
var validationSummaryTagHelper = new ValidationSummaryTagHelper(generator.Object)
{
ValidationSummary = ValidationSummary.ModelOnly,
};
var expectedPreContent = "original pre-content";
var expectedContent = "original content";
var output = new TagHelperOutput(
tagName: "div",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(
new DefaultTagHelperContent()));
output.PreContent.SetContent(expectedPreContent);
output.Content.SetContent(expectedContent);
output.PostContent.SetContent("Content of validation summary");
var viewContext = CreateViewContext();
validationSummaryTagHelper.ViewContext = viewContext;
var context = new TagHelperContext(
tagName: "div",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act
await validationSummaryTagHelper.ProcessAsync(context, output);
// Assert
Assert.Equal("div", output.TagName);
Assert.Collection(
output.Attributes,
attribute =>
{
Assert.Equal("anything", attribute.Name);
Assert.Equal("something", attribute.Value);
},
attribute =>
{
Assert.Equal("data-foo", attribute.Name);
Assert.Equal("bar", attribute.Value);
},
attribute =>
{
Assert.Equal("data-hello", attribute.Name);
Assert.Equal("world", attribute.Value);
});
Assert.Equal(expectedPreContent, output.PreContent.GetContent());
Assert.Equal(expectedContent, output.Content.GetContent());
Assert.Equal("Content of validation summaryNew HTML", output.PostContent.GetContent());
}
[Fact]
public async Task ProcessAsync_DoesNothingIfValidationSummaryNone()
{
// Arrange
var generator = new Mock<IHtmlGenerator>(MockBehavior.Strict);
var validationSummaryTagHelper = new ValidationSummaryTagHelper(generator.Object)
{
ValidationSummary = ValidationSummary.None,
};
var expectedPreContent = "original pre-content";
var expectedContent = "original content";
var expectedPostContent = "original post-content";
var output = new TagHelperOutput(
tagName: "div",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(
new DefaultTagHelperContent()));
output.PreContent.SetContent(expectedPreContent);
output.Content.SetContent(expectedContent);
output.PostContent.SetContent(expectedPostContent);
var viewContext = CreateViewContext();
validationSummaryTagHelper.ViewContext = viewContext;
var context = new TagHelperContext(
tagName: "div",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act
await validationSummaryTagHelper.ProcessAsync(context, output);
// Assert
Assert.Equal("div", output.TagName);
Assert.Empty(output.Attributes);
Assert.Equal(expectedPreContent, output.PreContent.GetContent());
Assert.Equal(expectedContent, output.Content.GetContent());
Assert.Equal(expectedPostContent, output.PostContent.GetContent());
}
[Theory]
[InlineData(ValidationSummary.All)]
[InlineData(ValidationSummary.ModelOnly)]
public async Task ProcessAsync_GeneratesValidationSummaryWhenNotNone(ValidationSummary validationSummary)
{
// Arrange
var tagBuilder = new TagBuilder("span2");
tagBuilder.InnerHtml.SetHtmlContent("New HTML");
var generator = new Mock<IHtmlGenerator>();
generator
.Setup(mock => mock.GenerateValidationSummary(
It.IsAny<ViewContext>(),
It.IsAny<bool>(),
It.IsAny<string>(),
It.IsAny<string>(),
It.IsAny<object>()))
.Returns(tagBuilder)
.Verifiable();
var validationSummaryTagHelper = new ValidationSummaryTagHelper(generator.Object)
{
ValidationSummary = validationSummary,
};
var expectedPreContent = "original pre-content";
var expectedContent = "original content";
var output = new TagHelperOutput(
tagName: "div",
attributes: new TagHelperAttributeList(),
getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(
new DefaultTagHelperContent()));
output.PreContent.SetContent(expectedPreContent);
output.Content.SetContent(expectedContent);
output.PostContent.SetContent("Content of validation message");
var viewContext = CreateViewContext();
validationSummaryTagHelper.ViewContext = viewContext;
var context = new TagHelperContext(
tagName: "div",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
// Act
await validationSummaryTagHelper.ProcessAsync(context, output);
// Assert
Assert.Equal("div", output.TagName);
Assert.Empty(output.Attributes);
Assert.Equal(expectedPreContent, output.PreContent.GetContent());
Assert.Equal(expectedContent, output.Content.GetContent());
Assert.Equal("Content of validation messageNew HTML", output.PostContent.GetContent());
generator.Verify();
}
[Theory]
[InlineData((ValidationSummary)(-1))]
[InlineData((ValidationSummary)23)]
[InlineData(ValidationSummary.All | ValidationSummary.ModelOnly)]
[ReplaceCulture]
public void ValidationSummaryProperty_ThrowsWhenSetToInvalidValidationSummaryValue(
ValidationSummary validationSummary)
{
// Arrange
var generator = new TestableHtmlGenerator(new EmptyModelMetadataProvider());
var validationSummaryTagHelper = new ValidationSummaryTagHelper(generator);
var validationTypeName = typeof(ValidationSummary).FullName;
var expectedMessage = $"The value of argument 'value' ({validationSummary}) is invalid for Enum type '{validationTypeName}'.";
// Act & Assert
ExceptionAssert.ThrowsArgument(
() => validationSummaryTagHelper.ValidationSummary = validationSummary,
"value",
expectedMessage);
}
[Fact]
public async Task ProcessAsync_GeneratesExpectedOutput_WithModelErrorForIEnumerable()
{
// Arrange
var expectedError = "Something went wrong.";
var expectedTagName = "not-div";
var expectedAttributes = new TagHelperAttributeList
{
new TagHelperAttribute("class", "form-control validation-summary-errors"),
new TagHelperAttribute("data-valmsg-summary", "true"),
};
var metadataProvider = new TestModelMetadataProvider();
var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
var validationSummaryTagHelper = new ValidationSummaryTagHelper(htmlGenerator)
{
ValidationSummary = ValidationSummary.All,
};
var expectedPreContent = "original pre-content";
var expectedContent = "original content";
var tagHelperContext = new TagHelperContext(
tagName: "not-div",
allAttributes: new TagHelperAttributeList(),
items: new Dictionary<object, object>(),
uniqueId: "test");
var output = new TagHelperOutput(
expectedTagName,
attributes: new TagHelperAttributeList
{
{ "class", "form-control" }
},
getChildContentAsync: (useCachedResult, encoder) =>
{
var tagHelperContent = new DefaultTagHelperContent();
tagHelperContent.SetContent("Something");
return Task.FromResult<TagHelperContent>(tagHelperContent);
});
output.PreContent.SetContent(expectedPreContent);
output.Content.SetContent(expectedContent);
output.PostContent.SetContent("Custom Content");
var model = new FormMetadata();
var viewContext = TestableHtmlGenerator.GetViewContext(model, htmlGenerator, metadataProvider);
validationSummaryTagHelper.ViewContext = viewContext;
viewContext.ModelState.AddModelError(key: nameof(FormMetadata.ID), errorMessage: expectedError);
// Act
await validationSummaryTagHelper.ProcessAsync(tagHelperContext, output);
// Assert
Assert.Equal(expectedAttributes, output.Attributes, CaseSensitiveTagHelperAttributeComparer.Default);
Assert.Equal(expectedPreContent, output.PreContent.GetContent());
Assert.Equal(expectedContent, output.Content.GetContent());
Assert.Equal(
$"Custom Content<ul><li>{expectedError}</li>{Environment.NewLine}</ul>",
output.PostContent.GetContent());
Assert.Equal(expectedTagName, output.TagName);
}
private static ViewContext CreateViewContext()
{
var actionContext = new ActionContext(
new DefaultHttpContext(),
new RouteData(),
new ActionDescriptor());
return new ViewContext(
actionContext,
Mock.Of<IView>(),
new ViewDataDictionary(
new EmptyModelMetadataProvider(),
new ModelStateDictionary()),
Mock.Of<ITempDataDictionary>(),
TextWriter.Null,
new HtmlHelperOptions());
}
private static void SetValidModelState(ModelStateDictionary modelState)
{
modelState.SetModelValue(key: nameof(Model.Empty), rawValue: null, attemptedValue: null);
modelState.SetModelValue(key: $"{nameof(Model.Strings)}[0]", rawValue: null, attemptedValue: null);
modelState.SetModelValue(key: $"{nameof(Model.Strings)}[1]", rawValue: null, attemptedValue: null);
modelState.SetModelValue(key: $"{nameof(Model.Strings)}[2]", rawValue: null, attemptedValue: null);
modelState.SetModelValue(key: nameof(Model.Text), rawValue: null, attemptedValue: null);
foreach (var key in modelState.Keys)
{
modelState.MarkFieldValid(key);
}
}
private class Model
{
public string Text { get; set; }
public string[] Strings { get; set; }
// Exists to ensure #4989 does not regress. Issue specific to case where collection has a ModelStateEntry
// but no element does.
public byte[] Empty { get; set; }
}
private class FormMetadata : IEnumerable<Model>
{
private readonly List<Model> _fields = new List<Model>();
public int ID { get; set; }
public IEnumerator<Model> GetEnumerator()
{
return _fields.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _fields.GetEnumerator();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using OrchardCore.Modules;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using OrchardCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Display;
using OrchardCore.ContentManagement.Metadata.Models;
using OrchardCore.ContentManagement.Metadata.Settings;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Records;
using OrchardCore.Contents.Services;
using OrchardCore.Contents.ViewModels;
using OrchardCore.DisplayManagement;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Navigation;
using OrchardCore.Settings;
using YesSql;
using YesSql.Services;
namespace OrchardCore.Contents.Controllers
{
public class AdminController : Controller, IUpdateModel
{
private readonly IContentManager _contentManager;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly ISiteService _siteService;
private readonly ISession _session;
private readonly IContentItemDisplayManager _contentItemDisplayManager;
private readonly INotifier _notifier;
private readonly IAuthorizationService _authorizationService;
private readonly IEnumerable<IContentAdminFilter> _contentAdminFilters;
public AdminController(
IContentManager contentManager,
IContentItemDisplayManager contentItemDisplayManager,
IContentDefinitionManager contentDefinitionManager,
ISiteService siteService,
INotifier notifier,
ISession session,
IShapeFactory shapeFactory,
ILogger<AdminController> logger,
IHtmlLocalizer<AdminController> localizer,
IAuthorizationService authorizationService,
IEnumerable<IContentAdminFilter> contentAdminFilters
)
{
_contentAdminFilters = contentAdminFilters;
_authorizationService = authorizationService;
_notifier = notifier;
_contentItemDisplayManager = contentItemDisplayManager;
_session = session;
_siteService = siteService;
_contentManager = contentManager;
_contentDefinitionManager = contentDefinitionManager;
T = localizer;
New = shapeFactory;
Logger = logger;
}
public IHtmlLocalizer T { get; }
public dynamic New { get; set; }
public ILogger Logger { get; set; }
public async Task<IActionResult> List(ListContentsViewModel model, PagerParameters pagerParameters)
{
var siteSettings = await _siteService.GetSiteSettingsAsync();
Pager pager = new Pager(pagerParameters, siteSettings.PageSize);
var query = _session.Query<ContentItem, ContentItemIndex>();
switch (model.Options.ContentsStatus)
{
case ContentsStatus.Published:
query = query.With<ContentItemIndex>(x => x.Published);
break;
case ContentsStatus.Draft:
query = query.With<ContentItemIndex>(x => x.Latest && !x.Published);
break;
case ContentsStatus.AllVersions:
query = query.With<ContentItemIndex>(x => x.Latest);
break;
default:
query = query.With<ContentItemIndex>(x => x.Latest);
break;
}
if (!string.IsNullOrEmpty(model.TypeName))
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(model.TypeName);
if (contentTypeDefinition == null)
return NotFound();
model.TypeDisplayName = contentTypeDefinition.ToString();
// We display a specific type even if it's not listable so that admin pages
// can reuse the Content list page for specific types.
query = query.With<ContentItemIndex>(x => x.ContentType == model.TypeName);
}
else
{
var listableTypes = (await GetListableTypesAsync()).Select(t => t.Name).ToArray();
if(listableTypes.Any())
{
query = query.With<ContentItemIndex>(x => x.ContentType.IsIn(listableTypes));
}
}
switch (model.Options.OrderBy)
{
case ContentsOrder.Modified:
query = query.OrderByDescending(x => x.ModifiedUtc);
break;
case ContentsOrder.Published:
query = query.OrderByDescending(cr => cr.PublishedUtc);
break;
case ContentsOrder.Created:
query = query.OrderByDescending(cr => cr.CreatedUtc);
break;
default:
query = query.OrderByDescending(cr => cr.ModifiedUtc);
break;
}
//if (!String.IsNullOrWhiteSpace(model.Options.SelectedCulture))
//{
// query = _cultureFilter.FilterCulture(query, model.Options.SelectedCulture);
//}
//if (model.Options.ContentsStatus == ContentsStatus.Owner)
//{
// query = query.Where<CommonPartRecord>(cr => cr.OwnerId == Services.WorkContext.CurrentUser.Id);
//}
model.Options.SelectedFilter = model.TypeName;
model.Options.FilterOptions = (await GetListableTypesAsync())
.Select(ctd => new KeyValuePair<string, string>(ctd.Name, ctd.DisplayName))
.ToList().OrderBy(kvp => kvp.Value);
//model.Options.Cultures = _cultureManager.ListCultures();
// Invoke any service that could alter the query
await _contentAdminFilters.InvokeAsync(x => x.FilterAsync(query, model, pagerParameters, this), Logger);
var maxPagedCount = siteSettings.MaxPagedCount;
if (maxPagedCount > 0 && pager.PageSize > maxPagedCount)
pager.PageSize = maxPagedCount;
var pagerShape = New.Pager(pager).TotalItemCount(maxPagedCount > 0 ? maxPagedCount : await query.CountAsync());
var pageOfContentItems = await query.Skip(pager.GetStartIndex()).Take(pager.PageSize).ListAsync();
var contentItemSummaries = new List<dynamic>();
foreach(var contentItem in pageOfContentItems)
{
contentItemSummaries.Add(await _contentItemDisplayManager.BuildDisplayAsync(contentItem, this, "SummaryAdmin"));
}
var viewModel = New.ViewModel()
.ContentItems(contentItemSummaries)
.Pager(pagerShape)
.Options(model.Options)
.TypeDisplayName(model.TypeDisplayName ?? "");
return View(viewModel);
}
private async Task<IEnumerable<ContentTypeDefinition>> GetCreatableTypesAsync()
{
var creatable = new List<ContentTypeDefinition>();
foreach (var ctd in _contentDefinitionManager.ListTypeDefinitions())
{
if(ctd.Settings.ToObject<ContentTypeSettings>().Creatable)
{
var authorized = await _authorizationService.AuthorizeAsync(User, Permissions.EditContent, _contentManager.New(ctd.Name));
if (authorized)
{
creatable.Add(ctd);
}
}
}
return creatable;
}
private async Task<IEnumerable<ContentTypeDefinition>> GetListableTypesAsync()
{
var listable = new List<ContentTypeDefinition>();
foreach (var ctd in _contentDefinitionManager.ListTypeDefinitions())
{
if (ctd.Settings.ToObject<ContentTypeSettings>().Listable)
{
var authorized = await _authorizationService.AuthorizeAsync(User, Permissions.EditContent, _contentManager.New(ctd.Name));
if (authorized)
{
listable.Add(ctd);
}
}
}
return listable;
}
//[HttpPost, ActionName("List")]
//[Mvc.FormValueRequired("submit.Filter")]
//public ActionResult ListFilterPOST(ContentOptions options)
//{
// var routeValues = ControllerContext.RouteData.Values;
// if (options != null)
// {
// routeValues["Options.SelectedCulture"] = options.SelectedCulture; //todo: don't hard-code the key
// routeValues["Options.OrderBy"] = options.OrderBy; //todo: don't hard-code the key
// routeValues["Options.ContentsStatus"] = options.ContentsStatus; //todo: don't hard-code the key
// if (GetListableTypes(false).Any(ctd => string.Equals(ctd.Name, options.SelectedFilter, StringComparison.OrdinalIgnoreCase)))
// {
// routeValues["id"] = options.SelectedFilter;
// }
// else {
// routeValues.Remove("id");
// }
// }
// return RedirectToAction("List", routeValues);
//}
//[HttpPost, ActionName("List")]
//[Mvc.FormValueRequired("submit.BulkEdit")]
//public ActionResult ListPOST(ContentOptions options, IEnumerable<int> itemIds, string returnUrl)
//{
// if (itemIds != null)
// {
// var checkedContentItems = _contentManager.GetMany<ContentItem>(itemIds, VersionOptions.Latest, QueryHints.Empty);
// switch (options.BulkAction)
// {
// case ContentsBulkAction.None:
// break;
// case ContentsBulkAction.PublishNow:
// foreach (var item in checkedContentItems)
// {
// if (!await _authorizationService.Authorize(User, Permissions.PublishContent, item, T("Couldn't publish selected content.")))
// {
// _transactionManager.Cancel();
// return Unauthorized();
// }
// _contentManager.Publish(item);
// }
// Services.Notifier.Information(T("Content successfully published."));
// break;
// case ContentsBulkAction.Unpublish:
// foreach (var item in checkedContentItems)
// {
// if (!await _authorizationService.Authorize(User, Permissions.PublishContent, item, T("Couldn't unpublish selected content.")))
// {
// _transactionManager.Cancel();
// return Unauthorized();
// }
// _contentManager.Unpublish(item);
// }
// Services.Notifier.Information(T("Content successfully unpublished."));
// break;
// case ContentsBulkAction.Remove:
// foreach (var item in checkedContentItems)
// {
// if (!await _authorizationService.Authorize(User, Permissions.DeleteContent, item, T("Couldn't remove selected content.")))
// {
// _transactionManager.Cancel();
// return Unauthorized();
// }
// _contentManager.Remove(item);
// }
// Services.Notifier.Information(T("Content successfully removed."));
// break;
// default:
// throw new ArgumentOutOfRangeException();
// }
// }
// return this.RedirectLocal(returnUrl, () => RedirectToAction("List"));
//}
//ActionResult ListableTypeList(int? containerId)
//{
// var viewModel = Shape.ViewModel(ContentTypes: GetListableTypes(containerId.HasValue), ContainerId: containerId);
// return View("ListableTypeList", viewModel);
//}
public async Task<IActionResult> Create(string id)
{
if (String.IsNullOrWhiteSpace(id))
{
return NotFound();
}
var contentItem = _contentManager.New(id);
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContent, contentItem))
{
return Unauthorized();
}
var model = await _contentItemDisplayManager.BuildEditorAsync(contentItem, this);
return View(model);
}
[HttpPost, ActionName("Create")]
[FormValueRequired("submit.Save")]
public Task<IActionResult> CreatePOST(string id, string returnUrl)
{
return CreatePOST(id, returnUrl, contentItem =>
{
var typeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType);
_notifier.Success(string.IsNullOrWhiteSpace(typeDefinition.DisplayName)
? T["Your content draft has been saved."]
: T["Your {0} draft has been saved.", typeDefinition.DisplayName]);
return Task.CompletedTask;
});
}
[HttpPost, ActionName("Create")]
[FormValueRequired("submit.Publish")]
public async Task<IActionResult> CreateAndPublishPOST(string id, string returnUrl)
{
// pass a dummy content to the authorization check to check for "own" variations
var dummyContent = _contentManager.New(id);
if (!await _authorizationService.AuthorizeAsync(User, Permissions.PublishContent, dummyContent))
{
return Unauthorized();
}
return await CreatePOST(id, returnUrl, async contentItem => {
await _contentManager.PublishAsync(contentItem);
var typeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType);
_notifier.Success(string.IsNullOrWhiteSpace(typeDefinition.DisplayName)
? T["Your content has been published."]
: T["Your {0} has been published.", typeDefinition.DisplayName]);
});
}
private async Task<IActionResult> CreatePOST(string id, string returnUrl, Func<ContentItem, Task> conditionallyPublish)
{
var contentItem = _contentManager.New(id);
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContent, contentItem))
{
return Unauthorized();
}
var model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, this);
if (!ModelState.IsValid)
{
_session.Cancel();
return View(model);
}
_contentManager.Create(contentItem, VersionOptions.Draft);
await conditionallyPublish(contentItem);
if (!string.IsNullOrEmpty(returnUrl))
{
return LocalRedirect(returnUrl);
}
var adminRouteValues = _contentManager.PopulateAspect<ContentItemMetadata>(contentItem).AdminRouteValues;
return RedirectToRoute(adminRouteValues);
}
public async Task<IActionResult> Display(string contentItemId)
{
var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest);
if (contentItem == null)
{
return NotFound();
}
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ViewContent, contentItem))
{
return Unauthorized();
}
var model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, this, "DetailAdmin");
return View(model);
}
public async Task<IActionResult> Edit(string contentItemId)
{
var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest);
if (contentItem == null)
return NotFound();
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContent, contentItem))
{
return Unauthorized();
}
var model = await _contentItemDisplayManager.BuildEditorAsync(contentItem, this);
return View(model);
}
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.Save")]
public Task<IActionResult> EditPOST(string contentItemId, string returnUrl)
{
return EditPOST(contentItemId, returnUrl, contentItem =>
{
var typeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType);
_notifier.Success(string.IsNullOrWhiteSpace(typeDefinition.DisplayName)
? T["Your content draft has been saved."]
: T["Your {0} draft has been saved.", typeDefinition.DisplayName]);
return Task.CompletedTask;
});
}
[HttpPost, ActionName("Edit")]
[FormValueRequired("submit.Publish")]
public async Task<IActionResult> EditAndPublishPOST(string contentItemId, string returnUrl)
{
var content = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest);
if (content == null)
{
return NotFound();
}
if (!await _authorizationService.AuthorizeAsync(User, Permissions.PublishContent, content))
{
return Unauthorized();
}
return await EditPOST(contentItemId, returnUrl, async contentItem =>
{
await _contentManager.PublishAsync(contentItem);
var typeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType);
_notifier.Success(string.IsNullOrWhiteSpace(typeDefinition.DisplayName)
? T["Your content has been published."]
: T["Your {0} has been published.", typeDefinition.DisplayName]);
});
}
private async Task<IActionResult> EditPOST(string contentItemId, string returnUrl, Func<ContentItem, Task> conditionallyPublish)
{
var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.DraftRequired);
if (contentItem == null)
{
return NotFound();
}
if (!await _authorizationService.AuthorizeAsync(User, Permissions.EditContent, contentItem))
{
return Unauthorized();
}
//string previousRoute = null;
//if (contentItem.Has<IAliasAspect>() &&
// !string.IsNullOrWhiteSpace(returnUrl)
// && Request.IsLocalUrl(returnUrl)
// // only if the original returnUrl is the content itself
// && String.Equals(returnUrl, Url.ItemDisplayUrl(contentItem), StringComparison.OrdinalIgnoreCase)
// )
//{
// previousRoute = contentItem.As<IAliasAspect>().Path;
//}
var model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, this);
if (!ModelState.IsValid)
{
_session.Cancel();
return View("Edit", model);
}
await conditionallyPublish(contentItem);
// The content item needs to be marked as saved (again) in case the drivers or the handlers have
// executed some query which would flush the saved entities. In this case the changes happening in handlers
// would not be taken into account.
_session.Save(contentItem);
//if (!string.IsNullOrWhiteSpace(returnUrl)
// && previousRoute != null
// && !String.Equals(contentItem.As<IAliasAspect>().Path, previousRoute, StringComparison.OrdinalIgnoreCase))
//{
// returnUrl = Url.ItemDisplayUrl(contentItem);
//}
var typeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType);
if (returnUrl == null)
{
return RedirectToAction("Edit", new RouteValueDictionary { { "ContentItemId", contentItem.ContentItemId } });
}
else
{
return LocalRedirect(returnUrl);
}
}
//[HttpPost]
//public ActionResult Clone(int id, string returnUrl)
//{
// var contentItem = _contentManager.GetLatest(id);
// if (contentItem == null)
// return NotFound();
// if (!await _authorizationService.Authorize(User, Permissions.EditContent, contentItem, T("Couldn't clone content")))
// return Unauthorized();
// try
// {
// Services.ContentManager.Clone(contentItem);
// }
// catch (InvalidOperationException)
// {
// Services.Notifier.Warning(T("Could not clone the content item."));
// return this.RedirectLocal(returnUrl, () => RedirectToAction("List"));
// }
// Services.Notifier.Information(T("Successfully cloned. The clone was saved as a draft."));
// return this.RedirectLocal(returnUrl, () => RedirectToAction("List"));
//}
[HttpPost]
public async Task<IActionResult> DiscardDraft(string contentItemId, string returnUrl)
{
var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest);
if (contentItem == null || contentItem.Published)
{
return NotFound();
}
if (!await _authorizationService.AuthorizeAsync(User, Permissions.DeleteContent, contentItem))
{
return Unauthorized();
}
if (contentItem != null)
{
var typeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType);
await _contentManager.DiscardDraftAsync(contentItem);
_notifier.Success(string.IsNullOrWhiteSpace(typeDefinition.DisplayName)
? T["The draft has been removed."]
: T["The {0} draft has been removed.", typeDefinition.DisplayName]);
}
return Url.IsLocalUrl(returnUrl) ? (IActionResult)LocalRedirect(returnUrl) : RedirectToAction("List");
}
[HttpPost]
public async Task<IActionResult> Remove(string contentItemId, string returnUrl)
{
var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest);
if (!await _authorizationService.AuthorizeAsync(User, Permissions.DeleteContent, contentItem))
{
return Unauthorized();
}
if (contentItem != null)
{
var typeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType);
await _contentManager.RemoveAsync(contentItem);
_notifier.Success(string.IsNullOrWhiteSpace(typeDefinition.DisplayName)
? T["That content has been removed."]
: T["That {0} has been removed.", typeDefinition.DisplayName]);
}
return Url.IsLocalUrl(returnUrl) ? (IActionResult)LocalRedirect(returnUrl) : RedirectToAction("List");
}
[HttpPost]
public async Task<IActionResult> Publish(string contentItemId, string returnUrl)
{
var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest);
if (contentItem == null)
{
return NotFound();
}
if (!await _authorizationService.AuthorizeAsync(User, Permissions.PublishContent, contentItem))
{
return Unauthorized();
}
await _contentManager.PublishAsync(contentItem);
var typeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType);
if (string.IsNullOrEmpty(typeDefinition.DisplayName))
{
_notifier.Success(T["That content has been published."]);
}
else
{
_notifier.Success(T["That {0} has been published.", typeDefinition.DisplayName]);
}
return Url.IsLocalUrl(returnUrl) ? (IActionResult)LocalRedirect(returnUrl) : RedirectToAction("List");
}
[HttpPost]
public async Task<IActionResult> Unpublish(string contentItemId, string returnUrl)
{
var contentItem = await _contentManager.GetAsync(contentItemId, VersionOptions.Latest);
if (contentItem == null)
{
return NotFound();
}
if (!await _authorizationService.AuthorizeAsync(User, Permissions.PublishContent, contentItem))
{
return Unauthorized();
}
await _contentManager.UnpublishAsync(contentItem);
var typeDefinition = _contentDefinitionManager.GetTypeDefinition(contentItem.ContentType);
if (string.IsNullOrEmpty(typeDefinition.DisplayName))
{
_notifier.Success(T["The content has been unpublished."]);
}
else
{
_notifier.Success(T["The {0} has been unpublished.", typeDefinition.DisplayName]);
}
return Url.IsLocalUrl(returnUrl) ? (IActionResult)LocalRedirect(returnUrl) : RedirectToAction("List");
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System.Collections.Generic;
using System.Runtime;
// Base class for opcodes that produce the query's final result
abstract class ResultOpcode : Opcode
{
internal ResultOpcode(OpcodeID id)
: base(id)
{
this.flags |= OpcodeFlags.Result;
}
}
internal class MatchResultOpcode : ResultOpcode
{
internal MatchResultOpcode()
: base(OpcodeID.MatchResult)
{
}
internal override Opcode Eval(ProcessingContext context)
{
context.Processor.Result = this.IsSuccess(context);
context.PopFrame();
return this.next;
}
protected bool IsSuccess(ProcessingContext context)
{
StackFrame topFrame = context.TopArg;
if (1 == topFrame.Count)
{
return context.Values[topFrame.basePtr].ToBoolean();
}
else
{
context.Processor.Result = false;
for (int i = topFrame.basePtr; i <= topFrame.endPtr; ++i)
{
if (context.Values[i].ToBoolean())
{
return true;
}
}
}
return false;
}
}
internal class QueryResultOpcode : ResultOpcode
{
internal QueryResultOpcode()
: base(OpcodeID.QueryResult)
{
}
internal override Opcode Eval(ProcessingContext context)
{
StackFrame topFrame = context.TopArg;
ValueDataType resultType = context.Values[topFrame.basePtr].Type;
XPathResult result;
switch (resultType)
{
case ValueDataType.Sequence:
{
SafeNodeSequenceIterator value = new SafeNodeSequenceIterator(context.Values[topFrame.basePtr].GetSequence(), context);
result = new XPathResult(value);
}
break;
case ValueDataType.Boolean:
{
bool value = context.Values[topFrame.basePtr].GetBoolean();
result = new XPathResult(value);
}
break;
case ValueDataType.String:
{
string value = context.Values[topFrame.basePtr].GetString();
result = new XPathResult(value);
}
break;
case ValueDataType.Double:
{
double value = context.Values[topFrame.basePtr].GetDouble();
result = new XPathResult(value);
}
break;
default:
throw Fx.AssertAndThrow("Unexpected result type.");
}
context.Processor.QueryResult = result;
context.PopFrame();
return this.next;
}
}
internal abstract class MultipleResultOpcode : ResultOpcode
{
protected QueryBuffer<object> results;
internal MultipleResultOpcode(OpcodeID id)
: base(id)
{
this.flags |= OpcodeFlags.Multiple;
this.results = new QueryBuffer<object>(1);
}
internal override void Add(Opcode op)
{
MultipleResultOpcode results = op as MultipleResultOpcode;
if (null != results)
{
this.results.Add(ref results.results);
this.results.TrimToCount();
return;
}
base.Add(op);
}
public void AddItem(object item)
{
this.results.Add(item);
}
internal override void CollectXPathFilters(ICollection<MessageFilter> filters)
{
for (int i = 0; i < this.results.Count; ++i)
{
XPathMessageFilter filter = this.results[i] as XPathMessageFilter;
if (filter != null)
{
filters.Add(filter);
}
}
}
internal override bool Equals(Opcode op)
{
if (base.Equals(op))
{
return object.ReferenceEquals(this, op);
}
return false;
}
public void RemoveItem(object item)
{
this.results.Remove(item);
this.Remove();
}
internal override void Remove()
{
if (0 == this.results.Count)
{
base.Remove();
}
}
internal override void Trim()
{
this.results.TrimToCount();
}
}
internal class QueryMultipleResultOpcode : MultipleResultOpcode
{
internal QueryMultipleResultOpcode() : base(OpcodeID.QueryMultipleResult) { }
internal override Opcode Eval(ProcessingContext context)
{
Fx.Assert(this.results.Count > 0, "QueryMultipleQueryResultOpcode in the eval tree but no query present");
Fx.Assert(context.Processor.ResultSet != null, "QueryMultipleQueryResultOpcode should only be used in eval cases");
StackFrame topFrame = context.TopArg;
ValueDataType resultType = context.Values[topFrame.basePtr].Type;
XPathResult result;
switch (resultType)
{
case ValueDataType.Sequence:
{
SafeNodeSequenceIterator value = new SafeNodeSequenceIterator(context.Values[topFrame.basePtr].GetSequence(), context);
result = new XPathResult(value);
}
break;
case ValueDataType.Boolean:
{
bool value = context.Values[topFrame.basePtr].GetBoolean();
result = new XPathResult(value);
}
break;
case ValueDataType.String:
{
string value = context.Values[topFrame.basePtr].GetString();
result = new XPathResult(value);
}
break;
case ValueDataType.Double:
{
double value = context.Values[topFrame.basePtr].GetDouble();
result = new XPathResult(value);
}
break;
default:
throw Fx.AssertAndThrow("Unexpected result type.");
}
context.Processor.ResultSet.Add(new KeyValuePair<MessageQuery, XPathResult>((MessageQuery)this.results[0], result));
for (int i = 1; i < this.results.Count; i++)
{
context.Processor.ResultSet.Add(new KeyValuePair<MessageQuery, XPathResult>((MessageQuery)this.results[i], result.Copy()));
}
context.PopFrame();
return this.next;
}
}
internal class MatchMultipleResultOpcode : MultipleResultOpcode
{
internal MatchMultipleResultOpcode() : base(OpcodeID.MatchMultipleResult) { }
internal override Opcode Eval(ProcessingContext context)
{
StackFrame topFrame = context.TopArg;
bool match = false;
if (1 == topFrame.Count)
{
match = context.Values[topFrame.basePtr].ToBoolean();
}
else
{
context.Processor.Result = false;
for (int i = topFrame.basePtr; i <= topFrame.endPtr; ++i)
{
if (context.Values[i].ToBoolean())
{
match = true;
break;
}
}
}
if (match)
{
ICollection<MessageFilter> matches = context.Processor.MatchSet;
for (int i = 0, count = this.results.Count; i < count; ++i)
{
matches.Add((MessageFilter)this.results[i]);
}
}
context.PopFrame();
return this.next;
}
}
}
| |
// 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.
using System.Collections.Generic;
using Xunit;
namespace System.Text.Tests
{
public class UTF8EncodingDecode
{
public static IEnumerable<object[]> Decode_TestData()
{
// All ASCII chars
for (char c = char.MinValue; c <= 0x7F; c++)
{
yield return new object[] { new byte[] { (byte)c }, 0, 1, c.ToString() };
yield return new object[] { new byte[] { 97, (byte)c, 98 }, 1, 1, c.ToString() };
yield return new object[] { new byte[] { 97, (byte)c, 98 }, 0, 3, "a" + c.ToString() + "b" };
}
// Mixture of ASCII and Unicode
yield return new object[] { new byte[] { 70, 111, 111, 66, 65, 208, 128, 82 }, 0, 8, "FooBA\u0400R" };
yield return new object[] { new byte[] { 195, 128, 110, 105, 109, 97, 204, 128, 108 }, 0, 9, "\u00C0nima\u0300l" };
yield return new object[] { new byte[] { 84, 101, 115, 116, 240, 144, 181, 181, 84, 101, 115, 116 }, 0, 12, "Test\uD803\uDD75Test" };
yield return new object[] { new byte[] { 0, 84, 101, 10, 115, 116, 0, 9, 0, 84, 15, 101, 115, 116, 0 }, 0, 15, "\0Te\nst\0\t\0T\u000Fest\0" };
yield return new object[] { new byte[] { 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 181, 181 }, 0, 12, "\uD803\uDD75\uD803\uDD75\uD803\uDD75" };
yield return new object[] { new byte[] { 196, 176 }, 0, 2, "\u0130" };
yield return new object[] { new byte[] { 0x61, 0xCC, 0x8A }, 0, 3, "\u0061\u030A" };
yield return new object[] { new byte[] { 0xC2, 0xA4, 0xC3, 0x90, 0x61, 0x52, 0x7C, 0x7B, 0x41, 0x6E, 0x47, 0x65, 0xC2, 0xA3, 0xC2, 0xA4 }, 0, 16, "\u00A4\u00D0aR|{AnGe\u00A3\u00A4" };
yield return new object[] { new byte[] { 0x00, 0x7F }, 0, 2, "\u0000\u007F" };
yield return new object[] { new byte[] { 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F, 0x00, 0x7F }, 0, 14, "\u0000\u007F\u0000\u007F\u0000\u007F\u0000\u007F\u0000\u007F\u0000\u007F\u0000\u007F" };
yield return new object[] { new byte[] { 0xC2, 0x80, 0xDF, 0xBF }, 0, 4, "\u0080\u07FF" };
yield return new object[] { new byte[] { 0xC2, 0x80, 0xDF, 0xBF, 0xC2, 0x80, 0xDF, 0xBF, 0xC2, 0x80, 0xDF, 0xBF, 0xC2, 0x80, 0xDF, 0xBF }, 0, 16, "\u0080\u07FF\u0080\u07FF\u0080\u07FF\u0080\u07FF" };
yield return new object[] { new byte[] { 0xE0, 0xA0, 0x80, 0xE0, 0xBF, 0xBF }, 0, 6, "\u0800\u0FFF" };
yield return new object[] { new byte[] { 0xE0, 0xA0, 0x80, 0xE0, 0xBF, 0xBF, 0xE0, 0xA0, 0x80, 0xE0, 0xBF, 0xBF, 0xE0, 0xA0, 0x80, 0xE0, 0xBF, 0xBF }, 0, 18, "\u0800\u0FFF\u0800\u0FFF\u0800\u0FFF" };
yield return new object[] { new byte[] { 0xE1, 0x80, 0x80, 0xEC, 0xBF, 0xBF }, 0, 6, "\u1000\uCFFF" };
yield return new object[] { new byte[] { 0xE1, 0x80, 0x80, 0xEC, 0xBF, 0xBF, 0xE1, 0x80, 0x80, 0xEC, 0xBF, 0xBF, 0xE1, 0x80, 0x80, 0xEC, 0xBF, 0xBF }, 0, 18, "\u1000\uCFFF\u1000\uCFFF\u1000\uCFFF" };
yield return new object[] { new byte[] { 0xED, 0x80, 0x80, 0xED, 0x9F, 0xBF }, 0, 6, "\uD000\uD7FF" };
yield return new object[] { new byte[] { 0xED, 0x80, 0x80, 0xED, 0x9F, 0xBF, 0xED, 0x80, 0x80, 0xED, 0x9F, 0xBF, 0xED, 0x80, 0x80, 0xED, 0x9F, 0xBF }, 0, 18, "\uD000\uD7FF\uD000\uD7FF\uD000\uD7FF" };
yield return new object[] { new byte[] { 0xF0, 0x90, 0x80, 0x80, 0xF0, 0xBF, 0xBF, 0xBF }, 0, 8, "\uD800\uDC00\uD8BF\uDFFF" };
yield return new object[] { new byte[] { 0xF0, 0x90, 0x80, 0x80, 0xF0, 0xBF, 0xBF, 0xBF, 0xF0, 0x90, 0x80, 0x80, 0xF0, 0xBF, 0xBF, 0xBF }, 0, 16, "\uD800\uDC00\uD8BF\uDFFF\uD800\uDC00\uD8BF\uDFFF" };
yield return new object[] { new byte[] { 0xF1, 0x80, 0x80, 0x80, 0xF3, 0xBF, 0xBF, 0xBF }, 0, 8, "\uD8C0\uDC00\uDBBF\uDFFF" };
yield return new object[] { new byte[] { 0xF1, 0x80, 0x80, 0x80, 0xF3, 0xBF, 0xBF, 0xBF, 0xF1, 0x80, 0x80, 0x80, 0xF3, 0xBF, 0xBF, 0xBF }, 0, 16, "\uD8C0\uDC00\uDBBF\uDFFF\uD8C0\uDC00\uDBBF\uDFFF" };
yield return new object[] { new byte[] { 0xF4, 0x80, 0x80, 0x80, 0xF4, 0x8F, 0xBF, 0xBF }, 0, 8, "\uDBC0\uDC00\uDBFF\uDFFF" };
yield return new object[] { new byte[] { 0xF4, 0x80, 0x80, 0x80, 0xF4, 0x8F, 0xBF, 0xBF, 0xF4, 0x80, 0x80, 0x80, 0xF4, 0x8F, 0xBF, 0xBF }, 0, 16, "\uDBC0\uDC00\uDBFF\uDFFF\uDBC0\uDC00\uDBFF\uDFFF" };
// Long ASCII strings
yield return new object[] { new byte[] { 84, 101, 115, 116, 83, 116, 114, 105, 110, 103 }, 0, 10, "TestString" };
yield return new object[] { new byte[] { 84, 101, 115, 116, 84, 101, 115, 116 }, 0, 8, "TestTest" };
// Control codes
yield return new object[] { new byte[] { 0x1F, 0x10, 0x00, 0x09 }, 0, 4, "\u001F\u0010\u0000\u0009" };
yield return new object[] { new byte[] { 0x1F, 0x00, 0x10, 0x09 }, 0, 4, "\u001F\u0000\u0010\u0009" };
yield return new object[] { new byte[] { 0x00, 0x1F, 0x10, 0x09 }, 0, 4, "\u0000\u001F\u0010\u0009" };
// BOM
yield return new object[] { new byte[] { 0xEF, 0xBB, 0xBF, 0x41 }, 0, 4, "\uFEFF\u0041" };
// U+FDD0 - U+FDEF
yield return new object[] { new byte[] { 0xEF, 0xB7, 0x90, 0xEF, 0xB7, 0xAF }, 0, 6, "\uFDD0\uFDEF" };
// 2 byte encoding
yield return new object[] { new byte[] { 0xC3, 0xA1 }, 0, 2, "\u00E1" };
yield return new object[] { new byte[] { 0xC3, 0x85 }, 0, 2, "\u00C5" };
// 3 byte encoding
yield return new object[] { new byte[] { 0xE8, 0x80, 0x80 }, 0, 3, "\u8000" };
yield return new object[] { new byte[] { 0xE2, 0x84, 0xAB }, 0, 3, "\u212B" };
// Surrogate pairs
yield return new object[] { new byte[] { 240, 144, 128, 128 }, 0, 4, "\uD800\uDC00" };
yield return new object[] { new byte[] { 97, 240, 144, 128, 128, 98 }, 0, 6, "a\uD800\uDC00b" };
yield return new object[] { new byte[] { 0xF0, 0x90, 0x8F, 0xBF }, 0, 4, "\uD800\uDFFF" };
yield return new object[] { new byte[] { 0xF4, 0x8F, 0xB0, 0x80 }, 0, 4, "\uDBFF\uDC00" };
yield return new object[] { new byte[] { 0xF4, 0x8F, 0xBF, 0xBF }, 0, 4, "\uDBFF\uDFFF" };
yield return new object[] { new byte[] { 0xF3, 0xB0, 0x80, 0x80 }, 0, 4, "\uDB80\uDC00" };
// High BMP non-chars
yield return new object[] { new byte[] { 239, 191, 189 }, 0, 3, "\uFFFD" };
yield return new object[] { new byte[] { 239, 191, 190 }, 0, 3, "\uFFFE" };
yield return new object[] { new byte[] { 239, 191, 191 }, 0, 3, "\uFFFF" };
yield return new object[] { new byte[] { 0xEF, 0xBF, 0xAE }, 0, 3, "\uFFEE" };
yield return new object[] { new byte[] { 0xEE, 0x80, 0x80, 0xEF, 0xBF, 0xBF, 0xEE, 0x80, 0x80, 0xEF, 0xBF, 0xBF, 0xEE, 0x80, 0x80, 0xEF, 0xBF, 0xBF }, 0, 18, "\uE000\uFFFF\uE000\uFFFF\uE000\uFFFF" };
// Empty strings
yield return new object[] { new byte[0], 0, 0, string.Empty };
yield return new object[] { new byte[10], 10, 0, string.Empty };
yield return new object[] { new byte[10], 0, 0, string.Empty };
}
[Theory]
[MemberData(nameof(Decode_TestData))]
public void Decode(byte[] bytes, int index, int count, string expected)
{
EncodingHelpers.Decode(new UTF8Encoding(true, false), bytes, index, count, expected);
EncodingHelpers.Decode(new UTF8Encoding(false, false), bytes, index, count, expected);
EncodingHelpers.Decode(new UTF8Encoding(false, true), bytes, index, count, expected);
EncodingHelpers.Decode(new UTF8Encoding(true, true), bytes, index, count, expected);
}
public static IEnumerable<object[]> Decode_InvalidBytes_TestData()
{
yield return new object[] { new byte[] { 196, 84, 101, 115, 116, 196, 196, 196, 176, 176, 84, 101, 115, 116, 176 }, 0, 15, "\uFFFDTest\uFFFD\uFFFD\u0130\uFFFDTest\uFFFD" };
yield return new object[] { new byte[] { 240, 240, 144, 181, 181, 240, 144, 181, 181, 240, 144, 240 }, 0, 12, "\uFFFD\uD803\uDD75\uD803\uDD75\uFFFD\uFFFD" };
// Invalid surrogate bytes
byte[] validSurrogateBytes = new byte[] { 240, 144, 128, 128 };
yield return new object[] { validSurrogateBytes, 0, 3, "\uFFFD" };
yield return new object[] { validSurrogateBytes, 1, 3, "\uFFFD\uFFFD\uFFFD" };
yield return new object[] { validSurrogateBytes, 0, 2, "\uFFFD" };
yield return new object[] { validSurrogateBytes, 1, 2, "\uFFFD\uFFFD" };
yield return new object[] { validSurrogateBytes, 2, 2, "\uFFFD\uFFFD" };
yield return new object[] { validSurrogateBytes, 2, 1, "\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0xA0, 0x80 }, 0, 3, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0xAF, 0xBF }, 0, 3, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0xB0, 0x80 }, 0, 3, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0xBF, 0xBF }, 0, 3, "\uFFFD\uFFFD" };
// Invalid surrogate pair (low/low, high/high, low/high)
yield return new object[] { new byte[] { 0xED, 0xA0, 0x80, 0xED, 0xAF, 0xBF }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0xB0, 0x80, 0xED, 0xB0, 0x80 }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0xA0, 0x80, 0xED, 0xA0, 0x80 }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD" };
// Too high scalar value in surrogates
yield return new object[] { new byte[] { 0xED, 0xA0, 0x80, 0xEE, 0x80, 0x80 }, 0, 6, "\uFFFD\uFFFD\uE000" };
yield return new object[] { new byte[] { 0xF4, 0x90, 0x80, 0x80 }, 0, 4, "\uFFFD\uFFFD\uFFFD" };
// These are examples of overlong sequences. This can cause security
// vulnerabilities (e.g. MS00-078) so it is important we parse these as invalid.
yield return new object[] { new byte[] { 0xC0 }, 0, 1, "\uFFFD" };
yield return new object[] { new byte[] { 0xC0, 0xAF }, 0, 2, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xE0, 0x80, 0xBF }, 0, 3, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF0, 0x80, 0x80, 0xBF }, 0, 4, "\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF8, 0x80, 0x80, 0x80, 0xBF }, 0, 5, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xFC, 0x80, 0x80, 0x80, 0x80, 0xBF }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xC0, 0xBF }, 0, 2, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xE0, 0x9C, 0x90 }, 0, 3, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF0, 0x8F, 0xA4, 0x80 }, 0, 4, "\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xEF, 0x41 }, 0, 2, "\uFFFD\u0041" };
yield return new object[] { new byte[] { 0xEF, 0xBF, 0xAE }, 0, 1, "\uFFFD" };
yield return new object[] { new byte[] { 0xEF, 0xBF, 0x41 }, 0, 3, "\uFFFD\u0041" };
yield return new object[] { new byte[] { 0xEF, 0xBF, 0x61 }, 0, 3, "\uFFFD\u0061" };
yield return new object[] { new byte[] { 0xEF, 0xBF, 0xEF, 0xBF, 0xAE }, 0, 5, "\uFFFD\uFFEE" };
yield return new object[] { new byte[] { 0xEF, 0xBF, 0xC0, 0xBF }, 0, 4, "\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF0, 0xC4, 0x80 }, 0, 3, "\uFFFD\u0100" };
yield return new object[] { new byte[] { 176 }, 0, 1, "\uFFFD" };
yield return new object[] { new byte[] { 196 }, 0, 1, "\uFFFD" };
yield return new object[] { new byte[] { 0xA4, 0xD0, 0x61, 0x52, 0x7C, 0x7B, 0x41, 0x6E, 0x47, 0x65, 0xA3, 0xA4 }, 0, 12, "\uFFFD\uFFFD\u0061\u0052\u007C\u007B\u0041\u006E\u0047\u0065\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xA3 }, 0, 1, "\uFFFD" };
yield return new object[] { new byte[] { 0xA3, 0xA4 }, 0, 2, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0x65, 0xA3, 0xA4 }, 0, 3, "\u0065\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0x47, 0x65, 0xA3, 0xA4 }, 0, 4, "\u0047\u0065\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xA4, 0xD0, 0x61, 0xA3, 0xA4 }, 0, 5, "\uFFFD\uFFFD\u0061\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xA4, 0xD0, 0x61, 0xA3 }, 0, 4, "\uFFFD\uFFFD\u0061\uFFFD" };
yield return new object[] { new byte[] { 0xD0, 0x61, 0xA3 }, 0, 3, "\uFFFD\u0061\uFFFD" };
yield return new object[] { new byte[] { 0xA4, 0x61, 0xA3 }, 0, 3, "\uFFFD\u0061\uFFFD" };
yield return new object[] { new byte[] { 0xD0, 0x61, 0x52, 0xA3 }, 0, 4, "\uFFFD\u0061\u0052\uFFFD" };
yield return new object[] { new byte[] { 0xAA }, 0, 1, "\uFFFD" };
yield return new object[] { new byte[] { 0xAA, 0x41 }, 0, 2, "\uFFFD\u0041" };
yield return new object[] { new byte[] { 0xEF, 0xFF, 0xEE }, 0, 3, "\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xEF, 0xFF, 0xAE }, 0, 3, "\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0x80, 0x90, 0xA0, 0xB0, 0xC1 }, 0, 5, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x80, 0x90, 0xA0, 0xB0, 0xC1 }, 0, 15, "\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0x80, 0x90, 0xA0, 0xB0, 0xC1, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F }, 0, 15, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F\u007F" };
yield return new object[] { new byte[] { 0xC2, 0x7F, 0xC2, 0xC0, 0xDF, 0x7F, 0xDF, 0xC0 }, 0, 8, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xC2, 0xDF }, 0, 2, "\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0x80, 0x80, 0xC1, 0x80, 0xC1, 0xBF }, 0, 6, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xC2, 0x7F, 0xC2, 0xC0, 0x7F, 0x7F, 0x7F, 0x7F, 0xC3, 0xA1, 0xDF, 0x7F, 0xDF, 0xC0 }, 0, 14, "\uFFFD\u007F\uFFFD\uFFFD\u007F\u007F\u007F\u007F\u00E1\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xE0, 0xA0, 0x7F, 0xE0, 0xA0, 0xC0, 0xE0, 0xBF, 0x7F, 0xE0, 0xBF, 0xC0 }, 0, 12, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xE0, 0x9F, 0x80, 0xE0, 0xC0, 0x80, 0xE0, 0x9F, 0xBF, 0xE0, 0xC0, 0xBF }, 0, 12, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xE0, 0xA0, 0x7F, 0xE0, 0xA0, 0xC0, 0x7F, 0xE0, 0xBF, 0x7F, 0xC3, 0xA1, 0xE0, 0xBF, 0xC0 }, 0, 15, "\uFFFD\u007F\uFFFD\uFFFD\u007F\uFFFD\u007F\u00E1\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xE1, 0x80, 0x7F, 0xE1, 0x80, 0xC0, 0xE1, 0xBF, 0x7F, 0xE1, 0xBF, 0xC0, 0xEC, 0x80, 0x7F, 0xEC, 0x80, 0xC0, 0xEC, 0xBF, 0x7F, 0xEC, 0xBF, 0xC0 }, 0, 24, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xE1, 0x7F, 0x80, 0xE1, 0xC0, 0x80, 0xE1, 0x7F, 0xBF, 0xE1, 0xC0, 0xBF, 0xEC, 0x7F, 0x80, 0xEC, 0xC0, 0x80, 0xEC, 0x7F, 0xBF, 0xEC, 0xC0, 0xBF }, 0, 24, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0x80, 0x7F, 0xED, 0x80, 0xC0, 0xED, 0x9F, 0x7F, 0xED, 0x9F, 0xC0 }, 0, 12, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0x7F, 0x80, 0xED, 0xA0, 0x80, 0xED, 0x7F, 0xBF, 0xED, 0xA0, 0xBF }, 0, 12, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xED, 0x7F, 0x80, 0xED, 0xA0, 0x80, 0xE8, 0x80, 0x80, 0xED, 0x7F, 0xBF, 0xED, 0xA0, 0xBF }, 0, 15, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u8000\uFFFD\u007F\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xEE, 0x80, 0x7F, 0xEE, 0x80, 0xC0, 0xEE, 0xBF, 0x7F, 0xEE, 0xBF, 0xC0, 0xEF, 0x80, 0x7F, 0xEF, 0x80, 0xC0, 0xEF, 0xBF, 0x7F, 0xEF, 0xBF, 0xC0 }, 0, 24, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xEE, 0x7F, 0x80, 0xEE, 0xC0, 0x80, 0xEE, 0x7F, 0xBF, 0xEE, 0xC0, 0xBF, 0xEF, 0x7F, 0x80, 0xEF, 0xC0, 0x80, 0xEF, 0x7F, 0xBF, 0xEF, 0xC0, 0xBF }, 0, 24, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF0, 0x90, 0x80, 0x7F, 0xF0, 0x90, 0x80, 0xC0, 0xF0, 0xBF, 0xBF, 0x7F, 0xF0, 0xBF, 0xBF, 0xC0 }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF0, 0x90, 0x7F, 0x80, 0xF0, 0x90, 0xC0, 0x80, 0xF0, 0x90, 0x7F, 0xBF, 0xF0, 0x90, 0xC0, 0xBF }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF0, 0x8F, 0x80, 0x80, 0xF0, 0xC0, 0x80, 0x80, 0xF0, 0x8F, 0xBF, 0xBF, 0xF0, 0xC0, 0xBF, 0xBF }, 0, 16, "\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF1, 0x80, 0x80, 0x7F, 0xF1, 0x80, 0x80, 0xC0, 0xF1, 0xBF, 0xBF, 0x7F, 0xF1, 0xBF, 0xBF, 0xC0, 0xF3, 0x80, 0x80, 0x7F, 0xF3, 0x80, 0x80, 0xC0, 0xF3, 0xBF, 0xBF, 0x7F, 0xF3, 0xBF, 0xBF, 0xC0 }, 0, 32, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF1, 0x80, 0x7F, 0x80, 0xF1, 0x80, 0xC0, 0x80, 0xF1, 0x80, 0x7F, 0xBF, 0xF1, 0x80, 0xC0, 0xBF, 0xF3, 0x80, 0x7F, 0x80, 0xF3, 0x80, 0xC0, 0x80, 0xF3, 0x80, 0x7F, 0xBF, 0xF3, 0x80, 0xC0, 0xBF }, 0, 32, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF1, 0x7F, 0x80, 0x80, 0xF1, 0xC0, 0x80, 0x80, 0xF1, 0x7F, 0xBF, 0xBF, 0xF1, 0xC0, 0xBF, 0xBF, 0xF3, 0x7F, 0x80, 0x80, 0xF3, 0xC0, 0x80, 0x80, 0xF3, 0x7F, 0xBF, 0xBF, 0xF3, 0xC0, 0xBF, 0xBF }, 0, 32, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF4, 0x80, 0x80, 0x7F, 0xF4, 0x80, 0x80, 0xC0, 0xF4, 0x8F, 0xBF, 0x7F, 0xF4, 0x8F, 0xBF, 0xC0 }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF4, 0x80, 0x7F, 0x80, 0xF4, 0x80, 0xC0, 0x80, 0xF4, 0x80, 0x7F, 0xBF, 0xF4, 0x80, 0xC0, 0xBF }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD" };
yield return new object[] { new byte[] { 0xF4, 0x7F, 0x80, 0x80, 0xF4, 0x90, 0x80, 0x80, 0xF4, 0x7F, 0xBF, 0xBF, 0xF4, 0x90, 0xBF, 0xBF }, 0, 16, "\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD\u007F\uFFFD\uFFFD\uFFFD\uFFFD\uFFFD" };
}
[Theory]
[MemberData(nameof(Decode_InvalidBytes_TestData))]
public static void Decode_InvalidBytes(byte[] bytes, int index, int count, string expected)
{
EncodingHelpers.Decode(new UTF8Encoding(true, false), bytes, index, count, expected);
EncodingHelpers.Decode(new UTF8Encoding(false, false), bytes, index, count, expected);
NegativeEncodingTests.Decode_Invalid(new UTF8Encoding(false, true), bytes, index, count);
NegativeEncodingTests.Decode_Invalid(new UTF8Encoding(true, true), bytes, index, count);
}
}
}
| |
// StrangeCRC.cs - computes a crc used in the bziplib
//
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.
//
// 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 2
// 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, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace ICSharpCode.SharpZipLib.Checksums
{
/// <summary>
/// Bzip2 checksum algorithm
/// </summary>
public class StrangeCRC : IChecksum
{
readonly static uint[] crc32Table = {
0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9,
0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9,
0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011,
0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81,
0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49,
0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,
0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae,
0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,
0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066,
0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e,
0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,
0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686,
0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,
0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f,
0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47,
0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7,
0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f,
0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,
0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f,
0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,
0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30,
0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088,
0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,
0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0,
0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,
0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
};
int globalCrc;
/// <summary>
/// Initialise a default instance of <see cref="StrangeCRC"></see>
/// </summary>
public StrangeCRC()
{
Reset();
}
/// <summary>
/// Reset the state of Crc.
/// </summary>
public void Reset()
{
globalCrc = -1;
}
/// <summary>
/// Get the current Crc value.
/// </summary>
public long Value {
get {
return ~globalCrc;
}
}
/// <summary>
/// Update the Crc value.
/// </summary>
/// <param name="value">data update is based on</param>
public void Update(int value)
{
int temp = (globalCrc >> 24) ^ value;
if (temp < 0) {
temp = 256 + temp;
}
globalCrc = unchecked((int)((globalCrc << 8) ^ crc32Table[temp]));
}
/// <summary>
/// Update Crc based on a block of data
/// </summary>
/// <param name="buffer">The buffer containing data to update the crc with.</param>
public void Update(byte[] buffer)
{
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
Update(buffer, 0, buffer.Length);
}
/// <summary>
/// Update Crc based on a portion of a block of data
/// </summary>
/// <param name="buffer">block of data</param>
/// <param name="offset">index of first byte to use</param>
/// <param name="count">number of bytes to use</param>
public void Update(byte[] buffer, int offset, int count)
{
if (buffer == null) {
throw new ArgumentNullException("buffer");
}
if ( offset < 0 )
{
#if NETCF_1_0
throw new ArgumentOutOfRangeException("offset");
#else
throw new ArgumentOutOfRangeException("offset", "cannot be less than zero");
#endif
}
if ( count < 0 )
{
#if NETCF_1_0
throw new ArgumentOutOfRangeException("count");
#else
throw new ArgumentOutOfRangeException("count", "cannot be less than zero");
#endif
}
if ( offset + count > buffer.Length )
{
throw new ArgumentOutOfRangeException("count");
}
for (int i = 0; i < count; ++i) {
Update(buffer[offset++]);
}
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
//using ActiveWave.RfidDb;
using ActiveWave.Controls;
namespace ActiveWave.CarTracker
{
public class TagImageView : System.Windows.Forms.UserControl
{
//public event TagEventHandler TagTrackOn = null;
//public event TagEventHandler TagTrackOff = null;
//private RfidDbController m_rfid = RfidDbController.theRfidDbController;
//private IRfidTag m_tag = null;
private System.Windows.Forms.PictureBox m_picImage;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label m_lblLocation;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label m_lblTagId;
private ActiveWave.Controls.TitleBar m_titleBar;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
#region Constructor
public TagImageView()
{
InitializeComponent();
this.Tag = null;
//m_rfid.TagChanged += new RfidDb.TagEventHandler(OnTagChanged);
//m_rfid.TagRemoved += new RfidDb.TagEventHandler(OnTagRemoved);
}
#endregion
/*#region Properties
public new IRfidTag Tag
{
get { return m_tag; }
set
{
// Always reset tracking for now
m_chkTrack.Checked = false;
m_chkTrack.Enabled = (value != null);
m_tag = value;
RefreshTag();
}
}
#endregion*/
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(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.m_picImage = new System.Windows.Forms.PictureBox();
this.label1 = new System.Windows.Forms.Label();
this.m_lblLocation = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.m_lblTagId = new System.Windows.Forms.Label();
this.m_titleBar = new ActiveWave.Controls.TitleBar();
this.SuspendLayout();
//
// m_picImage
//
this.m_picImage.Location = new System.Drawing.Point(24, 72);
this.m_picImage.Name = "m_picImage";
this.m_picImage.Size = new System.Drawing.Size(160, 128);
this.m_picImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
this.m_picImage.TabIndex = 12;
this.m_picImage.TabStop = false;
//
// label1
//
this.label1.AutoSize = true;
this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label1.Location = new System.Drawing.Point(8, 32);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(41, 16);
this.label1.TabIndex = 13;
this.label1.Text = "Tag ID:";
//
// m_lblLocation
//
this.m_lblLocation.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.m_lblLocation.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.m_lblLocation.Location = new System.Drawing.Point(72, 48);
this.m_lblLocation.Name = "m_lblLocation";
this.m_lblLocation.Size = new System.Drawing.Size(128, 16);
this.m_lblLocation.TabIndex = 15;
this.m_lblLocation.Text = "location";
//
// label2
//
this.label2.AutoSize = true;
this.label2.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.label2.Location = new System.Drawing.Point(8, 48);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(50, 16);
this.label2.TabIndex = 16;
this.label2.Text = "Location:";
//
// m_lblTagId
//
this.m_lblTagId.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.m_lblTagId.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.m_lblTagId.Location = new System.Drawing.Point(72, 32);
this.m_lblTagId.Name = "m_lblTagId";
this.m_lblTagId.Size = new System.Drawing.Size(72, 16);
this.m_lblTagId.TabIndex = 19;
this.m_lblTagId.Text = "tagid";
//
// m_titleBar
//
this.m_titleBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.m_titleBar.BackColor = System.Drawing.Color.Navy;
this.m_titleBar.BorderColor = System.Drawing.Color.White;
this.m_titleBar.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.m_titleBar.ForeColor = System.Drawing.Color.White;
this.m_titleBar.GradientColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(0)), ((System.Byte)(192)));
this.m_titleBar.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical;
this.m_titleBar.Location = new System.Drawing.Point(0, 0);
this.m_titleBar.Name = "m_titleBar";
this.m_titleBar.ShadowColor = System.Drawing.Color.Black;
this.m_titleBar.ShadowOffset = new System.Drawing.Size(1, 1);
this.m_titleBar.Size = new System.Drawing.Size(208, 23);
this.m_titleBar.TabIndex = 0;
this.m_titleBar.Text = "Title";
//
// TagImageView
//
this.Controls.Add(this.m_titleBar);
this.Controls.Add(this.m_lblTagId);
this.Controls.Add(this.label2);
this.Controls.Add(this.m_lblLocation);
this.Controls.Add(this.label1);
this.Controls.Add(this.m_picImage);
this.Name = "TagImageView";
this.Size = new System.Drawing.Size(208, 208);
this.ResumeLayout(false);
}
#endregion
#region User events
private void Track_CheckedChanged(object sender, System.EventArgs e)
{
/*if (m_tag != null)
{
if (m_chkTrack.Checked && TagTrackOn != null)
TagTrackOn(m_tag);
if (!m_chkTrack.Checked && TagTrackOff != null)
TagTrackOff(m_tag);
}*/
}
#endregion
/*#region RFID events
private void OnTagChanged(IRfidTag tag)
{
if (m_tag == tag)
{
RefreshTag();
}
}
private void OnTagRemoved(IRfidTag tag)
{
if (m_tag == tag)
{
this.Tag = null;
}
}
#endregion */
private void RefreshTag()
{
/*if (m_tag != null)
{
IRfidReader reader = m_rfid.GetReader(m_tag.ReaderId);
m_titleBar.Text = m_tag.Name;
m_lblTagId.Text = m_tag.Id;
m_lblLocation.Text = (reader != null) ? reader.Name : string.Empty;
m_lblTimestamp.Text = (m_tag.Timestamp != DateTime.MinValue) ? m_tag.Timestamp.ToString("MM/dd/yyyy hh:mm:ss tt") : string.Empty;
m_picImage.Image = GetScaledImage(m_tag.Image);
}
else
{
m_titleBar.Text = string.Empty;
m_lblTagId.Text = string.Empty;
m_lblLocation.Text = string.Empty;
m_lblTimestamp.Text = string.Empty;
m_picImage.Image = null;
}
this.Visible = (m_tag != null);*/
}
private Image GetScaledImage(Image image)
{
if (image != null)
{
// Get image sized to picture box, but maintain aspect ratio
Size size = m_picImage.Size;
float ar1 = (float)size.Width / (float)size.Height;
float ar2 = (float)image.Width / (float)image.Height;
if (ar1 > ar2)
size.Width = Convert.ToInt32(size.Height * ar2);
else if (ar2 > ar1)
size.Height = Convert.ToInt32(size.Width / ar2);
return new Bitmap(image, size);
}
return null;
}
}
}
| |
// 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.
using System.Buffers;
using System.IO;
namespace System.Security.Cryptography
{
public abstract class HashAlgorithm : IDisposable, ICryptoTransform
{
private bool _disposed;
protected int HashSizeValue;
protected internal byte[] HashValue;
protected int State = 0;
protected HashAlgorithm() { }
public static HashAlgorithm Create() =>
CryptoConfigForwarder.CreateDefaultHashAlgorithm();
public static HashAlgorithm Create(string hashName) =>
(HashAlgorithm)CryptoConfigForwarder.CreateFromName(hashName);
public virtual int HashSize => HashSizeValue;
public virtual byte[] Hash
{
get
{
if (_disposed)
throw new ObjectDisposedException(null);
if (State != 0)
throw new CryptographicUnexpectedOperationException(SR.Cryptography_HashNotYetFinalized);
return (byte[])HashValue?.Clone();
}
}
public byte[] ComputeHash(byte[] buffer)
{
if (_disposed)
throw new ObjectDisposedException(null);
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
HashCore(buffer, 0, buffer.Length);
return CaptureHashCodeAndReinitialize();
}
public bool TryComputeHash(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten)
{
if (_disposed)
{
throw new ObjectDisposedException(null);
}
if (destination.Length < HashSizeValue/8)
{
bytesWritten = 0;
return false;
}
HashCore(source);
if (!TryHashFinal(destination, out bytesWritten))
{
// The only reason for failure should be that the destination isn't long enough,
// but we checked the size earlier.
throw new InvalidOperationException(SR.InvalidOperation_IncorrectImplementation);
}
HashValue = null;
Initialize();
return true;
}
public byte[] ComputeHash(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0 || (count > buffer.Length))
throw new ArgumentException(SR.Argument_InvalidValue);
if ((buffer.Length - count) < offset)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (_disposed)
throw new ObjectDisposedException(null);
HashCore(buffer, offset, count);
return CaptureHashCodeAndReinitialize();
}
public byte[] ComputeHash(Stream inputStream)
{
if (_disposed)
throw new ObjectDisposedException(null);
// Default the buffer size to 4K.
byte[] buffer = ArrayPool<byte>.Shared.Rent(4096);
try
{
int bytesRead;
while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
HashCore(buffer, 0, bytesRead);
}
return CaptureHashCodeAndReinitialize();
}
finally
{
CryptographicOperations.ZeroMemory(buffer);
ArrayPool<byte>.Shared.Return(buffer);
}
}
private byte[] CaptureHashCodeAndReinitialize()
{
HashValue = HashFinal();
// Clone the hash value prior to invoking Initialize in case the user-defined Initialize
// manipulates the array.
byte[] tmp = (byte[])HashValue.Clone();
Initialize();
return tmp;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Clear()
{
(this as IDisposable).Dispose();
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// Although we don't have any resources to dispose at this level,
// we need to continue to throw ObjectDisposedExceptions from CalculateHash
// for compatibility with the desktop framework.
_disposed = true;
}
return;
}
// ICryptoTransform methods
// We assume any HashAlgorithm can take input a byte at a time
public virtual int InputBlockSize => 1;
public virtual int OutputBlockSize => 1;
public virtual bool CanTransformMultipleBlocks => true;
public virtual bool CanReuseTransform => true;
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
ValidateTransformBlock(inputBuffer, inputOffset, inputCount);
// Change the State value
State = 1;
HashCore(inputBuffer, inputOffset, inputCount);
if ((outputBuffer != null) && ((inputBuffer != outputBuffer) || (inputOffset != outputOffset)))
{
// We let BlockCopy do the destination array validation
Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount);
}
return inputCount;
}
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
ValidateTransformBlock(inputBuffer, inputOffset, inputCount);
HashCore(inputBuffer, inputOffset, inputCount);
HashValue = CaptureHashCodeAndReinitialize();
byte[] outputBytes;
if (inputCount != 0)
{
outputBytes = new byte[inputCount];
Buffer.BlockCopy(inputBuffer, inputOffset, outputBytes, 0, inputCount);
}
else
{
outputBytes = Array.Empty<byte>();
}
// Reset the State value
State = 0;
return outputBytes;
}
private void ValidateTransformBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
if (inputBuffer == null)
throw new ArgumentNullException(nameof(inputBuffer));
if (inputOffset < 0)
throw new ArgumentOutOfRangeException(nameof(inputOffset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (inputCount < 0 || inputCount > inputBuffer.Length)
throw new ArgumentException(SR.Argument_InvalidValue);
if ((inputBuffer.Length - inputCount) < inputOffset)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (_disposed)
throw new ObjectDisposedException(null);
}
protected abstract void HashCore(byte[] array, int ibStart, int cbSize);
protected abstract byte[] HashFinal();
public abstract void Initialize();
protected virtual void HashCore(ReadOnlySpan<byte> source)
{
byte[] array = ArrayPool<byte>.Shared.Rent(source.Length);
try
{
source.CopyTo(array);
HashCore(array, 0, source.Length);
}
finally
{
Array.Clear(array, 0, source.Length);
ArrayPool<byte>.Shared.Return(array);
}
}
protected virtual bool TryHashFinal(Span<byte> destination, out int bytesWritten)
{
int hashSizeInBytes = HashSizeValue / 8;
if (destination.Length >= hashSizeInBytes)
{
byte[] final = HashFinal();
if (final.Length == hashSizeInBytes)
{
new ReadOnlySpan<byte>(final).CopyTo(destination);
bytesWritten = final.Length;
return true;
}
throw new InvalidOperationException(SR.InvalidOperation_IncorrectImplementation);
}
bytesWritten = 0;
return false;
}
}
}
| |
using System.Collections.Generic;
using JsonLD.Core;
using Newtonsoft.Json.Linq;
namespace JsonLD.Impl
{
internal class TurtleTripleCallback : IJSONLDTripleCallback
{
private const int MaxLineLength = 160;
private const int TabSpaces = 4;
private const string ColsKey = "..cols..";
private sealed class _Dictionary_32 : Dictionary<string, string>
{
public _Dictionary_32()
{
{
}
}
}
internal readonly IDictionary<string, string> availableNamespaces = new _Dictionary_32
();
internal ICollection<string> usedNamespaces;
public TurtleTripleCallback()
{
}
// this shouldn't be a
// valid iri/bnode i
// hope!
// TODO: fill with default namespaces
public virtual object Call(RDFDataset dataset)
{
foreach (KeyValuePair<string, string> e in dataset.GetNamespaces().GetEnumerableSelf
())
{
availableNamespaces[e.Value] = e.Key;
}
usedNamespaces = new HashSet<string>();
JObject refs = new JObject();
JObject ttl = new JObject();
foreach (string graphName in dataset.Keys)
{
string localGraphName = graphName;
IList<RDFDataset.Quad> triples = (IList<RDFDataset.Quad>)dataset.GetQuads(localGraphName);
if ("@default".Equals(localGraphName))
{
localGraphName = null;
}
// http://www.w3.org/TR/turtle/#unlabeled-bnodes
// TODO: implement nesting for unlabled nodes
// map of what the output should look like
// subj (or [ if bnode) > pred > obj
// > obj (set ref if IRI)
// > pred > obj (set ref if bnode)
// subj > etc etc etc
// subjid -> [ ref, ref, ref ]
string prevSubject = string.Empty;
string prevPredicate = string.Empty;
JObject thisSubject = null;
JArray thisPredicate = null;
foreach (RDFDataset.Quad triple in triples)
{
string subject = triple.GetSubject().GetValue();
string predicate = triple.GetPredicate().GetValue();
if (prevSubject.Equals(subject))
{
if (prevPredicate.Equals(predicate))
{
}
else
{
// nothing to do
// new predicate
if (thisSubject.ContainsKey(predicate))
{
thisPredicate = (JArray)thisSubject[predicate];
}
else
{
thisPredicate = new JArray();
thisSubject[predicate] = thisPredicate;
}
prevPredicate = predicate;
}
}
else
{
// new subject
if (ttl.ContainsKey(subject))
{
thisSubject = (JObject)ttl[subject];
}
else
{
thisSubject = new JObject();
ttl[subject] = thisSubject;
}
if (thisSubject.ContainsKey(predicate))
{
thisPredicate = (JArray)thisSubject[predicate];
}
else
{
thisPredicate = new JArray();
thisSubject[predicate] = thisPredicate;
}
prevSubject = subject;
prevPredicate = predicate;
}
if (triple.GetObject().IsLiteral())
{
thisPredicate.Add(triple.GetObject());
}
else
{
string o = triple.GetObject().GetValue();
if (o.StartsWith("_:"))
{
// add ref to o
if (!refs.ContainsKey(o))
{
refs[o] = new JArray();
}
((JArray)refs[o]).Add(thisPredicate);
}
thisPredicate.Add(o);
}
}
}
JObject collections = new JObject();
JArray subjects = new JArray(ttl.GetKeys());
// find collections
foreach (string subj in subjects)
{
JObject preds = (JObject)ttl[subj];
if (preds != null && preds.ContainsKey(JSONLDConsts.RdfFirst))
{
JArray col = new JArray();
collections[subj] = col;
while (true)
{
JArray first = (JArray)JsonLD.Collections.Remove(preds, JSONLDConsts.RdfFirst);
JToken o = first[0];
col.Add(o);
// refs
if (refs.ContainsKey((string)o))
{
((JArray)refs[(string)o]).Remove(first);
((JArray)refs[(string)o]).Add(col);
}
string next = (string)JsonLD.Collections.Remove(preds, JSONLDConsts.RdfRest)[0
];
if (JSONLDConsts.RdfNil.Equals(next))
{
// end of this list
break;
}
// if collections already contains a value for "next", add
// it to this col and break out
if (collections.ContainsKey(next))
{
JsonLD.Collections.AddAll(col, (JArray)JsonLD.Collections.Remove(collections, next));
break;
}
preds = (JObject)JsonLD.Collections.Remove(ttl, next);
JsonLD.Collections.Remove(refs, next);
}
}
}
// process refs (nesting referenced bnodes if only one reference to them
// in the whole graph)
foreach (string id in refs.GetKeys())
{
// skip items if there is more than one reference to them in the
// graph
if (((JArray)refs[id]).Count > 1)
{
continue;
}
// otherwise embed them into the referenced location
JToken @object = JsonLD.Collections.Remove(ttl, id);
if (collections.ContainsKey(id))
{
@object = new JObject();
JArray tmp = new JArray();
tmp.Add(JsonLD.Collections.Remove(collections, id));
((JObject)@object)[ColsKey] = tmp;
}
JArray predicate = (JArray)refs[id][0];
// replace the one bnode ref with the object
predicate[predicate.LastIndexOf(id)] = (JToken)@object;
}
// replace the rest of the collections
foreach (string id_1 in collections.GetKeys())
{
JObject subj_1 = (JObject)ttl[id_1];
if (!subj_1.ContainsKey(ColsKey))
{
subj_1[ColsKey] = new JArray();
}
((JArray)subj_1[ColsKey]).Add(collections[id_1]);
}
// build turtle output
string output = GenerateTurtle(ttl, 0, 0, false);
string prefixes = string.Empty;
foreach (string prefix in usedNamespaces)
{
string name = availableNamespaces[prefix];
prefixes += "@prefix " + name + ": <" + prefix + "> .\n";
}
return (string.Empty.Equals(prefixes) ? string.Empty : prefixes + "\n") + output;
}
private string GenerateObject(object @object, string sep, bool hasNext, int indentation
, int lineLength)
{
string rval = string.Empty;
string obj;
if (@object is string)
{
obj = GetURI((string)@object);
}
else
{
if (@object is RDFDataset.Literal)
{
obj = ((RDFDataset.Literal)@object).GetValue();
string lang = ((RDFDataset.Literal)@object).GetLanguage();
string dt = ((RDFDataset.Literal)@object).GetDatatype();
if (lang != null)
{
obj = "\"" + obj + "\"";
obj += "@" + lang;
}
else
{
if (dt != null)
{
// TODO: this probably isn't an exclusive list of all the
// datatype literals that can be represented as native types
if (!(JSONLDConsts.XsdDouble.Equals(dt) || JSONLDConsts.XsdInteger.Equals(dt) ||
JSONLDConsts.XsdFloat.Equals(dt) || JSONLDConsts.XsdBoolean.Equals(dt)))
{
obj = "\"" + obj + "\"";
if (!JSONLDConsts.XsdString.Equals(dt))
{
obj += "^^" + GetURI(dt);
}
}
}
else
{
obj = "\"" + obj + "\"";
}
}
}
else
{
// must be an object
JObject tmp = new JObject();
tmp["_:x"] = (JObject)@object;
obj = GenerateTurtle(tmp, indentation + 1, lineLength, true);
}
}
int idxofcr = obj.IndexOf("\n");
// check if output will fix in the max line length (factor in comma if
// not the last item, current line length and length to the next CR)
if ((hasNext ? 1 : 0) + lineLength + (idxofcr != -1 ? idxofcr : obj.Length) > MaxLineLength)
{
rval += "\n" + Tabs(indentation + 1);
lineLength = (indentation + 1) * TabSpaces;
}
rval += obj;
if (idxofcr != -1)
{
lineLength += (obj.Length - obj.LastIndexOf("\n"));
}
else
{
lineLength += obj.Length;
}
if (hasNext)
{
rval += sep;
lineLength += sep.Length;
if (lineLength < MaxLineLength)
{
rval += " ";
lineLength++;
}
else
{
rval += "\n";
}
}
return rval;
}
private string GenerateTurtle(JObject ttl, int indentation, int lineLength, bool isObject)
{
string rval = string.Empty;
IEnumerator<string> subjIter = ttl.GetKeys().GetEnumerator();
while (subjIter.MoveNext())
{
string subject = subjIter.Current;
JObject subjval = (JObject)ttl[subject];
// boolean isBlankNode = subject.startsWith("_:");
bool hasOpenBnodeBracket = false;
if (subject.StartsWith("_:"))
{
// only open blank node bracket the node doesn't contain any
// collections
if (!subjval.ContainsKey(ColsKey))
{
rval += "[ ";
lineLength += 2;
hasOpenBnodeBracket = true;
}
// TODO: according to http://www.rdfabout.com/demo/validator/
// 1) collections as objects cannot contain any predicates other
// than rdf:first and rdf:rest
// 2) collections cannot be surrounded with [ ]
// check for collection
if (subjval.ContainsKey(ColsKey))
{
JArray collections = (JArray)JsonLD.Collections.Remove(subjval, ColsKey);
foreach (JToken collection in collections)
{
rval += "( ";
lineLength += 2;
IEnumerator<JToken> objIter = ((JArray)collection).Children().GetEnumerator();
while (objIter.MoveNext())
{
JToken @object = objIter.Current;
rval += GenerateObject(@object, string.Empty, objIter.MoveNext(), indentation, lineLength
);
lineLength = rval.Length - rval.LastIndexOf("\n");
}
rval += " ) ";
lineLength += 3;
}
}
}
else
{
// check for blank node
rval += GetURI(subject) + " ";
lineLength += subject.Length + 1;
}
IEnumerator<string> predIter = ttl[subject].GetKeys().GetEnumerator();
while (predIter.MoveNext())
{
string predicate = predIter.Current;
rval += GetURI(predicate) + " ";
lineLength += predicate.Length + 1;
IEnumerator<JToken> objIter = ((JArray)ttl[subject][predicate]).Children().GetEnumerator();
while (objIter.MoveNext())
{
JToken @object = objIter.Current;
rval += GenerateObject(@object, ",", objIter.MoveNext(), indentation, lineLength);
lineLength = rval.Length - rval.LastIndexOf("\n");
}
if (predIter.MoveNext())
{
rval += " ;\n" + Tabs(indentation + 1);
lineLength = (indentation + 1) * TabSpaces;
}
}
if (hasOpenBnodeBracket)
{
rval += " ]";
}
if (!isObject)
{
rval += " .\n";
if (subjIter.MoveNext())
{
// add blank space if we have another
// object below this
rval += "\n";
}
}
}
return rval;
}
// TODO: Assert (TAB_SPACES == 4) otherwise this needs to be edited, and
// should fail to compile
private string Tabs(int tabs)
{
string rval = string.Empty;
for (int i = 0; i < tabs; i++)
{
rval += " ";
}
// using spaces for tabs
return rval;
}
/// <summary>
/// checks the URI for a prefix, and if one is found, set used prefixes to
/// true
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
private string GetURI(string uri)
{
// check for bnode
if (uri.StartsWith("_:"))
{
// return the bnode id
return uri;
}
foreach (string prefix in availableNamespaces.Keys)
{
if (uri.StartsWith(prefix))
{
usedNamespaces.Add(prefix);
// return the prefixed URI
return availableNamespaces[prefix] + ":" + JsonLD.JavaCompat.Substring(uri, prefix.
Length);
}
}
// return the full URI
return "<" + uri + ">";
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Hyak.Common;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.AzureStack.Management
{
/// <summary>
/// Operations for delegated provider configuration. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for
/// more information)
/// </summary>
internal partial class DelegatedProviderConfigurationOperations : IServiceOperations<AzureStackClient>, IDelegatedProviderConfigurationOperations
{
/// <summary>
/// Initializes a new instance of the
/// DelegatedProviderConfigurationOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DelegatedProviderConfigurationOperations(AzureStackClient client)
{
this._client = client;
}
private AzureStackClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.AzureStack.Management.AzureStackClient.
/// </summary>
public AzureStackClient Client
{
get { return this._client; }
}
/// <summary>
/// Create or update delegated provider configuration. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='parameters'>
/// Required. The create or update result of delegated provider
/// configuration operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The create or update result of delegated provider configuration
/// operation.
/// </returns>
public async Task<DelegatedProviderConfigurationOperationsCreateOrUpdateResult> CreateOrUpdateAsync(DelegatedProviderConfigurationOperationsCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.DelegatedProviderConfiguration == null)
{
throw new ArgumentNullException("parameters.DelegatedProviderConfiguration");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.Subscriptions/configurations/default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject delegatedProviderConfigurationOperationsCreateOrUpdateParametersValue = new JObject();
requestDoc = delegatedProviderConfigurationOperationsCreateOrUpdateParametersValue;
if (parameters.DelegatedProviderConfiguration.Name != null)
{
delegatedProviderConfigurationOperationsCreateOrUpdateParametersValue["name"] = parameters.DelegatedProviderConfiguration.Name;
}
if (parameters.DelegatedProviderConfiguration.ProviderIdentifier != null)
{
delegatedProviderConfigurationOperationsCreateOrUpdateParametersValue["providerIdentifier"] = parameters.DelegatedProviderConfiguration.ProviderIdentifier;
}
if (parameters.DelegatedProviderConfiguration.DisplayName != null)
{
delegatedProviderConfigurationOperationsCreateOrUpdateParametersValue["displayName"] = parameters.DelegatedProviderConfiguration.DisplayName;
}
if (parameters.DelegatedProviderConfiguration.ExternalReferenceId != null)
{
delegatedProviderConfigurationOperationsCreateOrUpdateParametersValue["externalReferenceId"] = parameters.DelegatedProviderConfiguration.ExternalReferenceId;
}
if (parameters.DelegatedProviderConfiguration.SubscriptionApprovalEndpoint != null)
{
JObject subscriptionApprovalEndpointValue = new JObject();
delegatedProviderConfigurationOperationsCreateOrUpdateParametersValue["subscriptionApprovalEndpoint"] = subscriptionApprovalEndpointValue;
if (parameters.DelegatedProviderConfiguration.SubscriptionApprovalEndpoint.ApiVersion != null)
{
subscriptionApprovalEndpointValue["apiVersion"] = parameters.DelegatedProviderConfiguration.SubscriptionApprovalEndpoint.ApiVersion;
}
if (parameters.DelegatedProviderConfiguration.SubscriptionApprovalEndpoint.Enabled != null)
{
subscriptionApprovalEndpointValue["enabled"] = parameters.DelegatedProviderConfiguration.SubscriptionApprovalEndpoint.Enabled.Value;
}
if (parameters.DelegatedProviderConfiguration.SubscriptionApprovalEndpoint.EndpointUri != null)
{
subscriptionApprovalEndpointValue["endpointUri"] = parameters.DelegatedProviderConfiguration.SubscriptionApprovalEndpoint.EndpointUri;
}
subscriptionApprovalEndpointValue["timeout"] = XmlConvert.ToString(parameters.DelegatedProviderConfiguration.SubscriptionApprovalEndpoint.Timeout);
if (parameters.DelegatedProviderConfiguration.SubscriptionApprovalEndpoint.AuthenticationUsername != null)
{
subscriptionApprovalEndpointValue["authenticationUsername"] = parameters.DelegatedProviderConfiguration.SubscriptionApprovalEndpoint.AuthenticationUsername;
}
if (parameters.DelegatedProviderConfiguration.SubscriptionApprovalEndpoint.AuthenticationPassword != null)
{
subscriptionApprovalEndpointValue["authenticationPassword"] = parameters.DelegatedProviderConfiguration.SubscriptionApprovalEndpoint.AuthenticationPassword;
}
}
if (parameters.DelegatedProviderConfiguration.PricingEndpoint != null)
{
JObject pricingEndpointValue = new JObject();
delegatedProviderConfigurationOperationsCreateOrUpdateParametersValue["pricingEndpoint"] = pricingEndpointValue;
if (parameters.DelegatedProviderConfiguration.PricingEndpoint.ApiVersion != null)
{
pricingEndpointValue["apiVersion"] = parameters.DelegatedProviderConfiguration.PricingEndpoint.ApiVersion;
}
if (parameters.DelegatedProviderConfiguration.PricingEndpoint.Enabled != null)
{
pricingEndpointValue["enabled"] = parameters.DelegatedProviderConfiguration.PricingEndpoint.Enabled.Value;
}
if (parameters.DelegatedProviderConfiguration.PricingEndpoint.EndpointUri != null)
{
pricingEndpointValue["endpointUri"] = parameters.DelegatedProviderConfiguration.PricingEndpoint.EndpointUri;
}
pricingEndpointValue["timeout"] = XmlConvert.ToString(parameters.DelegatedProviderConfiguration.PricingEndpoint.Timeout);
if (parameters.DelegatedProviderConfiguration.PricingEndpoint.AuthenticationUsername != null)
{
pricingEndpointValue["authenticationUsername"] = parameters.DelegatedProviderConfiguration.PricingEndpoint.AuthenticationUsername;
}
if (parameters.DelegatedProviderConfiguration.PricingEndpoint.AuthenticationPassword != null)
{
pricingEndpointValue["authenticationPassword"] = parameters.DelegatedProviderConfiguration.PricingEndpoint.AuthenticationPassword;
}
}
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DelegatedProviderConfigurationOperationsCreateOrUpdateResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DelegatedProviderConfigurationOperationsCreateOrUpdateResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DelegatedProviderConfigurationDefinition delegatedProviderConfigurationInstance = new DelegatedProviderConfigurationDefinition();
result.DelegatedProviderConfiguration = delegatedProviderConfigurationInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
delegatedProviderConfigurationInstance.Name = nameInstance;
}
JToken providerIdentifierValue = responseDoc["providerIdentifier"];
if (providerIdentifierValue != null && providerIdentifierValue.Type != JTokenType.Null)
{
string providerIdentifierInstance = ((string)providerIdentifierValue);
delegatedProviderConfigurationInstance.ProviderIdentifier = providerIdentifierInstance;
}
JToken displayNameValue = responseDoc["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
delegatedProviderConfigurationInstance.DisplayName = displayNameInstance;
}
JToken externalReferenceIdValue = responseDoc["externalReferenceId"];
if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null)
{
string externalReferenceIdInstance = ((string)externalReferenceIdValue);
delegatedProviderConfigurationInstance.ExternalReferenceId = externalReferenceIdInstance;
}
JToken subscriptionApprovalEndpointValue2 = responseDoc["subscriptionApprovalEndpoint"];
if (subscriptionApprovalEndpointValue2 != null && subscriptionApprovalEndpointValue2.Type != JTokenType.Null)
{
ResourceProviderEndpoint subscriptionApprovalEndpointInstance = new ResourceProviderEndpoint();
delegatedProviderConfigurationInstance.SubscriptionApprovalEndpoint = subscriptionApprovalEndpointInstance;
JToken apiVersionValue = subscriptionApprovalEndpointValue2["apiVersion"];
if (apiVersionValue != null && apiVersionValue.Type != JTokenType.Null)
{
string apiVersionInstance = ((string)apiVersionValue);
subscriptionApprovalEndpointInstance.ApiVersion = apiVersionInstance;
}
JToken enabledValue = subscriptionApprovalEndpointValue2["enabled"];
if (enabledValue != null && enabledValue.Type != JTokenType.Null)
{
bool enabledInstance = ((bool)enabledValue);
subscriptionApprovalEndpointInstance.Enabled = enabledInstance;
}
JToken endpointUriValue = subscriptionApprovalEndpointValue2["endpointUri"];
if (endpointUriValue != null && endpointUriValue.Type != JTokenType.Null)
{
string endpointUriInstance = ((string)endpointUriValue);
subscriptionApprovalEndpointInstance.EndpointUri = endpointUriInstance;
}
JToken timeoutValue = subscriptionApprovalEndpointValue2["timeout"];
if (timeoutValue != null && timeoutValue.Type != JTokenType.Null)
{
TimeSpan timeoutInstance = XmlConvert.ToTimeSpan(((string)timeoutValue));
subscriptionApprovalEndpointInstance.Timeout = timeoutInstance;
}
JToken authenticationUsernameValue = subscriptionApprovalEndpointValue2["authenticationUsername"];
if (authenticationUsernameValue != null && authenticationUsernameValue.Type != JTokenType.Null)
{
string authenticationUsernameInstance = ((string)authenticationUsernameValue);
subscriptionApprovalEndpointInstance.AuthenticationUsername = authenticationUsernameInstance;
}
JToken authenticationPasswordValue = subscriptionApprovalEndpointValue2["authenticationPassword"];
if (authenticationPasswordValue != null && authenticationPasswordValue.Type != JTokenType.Null)
{
string authenticationPasswordInstance = ((string)authenticationPasswordValue);
subscriptionApprovalEndpointInstance.AuthenticationPassword = authenticationPasswordInstance;
}
}
JToken pricingEndpointValue2 = responseDoc["pricingEndpoint"];
if (pricingEndpointValue2 != null && pricingEndpointValue2.Type != JTokenType.Null)
{
ResourceProviderEndpoint pricingEndpointInstance = new ResourceProviderEndpoint();
delegatedProviderConfigurationInstance.PricingEndpoint = pricingEndpointInstance;
JToken apiVersionValue2 = pricingEndpointValue2["apiVersion"];
if (apiVersionValue2 != null && apiVersionValue2.Type != JTokenType.Null)
{
string apiVersionInstance2 = ((string)apiVersionValue2);
pricingEndpointInstance.ApiVersion = apiVersionInstance2;
}
JToken enabledValue2 = pricingEndpointValue2["enabled"];
if (enabledValue2 != null && enabledValue2.Type != JTokenType.Null)
{
bool enabledInstance2 = ((bool)enabledValue2);
pricingEndpointInstance.Enabled = enabledInstance2;
}
JToken endpointUriValue2 = pricingEndpointValue2["endpointUri"];
if (endpointUriValue2 != null && endpointUriValue2.Type != JTokenType.Null)
{
string endpointUriInstance2 = ((string)endpointUriValue2);
pricingEndpointInstance.EndpointUri = endpointUriInstance2;
}
JToken timeoutValue2 = pricingEndpointValue2["timeout"];
if (timeoutValue2 != null && timeoutValue2.Type != JTokenType.Null)
{
TimeSpan timeoutInstance2 = XmlConvert.ToTimeSpan(((string)timeoutValue2));
pricingEndpointInstance.Timeout = timeoutInstance2;
}
JToken authenticationUsernameValue2 = pricingEndpointValue2["authenticationUsername"];
if (authenticationUsernameValue2 != null && authenticationUsernameValue2.Type != JTokenType.Null)
{
string authenticationUsernameInstance2 = ((string)authenticationUsernameValue2);
pricingEndpointInstance.AuthenticationUsername = authenticationUsernameInstance2;
}
JToken authenticationPasswordValue2 = pricingEndpointValue2["authenticationPassword"];
if (authenticationPasswordValue2 != null && authenticationPasswordValue2.Type != JTokenType.Null)
{
string authenticationPasswordInstance2 = ((string)authenticationPasswordValue2);
pricingEndpointInstance.AuthenticationPassword = authenticationPasswordInstance2;
}
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Get the configuration for the provider. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx
/// for more information)
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The get result for delegated provider configuration.
/// </returns>
public async Task<DelegatedProviderConfigurationGetResult> GetAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.Subscriptions/configurations/default";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion));
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DelegatedProviderConfigurationGetResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DelegatedProviderConfigurationGetResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DelegatedProviderConfigurationDefinition configurationInstance = new DelegatedProviderConfigurationDefinition();
result.Configuration = configurationInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
configurationInstance.Name = nameInstance;
}
JToken providerIdentifierValue = responseDoc["providerIdentifier"];
if (providerIdentifierValue != null && providerIdentifierValue.Type != JTokenType.Null)
{
string providerIdentifierInstance = ((string)providerIdentifierValue);
configurationInstance.ProviderIdentifier = providerIdentifierInstance;
}
JToken displayNameValue = responseDoc["displayName"];
if (displayNameValue != null && displayNameValue.Type != JTokenType.Null)
{
string displayNameInstance = ((string)displayNameValue);
configurationInstance.DisplayName = displayNameInstance;
}
JToken externalReferenceIdValue = responseDoc["externalReferenceId"];
if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null)
{
string externalReferenceIdInstance = ((string)externalReferenceIdValue);
configurationInstance.ExternalReferenceId = externalReferenceIdInstance;
}
JToken subscriptionApprovalEndpointValue = responseDoc["subscriptionApprovalEndpoint"];
if (subscriptionApprovalEndpointValue != null && subscriptionApprovalEndpointValue.Type != JTokenType.Null)
{
ResourceProviderEndpoint subscriptionApprovalEndpointInstance = new ResourceProviderEndpoint();
configurationInstance.SubscriptionApprovalEndpoint = subscriptionApprovalEndpointInstance;
JToken apiVersionValue = subscriptionApprovalEndpointValue["apiVersion"];
if (apiVersionValue != null && apiVersionValue.Type != JTokenType.Null)
{
string apiVersionInstance = ((string)apiVersionValue);
subscriptionApprovalEndpointInstance.ApiVersion = apiVersionInstance;
}
JToken enabledValue = subscriptionApprovalEndpointValue["enabled"];
if (enabledValue != null && enabledValue.Type != JTokenType.Null)
{
bool enabledInstance = ((bool)enabledValue);
subscriptionApprovalEndpointInstance.Enabled = enabledInstance;
}
JToken endpointUriValue = subscriptionApprovalEndpointValue["endpointUri"];
if (endpointUriValue != null && endpointUriValue.Type != JTokenType.Null)
{
string endpointUriInstance = ((string)endpointUriValue);
subscriptionApprovalEndpointInstance.EndpointUri = endpointUriInstance;
}
JToken timeoutValue = subscriptionApprovalEndpointValue["timeout"];
if (timeoutValue != null && timeoutValue.Type != JTokenType.Null)
{
TimeSpan timeoutInstance = XmlConvert.ToTimeSpan(((string)timeoutValue));
subscriptionApprovalEndpointInstance.Timeout = timeoutInstance;
}
JToken authenticationUsernameValue = subscriptionApprovalEndpointValue["authenticationUsername"];
if (authenticationUsernameValue != null && authenticationUsernameValue.Type != JTokenType.Null)
{
string authenticationUsernameInstance = ((string)authenticationUsernameValue);
subscriptionApprovalEndpointInstance.AuthenticationUsername = authenticationUsernameInstance;
}
JToken authenticationPasswordValue = subscriptionApprovalEndpointValue["authenticationPassword"];
if (authenticationPasswordValue != null && authenticationPasswordValue.Type != JTokenType.Null)
{
string authenticationPasswordInstance = ((string)authenticationPasswordValue);
subscriptionApprovalEndpointInstance.AuthenticationPassword = authenticationPasswordInstance;
}
}
JToken pricingEndpointValue = responseDoc["pricingEndpoint"];
if (pricingEndpointValue != null && pricingEndpointValue.Type != JTokenType.Null)
{
ResourceProviderEndpoint pricingEndpointInstance = new ResourceProviderEndpoint();
configurationInstance.PricingEndpoint = pricingEndpointInstance;
JToken apiVersionValue2 = pricingEndpointValue["apiVersion"];
if (apiVersionValue2 != null && apiVersionValue2.Type != JTokenType.Null)
{
string apiVersionInstance2 = ((string)apiVersionValue2);
pricingEndpointInstance.ApiVersion = apiVersionInstance2;
}
JToken enabledValue2 = pricingEndpointValue["enabled"];
if (enabledValue2 != null && enabledValue2.Type != JTokenType.Null)
{
bool enabledInstance2 = ((bool)enabledValue2);
pricingEndpointInstance.Enabled = enabledInstance2;
}
JToken endpointUriValue2 = pricingEndpointValue["endpointUri"];
if (endpointUriValue2 != null && endpointUriValue2.Type != JTokenType.Null)
{
string endpointUriInstance2 = ((string)endpointUriValue2);
pricingEndpointInstance.EndpointUri = endpointUriInstance2;
}
JToken timeoutValue2 = pricingEndpointValue["timeout"];
if (timeoutValue2 != null && timeoutValue2.Type != JTokenType.Null)
{
TimeSpan timeoutInstance2 = XmlConvert.ToTimeSpan(((string)timeoutValue2));
pricingEndpointInstance.Timeout = timeoutInstance2;
}
JToken authenticationUsernameValue2 = pricingEndpointValue["authenticationUsername"];
if (authenticationUsernameValue2 != null && authenticationUsernameValue2.Type != JTokenType.Null)
{
string authenticationUsernameInstance2 = ((string)authenticationUsernameValue2);
pricingEndpointInstance.AuthenticationUsername = authenticationUsernameInstance2;
}
JToken authenticationPasswordValue2 = pricingEndpointValue["authenticationPassword"];
if (authenticationPasswordValue2 != null && authenticationPasswordValue2.Type != JTokenType.Null)
{
string authenticationPasswordInstance2 = ((string)authenticationPasswordValue2);
pricingEndpointInstance.AuthenticationPassword = authenticationPasswordInstance2;
}
}
}
}
result.StatusCode = statusCode;
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// [AUTO_HEADER]
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace BaseIMEUI
{
public partial class BIStatusBarForm
{
private void PaintToolStrip(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
int rightBorder = this.u_toolStrip.Width - 3;
Rectangle rect = new Rectangle(0, 0,
this.u_toolStrip.Width - 1, this.u_toolStrip.Height - 2);
using (Region tooltipRegion = new Region(rect))
{
this.u_toolStrip.Region = tooltipRegion;
}
Pen blackPen = new Pen(Color.Black);
Pen grayPen = new Pen(Color.Gray);
g.DrawLine(blackPen, new Point(rightBorder, 0),
new Point(rightBorder, this.u_toolStrip.Height));
g.DrawLine(blackPen, new Point(0, 0),
new Point(0, this.u_toolStrip.Height));
g.DrawLine(grayPen, new Point(1, 0),
new Point(1, this.u_toolStrip.Height));
blackPen.Dispose();
grayPen.Dispose();
}
/// <summary>
/// Paint the appearance of the status bar in the mini mode.
/// </summary>
/// <param name="e"></param>
private void PaintMiniMode(PaintEventArgs e)
{
Graphics g = e.Graphics;
this.u_toolStrip.Visible = false;
Size windowSize = new Size(this.u_toolStrip.Size.Width + this.u_toolStrip.Left + 10, this.u_toolStrip.Size.Height - 2);
this.m_windowRect = new Rectangle(new Point(0, 0), windowSize);
Rectangle windowRect = new Rectangle(0, 0, 64, windowSize.Height);
Rectangle outside = windowRect;
outside.Height += 1;
outside.Width += 1;
Region windowRegion = new Region(outside);
this.Region = windowRegion;
windowRegion.Dispose();
// Paint the header of the status bar with a Yahoo! logo.
g.DrawImage(this.m_barhead, 0, 0, 36, outside.Height);
BIServerConnector callback = BIServerConnector.SharedInstance;
if (callback != null)
{
// If we are now in the Alphanumeric mode, the icon on the status bar
// in the mini mode should be a icon title "EN", otherwise, it should
// be the icon of the current Chinese Input Method.
Image i;
if (callback.isAlphanumericMode())
i = this.u_toggleAlphanumericMode.Image;
else
i = this.u_toggleInputMethod.Image;
g.DrawImage(i, 40, 3, 20, 20);
}
Pen blackPen = new Pen(Color.Black);
g.DrawRectangle(blackPen, windowRect);
g.DrawLine(blackPen, new Point(36, 0), new Point(36, this.Height));
blackPen.Dispose();
}
/// <summary>
/// Paint the appearance of the status bar in the normal mode.
/// </summary>
/// <param name="e"></param>
private void PaintNormalMode(PaintEventArgs e)
{
Graphics g = e.Graphics;
this.u_toolStrip.Visible = true;
Size windowSize = new Size(this.u_toolStrip.Size.Width + this.u_toolStrip.Left + 10, this.u_toolStrip.Size.Height - 2);
this.m_windowRect = new Rectangle(new Point(0, 0), windowSize);
this.Height = windowSize.Height + 10;
this.Width = windowSize.Width + 10;
Rectangle outside = this.m_windowRect;
outside.Height += 1;
outside.Width += 1;
Region windowRegion = new Region(outside);
this.Region = windowRegion;
windowRegion.Dispose();
// Paint the header of the status bar with a Yahoo! logo.
g.DrawImage(this.m_barhead, 0, 0, 36, outside.Height);
g.DrawImage(this.m_bartail, this.u_toolStrip.Right - 2, 0, 20, outside.Height);
Pen blackPen = new Pen(Color.Black);
Pen grayPen = new Pen(Color.Gray);
g.DrawRectangle(blackPen, this.m_windowRect);
g.DrawLine(grayPen, new Point(1, 0), new Point(1, this.Height));
blackPen.Dispose();
grayPen.Dispose();
}
void BIStatusBar_Paint(object sender, PaintEventArgs e)
{
// If the status bar is not visible, we do not need to refresh
// the appearance of the status bar.
if (!this.Visible)
return;
if (this.m_isMiniMode == true && this.m_isUsingSystemTrayMode == false)
this.PaintMiniMode(e);
else
this.PaintNormalMode(e);
if (!this.m_isLocationInitialized)
this.InitLocation();
}
private void BIStatusBar_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button.Equals(MouseButtons.Left))
{
Win32FunctionHelper.ReleaseCapture();
Win32FunctionHelper.SendMessage(Handle, Win32FunctionHelper.MouseMove.WM_NCLBUTTONDOWN,
Win32FunctionHelper.MouseMove.HT_CAPTION, 0);
}
}
private void BIStatusBarForm_Move(object sender, System.EventArgs e)
{
if (this.m_isMiniMode == true && this.m_isUsingSystemTrayMode == false)
{
Screen currentScreen = Screen.FromPoint(this.Location);
int currentLeft = currentScreen.WorkingArea.Right - 64;
this.Left = currentLeft;
}
if (this.u_symbolForm.Visible == true && this.m_isMiniMode == false)
{
int x = this.Left;
int y = this.Top - this.u_symbolForm.Height - 10;
if (y < 0)
y = this.Bottom;
this.u_symbolForm.Location = new Point(x, y);
}
if (this.Top - this.u_toggleInputMethodDropDownMenu.Height < 0 ||
this.Top - this.u_configsDropDownMenu.Height < 0)
{
this.u_toggleInputMethod.DropDownDirection = ToolStripDropDownDirection.BelowRight;
this.u_configs.DropDownDirection = ToolStripDropDownDirection.BelowLeft;
}
else
{
this.u_toggleInputMethod.DropDownDirection = ToolStripDropDownDirection.AboveRight;
this.u_configs.DropDownDirection = ToolStripDropDownDirection.AboveLeft;
}
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case Win32FunctionHelper.MouseMove.WM_MOVING:
case Win32FunctionHelper.MouseMove.WM_SIZING:
{
if (this.Visible)
{
RECT prc = (RECT)m.GetLParam(typeof(RECT));
if (this.m_isMiniMode == true && this.m_isUsingSystemTrayMode == false)
{
Screen currentScreen = Screen.FromPoint(this.Location);
int currentLeft = currentScreen.WorkingArea.Right - 64;
Win32FunctionHelper.SetWindowPos(m.HWnd, (IntPtr)Win32FunctionHelper.CmdShow.HWND_TOP,
currentLeft, prc.Top, 64, prc.Bottom - prc.Top, 0);
}
else
{
Win32FunctionHelper.SetWindowPos(m.HWnd, (IntPtr)Win32FunctionHelper.CmdShow.HWND_TOP,
prc.Left, prc.Top, prc.Right - prc.Left, prc.Bottom - prc.Top, 0);
}
}
}
break;
default:
break;
}
base.WndProc(ref m);
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * 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.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may 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.
//
namespace NLog.Targets.Wrappers
{
using System;
using System.ComponentModel;
using System.Threading;
using Common;
using Internal;
/// <summary>
/// Provides asynchronous, buffered execution of target writes.
/// </summary>
/// <seealso href="http://nlog-project.org/wiki/AsyncWrapper_target">Documentation on NLog Wiki</seealso>
/// <remarks>
/// <p>
/// Asynchronous target wrapper allows the logger code to execute more quickly, by queueing
/// messages and processing them in a separate thread. You should wrap targets
/// that spend a non-trivial amount of time in their Write() method with asynchronous
/// target to speed up logging.
/// </p>
/// <p>
/// Because asynchronous logging is quite a common scenario, NLog supports a
/// shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to
/// the <targets/> element in the configuration file.
/// </p>
/// <code lang="XML">
/// <![CDATA[
/// <targets async="true">
/// ... your targets go here ...
/// </targets>
/// ]]></code>
/// </remarks>
/// <example>
/// <p>
/// To set up the target in the <a href="config.html">configuration file</a>,
/// use the following syntax:
/// </p>
/// <code lang="XML" source="examples/targets/Configuration File/AsyncWrapper/NLog.config" />
/// <p>
/// The above examples assume just one target and a single rule. See below for
/// a programmatic configuration that's equivalent to the above config file:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/AsyncWrapper/Wrapping File/Example.cs" />
/// </example>
[Target("AsyncWrapper", IsWrapper = true)]
public class AsyncTargetWrapper : WrapperTargetBase
{
private readonly object lockObject = new object();
private Timer lazyWriterTimer;
private AsyncContinuation flushAllContinuation;
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
public AsyncTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public AsyncTargetWrapper(Target wrappedTarget)
: this(wrappedTarget, 10000, AsyncTargetWrapperOverflowAction.Discard)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="queueLimit">Maximum number of requests in the queue.</param>
/// <param name="overflowAction">The action to be taken when the queue overflows.</param>
public AsyncTargetWrapper(Target wrappedTarget, int queueLimit, AsyncTargetWrapperOverflowAction overflowAction)
{
this.RequestQueue = new AsyncRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard);
this.TimeToSleepBetweenBatches = 50;
this.BatchSize = 100;
this.WrappedTarget = wrappedTarget;
this.QueueLimit = queueLimit;
this.OverflowAction = overflowAction;
}
/// <summary>
/// Gets or sets the number of log events that should be processed in a batch
/// by the lazy writer thread.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(100)]
public int BatchSize { get; set; }
/// <summary>
/// Gets or sets the time in milliseconds to sleep between batches.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(50)]
public int TimeToSleepBetweenBatches { get; set; }
/// <summary>
/// Gets or sets the action to be taken when the lazy writer thread request queue count
/// exceeds the set limit.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue("Discard")]
public AsyncTargetWrapperOverflowAction OverflowAction
{
get { return this.RequestQueue.OnOverflow; }
set { this.RequestQueue.OnOverflow = value; }
}
/// <summary>
/// Gets or sets the limit on the number of requests in the lazy writer thread request queue.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(10000)]
public int QueueLimit
{
get { return this.RequestQueue.RequestLimit; }
set { this.RequestQueue.RequestLimit = value; }
}
/// <summary>
/// Gets the queue of lazy writer thread requests.
/// </summary>
internal AsyncRequestQueue RequestQueue { get; private set; }
/// <summary>
/// Waits for the lazy writer thread to finish writing messages.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
this.flushAllContinuation = asyncContinuation;
}
/// <summary>
/// Initializes the target by starting the lazy writer timer.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
this.RequestQueue.Clear();
this.lazyWriterTimer = new Timer(this.ProcessPendingEvents, null, Timeout.Infinite, Timeout.Infinite);
this.StartLazyWriterTimer();
}
/// <summary>
/// Shuts down the lazy writer timer.
/// </summary>
protected override void CloseTarget()
{
this.StopLazyWriterThread();
if (this.RequestQueue.RequestCount > 0)
{
ProcessPendingEvents(null);
}
base.CloseTarget();
}
/// <summary>
/// Starts the lazy writer thread which periodically writes
/// queued log messages.
/// </summary>
protected virtual void StartLazyWriterTimer()
{
lock (this.lockObject)
{
if (this.lazyWriterTimer != null)
{
this.lazyWriterTimer.Change(this.TimeToSleepBetweenBatches, Timeout.Infinite);
}
}
}
/// <summary>
/// Starts the lazy writer thread.
/// </summary>
protected virtual void StopLazyWriterThread()
{
lock (this.lockObject)
{
if (this.lazyWriterTimer != null)
{
this.lazyWriterTimer.Change(Timeout.Infinite, Timeout.Infinite);
this.lazyWriterTimer = null;
}
}
}
/// <summary>
/// Adds the log event to asynchronous queue to be processed by
/// the lazy writer thread.
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <remarks>
/// The <see cref="Target.PrecalculateVolatileLayouts"/> is called
/// to ensure that the log event can be processed in another thread.
/// </remarks>
protected override void Write(AsyncLogEventInfo logEvent)
{
this.PrecalculateVolatileLayouts(logEvent.LogEvent);
this.RequestQueue.Enqueue(logEvent);
}
private void ProcessPendingEvents(object state)
{
try
{
int count = this.BatchSize;
var continuation = Interlocked.Exchange(ref this.flushAllContinuation, null);
if (continuation != null)
{
count = this.RequestQueue.RequestCount;
InternalLogger.Trace("Flushing {0} events.", count);
}
AsyncLogEventInfo[] logEventInfos = this.RequestQueue.DequeueBatch(count);
if (continuation != null)
{
// write all events, then flush, then call the continuation
this.WrappedTarget.WriteAsyncLogEvents(logEventInfos, ex => this.WrappedTarget.Flush(continuation));
}
else
{
// just write all events
this.WrappedTarget.WriteAsyncLogEvents(logEventInfos);
}
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Error("Error in lazy writer timer procedure: {0}", exception);
}
finally
{
this.StartLazyWriterTimer();
}
}
}
}
| |
using System;
using static OneOf.Functions;
namespace OneOf
{
public struct OneOf<T0, T1, T2, T3, T4, T5> : IOneOf
{
readonly T0 _value0;
readonly T1 _value1;
readonly T2 _value2;
readonly T3 _value3;
readonly T4 _value4;
readonly T5 _value5;
readonly int _index;
OneOf(int index, T0 value0 = default, T1 value1 = default, T2 value2 = default, T3 value3 = default, T4 value4 = default, T5 value5 = default)
{
_index = index;
_value0 = value0;
_value1 = value1;
_value2 = value2;
_value3 = value3;
_value4 = value4;
_value5 = value5;
}
public object Value =>
_index switch
{
0 => _value0,
1 => _value1,
2 => _value2,
3 => _value3,
4 => _value4,
5 => _value5,
_ => throw new InvalidOperationException()
};
public int Index => _index;
public bool IsT0 => _index == 0;
public bool IsT1 => _index == 1;
public bool IsT2 => _index == 2;
public bool IsT3 => _index == 3;
public bool IsT4 => _index == 4;
public bool IsT5 => _index == 5;
public T0 AsT0 =>
_index == 0 ?
_value0 :
throw new InvalidOperationException($"Cannot return as T0 as result is T{_index}");
public T1 AsT1 =>
_index == 1 ?
_value1 :
throw new InvalidOperationException($"Cannot return as T1 as result is T{_index}");
public T2 AsT2 =>
_index == 2 ?
_value2 :
throw new InvalidOperationException($"Cannot return as T2 as result is T{_index}");
public T3 AsT3 =>
_index == 3 ?
_value3 :
throw new InvalidOperationException($"Cannot return as T3 as result is T{_index}");
public T4 AsT4 =>
_index == 4 ?
_value4 :
throw new InvalidOperationException($"Cannot return as T4 as result is T{_index}");
public T5 AsT5 =>
_index == 5 ?
_value5 :
throw new InvalidOperationException($"Cannot return as T5 as result is T{_index}");
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5>(T0 t) => new OneOf<T0, T1, T2, T3, T4, T5>(0, value0: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5>(T1 t) => new OneOf<T0, T1, T2, T3, T4, T5>(1, value1: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5>(T2 t) => new OneOf<T0, T1, T2, T3, T4, T5>(2, value2: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5>(T3 t) => new OneOf<T0, T1, T2, T3, T4, T5>(3, value3: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5>(T4 t) => new OneOf<T0, T1, T2, T3, T4, T5>(4, value4: t);
public static implicit operator OneOf<T0, T1, T2, T3, T4, T5>(T5 t) => new OneOf<T0, T1, T2, T3, T4, T5>(5, value5: t);
public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2, Action<T3> f3, Action<T4> f4, Action<T5> f5)
{
if (_index == 0 && f0 != null)
{
f0(_value0);
return;
}
if (_index == 1 && f1 != null)
{
f1(_value1);
return;
}
if (_index == 2 && f2 != null)
{
f2(_value2);
return;
}
if (_index == 3 && f3 != null)
{
f3(_value3);
return;
}
if (_index == 4 && f4 != null)
{
f4(_value4);
return;
}
if (_index == 5 && f5 != null)
{
f5(_value5);
return;
}
throw new InvalidOperationException();
}
public TResult Match<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2, Func<T3, TResult> f3, Func<T4, TResult> f4, Func<T5, TResult> f5)
{
if (_index == 0 && f0 != null)
{
return f0(_value0);
}
if (_index == 1 && f1 != null)
{
return f1(_value1);
}
if (_index == 2 && f2 != null)
{
return f2(_value2);
}
if (_index == 3 && f3 != null)
{
return f3(_value3);
}
if (_index == 4 && f4 != null)
{
return f4(_value4);
}
if (_index == 5 && f5 != null)
{
return f5(_value5);
}
throw new InvalidOperationException();
}
public static OneOf<T0, T1, T2, T3, T4, T5> FromT0(T0 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5> FromT1(T1 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5> FromT2(T2 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5> FromT3(T3 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5> FromT4(T4 input) => input;
public static OneOf<T0, T1, T2, T3, T4, T5> FromT5(T5 input) => input;
public OneOf<TResult, T1, T2, T3, T4, T5> MapT0<TResult>(Func<T0, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => mapFunc(AsT0),
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, TResult, T2, T3, T4, T5> MapT1<TResult>(Func<T1, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => mapFunc(AsT1),
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, TResult, T3, T4, T5> MapT2<TResult>(Func<T2, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => mapFunc(AsT2),
3 => AsT3,
4 => AsT4,
5 => AsT5,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, T2, TResult, T4, T5> MapT3<TResult>(Func<T3, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => mapFunc(AsT3),
4 => AsT4,
5 => AsT5,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, T2, T3, TResult, T5> MapT4<TResult>(Func<T4, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => mapFunc(AsT4),
5 => AsT5,
_ => throw new InvalidOperationException()
};
}
public OneOf<T0, T1, T2, T3, T4, TResult> MapT5<TResult>(Func<T5, TResult> mapFunc)
{
if (mapFunc == null)
{
throw new ArgumentNullException(nameof(mapFunc));
}
return _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => mapFunc(AsT5),
_ => throw new InvalidOperationException()
};
}
public bool TryPickT0(out T0 value, out OneOf<T1, T2, T3, T4, T5> remainder)
{
value = IsT0 ? AsT0 : default;
remainder = _index switch
{
0 => default,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
_ => throw new InvalidOperationException()
};
return this.IsT0;
}
public bool TryPickT1(out T1 value, out OneOf<T0, T2, T3, T4, T5> remainder)
{
value = IsT1 ? AsT1 : default;
remainder = _index switch
{
0 => AsT0,
1 => default,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => AsT5,
_ => throw new InvalidOperationException()
};
return this.IsT1;
}
public bool TryPickT2(out T2 value, out OneOf<T0, T1, T3, T4, T5> remainder)
{
value = IsT2 ? AsT2 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => default,
3 => AsT3,
4 => AsT4,
5 => AsT5,
_ => throw new InvalidOperationException()
};
return this.IsT2;
}
public bool TryPickT3(out T3 value, out OneOf<T0, T1, T2, T4, T5> remainder)
{
value = IsT3 ? AsT3 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => default,
4 => AsT4,
5 => AsT5,
_ => throw new InvalidOperationException()
};
return this.IsT3;
}
public bool TryPickT4(out T4 value, out OneOf<T0, T1, T2, T3, T5> remainder)
{
value = IsT4 ? AsT4 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => default,
5 => AsT5,
_ => throw new InvalidOperationException()
};
return this.IsT4;
}
public bool TryPickT5(out T5 value, out OneOf<T0, T1, T2, T3, T4> remainder)
{
value = IsT5 ? AsT5 : default;
remainder = _index switch
{
0 => AsT0,
1 => AsT1,
2 => AsT2,
3 => AsT3,
4 => AsT4,
5 => default,
_ => throw new InvalidOperationException()
};
return this.IsT5;
}
bool Equals(OneOf<T0, T1, T2, T3, T4, T5> other) =>
_index == other._index &&
_index switch
{
0 => Equals(_value0, other._value0),
1 => Equals(_value1, other._value1),
2 => Equals(_value2, other._value2),
3 => Equals(_value3, other._value3),
4 => Equals(_value4, other._value4),
5 => Equals(_value5, other._value5),
_ => false
};
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is OneOf<T0, T1, T2, T3, T4, T5> o && Equals(o);
}
public override string ToString() =>
_index switch {
0 => FormatValue(_value0),
1 => FormatValue(_value1),
2 => FormatValue(_value2),
3 => FormatValue(_value3),
4 => FormatValue(_value4),
5 => FormatValue(_value5),
_ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the OneOf codegen.")
};
public override int GetHashCode()
{
unchecked
{
int hashCode = _index switch
{
0 => _value0?.GetHashCode(),
1 => _value1?.GetHashCode(),
2 => _value2?.GetHashCode(),
3 => _value3?.GetHashCode(),
4 => _value4?.GetHashCode(),
5 => _value5?.GetHashCode(),
_ => 0
} ?? 0;
return (hashCode*397) ^ _index;
}
}
}
}
| |
using System;
using System.Collections;
using System.Diagnostics;
using BCurve=NS_GMath.I_BCurveD;
namespace NS_GMath
{
public class ListInfoInters : IEnumerable
{
/*
* MEMBERS
*/
int[] indsGlyphComponent;
ArrayList linters;
/*
* CONSTRUCTORS
*/
public ListInfoInters()
{
this.linters=new ArrayList();
this.indsGlyphComponent=new int[2];
this.indsGlyphComponent[0]=GConsts.IND_UNINITIALIZED;
this.indsGlyphComponent[1]=GConsts.IND_UNINITIALIZED;
}
/*
* PROPERTIES
*/
public bool ContainsD1
{
get
{
foreach (InfoInters inters in this.linters)
{
if (inters.Dim==InfoInters.TypeDim.Dim1)
return true;
}
return false;
}
}
public bool ContainsBezSI
{
get
{
foreach (InfoInters inters in this.linters)
{
if (inters.IsBezSI)
return true;
}
return false;
}
}
/*
* METHODS
*/
public void SetIndGlyphComponent(int indGlyphA, int indGlyphB)
{
this.indsGlyphComponent[0]=indGlyphA;
this.indsGlyphComponent[1]=indGlyphB;
}
public int IndGlyphComponent(int ind)
{
if ((ind!=0)&&(ind!=1))
{
throw new ExceptionGMath("ListInfoInters","IndGlyphComponent",null);
//return GConsts.IND_UNDEFINED;
}
return this.indsGlyphComponent[ind];
}
public void ClearDestroy()
{
foreach (InfoInters inters in this.linters)
{
inters.ClearRelease();
}
this.linters.Clear();
this.linters=null;
}
public InfoInters this [int ind]
{
get
{
return (this.linters[ind] as InfoInters);
}
}
public void Add(InfoInters inters)
{
this.linters.Add(inters);
}
public int Count
{
get { return this.linters.Count; }
}
public void RemoveAt(int poz)
{
this.linters.RemoveAt(poz);
}
public void ParamReverse(double valRev, int indCurve, int pozStart)
{
for (int poz=pozStart; poz<this.linters.Count; poz++)
{
InfoInters inters=linters[poz] as InfoInters;
inters.ParamReverse(valRev, indCurve);
}
}
public void ParamFromReduced(BCurve bcurve, int indCurve, int pozStart)
{
for (int poz=pozStart; poz<this.linters.Count; poz++)
{
InfoInters inters=linters[poz] as InfoInters;
inters.ParamFromReduced(bcurve,indCurve);
}
}
public void ParamSwap(int pozStart)
{
for (int poz=pozStart; poz<this.linters.Count; poz++)
{
InfoInters inters=linters[poz] as InfoInters;
inters.ParamSwap();
}
}
public void ParamToCParam(Knot kn0, Knot kn1, int pozStart)
{
for (int poz=pozStart; poz<this.linters.Count; poz++)
{
InfoInters inters=linters[poz] as InfoInters;
inters.ParamToCParam(kn0,kn1);
}
}
public void ParamInvalidateBezSI(int pozStart)
{
for (int poz=pozStart; poz<this.linters.Count; poz++)
{
InfoInters inters=linters[poz] as InfoInters;
inters.ParamInvalidateBezSI();
}
}
public void CleanEndPointBezSI(VecD pnt, int pozStart)
{
for (int poz=pozStart; poz<this.linters.Count; poz++)
{
IntersD0 intersD0=linters[poz] as IntersD0;
if (intersD0!=null)
{
bool toDelete=(intersD0.PntInters==pnt);
if (toDelete)
{
this.linters.RemoveAt(poz);
poz--;
}
}
}
}
public void CleanEndPointInters(bool connectAB, bool connectBA,
int pozStart)
{
if ((!connectAB)&&(!connectBA))
return;
for (int poz=pozStart; poz<this.linters.Count; poz++)
{
IntersD0 intersD0=linters[poz] as IntersD0;
if (intersD0!=null)
{
if (!intersD0.IncludeBezSI)
{
intersD0.Ipi.Par(0).Round(0,1);
intersD0.Ipi.Par(1).Round(0,1);
bool toDelete=((connectAB&&(intersD0.Ipi.Par(0).Val==1)&&(intersD0.Ipi.Par(1).Val==0))||
(connectBA&&(intersD0.Ipi.Par(0).Val==0)&&(intersD0.Ipi.Par(1).Val==1)));
if (toDelete)
{
this.linters.RemoveAt(poz);
poz--;
}
}
}
}
}
/*
* METHODS: IENUMERABLE
*/
public IEnumerator GetEnumerator()
{
return this.linters.GetEnumerator();
}
}
}
| |
#define PRETTY //Comment out when you no longer need to read JSON to disable pretty Print system-wide
//Using doubles will cause errors in VectorTemplates.cs; Unity speaks floats
//#define USEFLOAT //Use floats for numbers instead of doubles (enable if you're getting too many significant digits in string output)
//#define POOLING //Currently using a build setting for this one (also it's experimental)
using System.Diagnostics;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Debug = UnityEngine.Debug;
/*
* http://www.opensource.org/licenses/lgpl-2.1.php
* JSONObject class
* for use with Unity
* Copyright Matt Schoen 2010 - 2013
*/
namespace UnityEngine.UI.Windows.Plugins.Social.ThirdParty {
public class JSONObject {
#if POOLING
const int MAX_POOL_SIZE = 10000;
public static Queue<JSONObject> releaseQueue = new Queue<JSONObject>();
#endif
private static JSONObject _empty;
public static JSONObject Empty {
get {
if (JSONObject._empty == null) JSONObject._empty = new JSONObject();
return JSONObject._empty;
}
}
const int MAX_DEPTH = 100;
const string INFINITY = "\"INFINITY\"";
const string NEGINFINITY = "\"NEGINFINITY\"";
const string NaN = "\"NaN\"";
static readonly char[] WHITESPACE = new[] { ' ', '\r', '\n', '\t' };
public enum Type { NULL, STRING, NUMBER, OBJECT, ARRAY, BOOL, BAKED }
public bool isContainer { get { return (type == Type.ARRAY || type == Type.OBJECT); } }
public Type type = Type.NULL;
public int Count {
get {
if(list == null)
return -1;
return list.Count;
}
}
public List<JSONObject> list;
public List<string> keys;
public string str;
#if USEFLOAT
public float n;
public float f {
get {
return n;
}
}
#else
public double n;
public float f {
get {
return (float)n;
}
}
public double d {
get {
return n;
}
}
#endif
public bool b;
public delegate void AddJSONConents(JSONObject self);
public static JSONObject nullJO { get { return Create(Type.NULL); } } //an empty, null object
public static JSONObject obj { get { return Create(Type.OBJECT); } } //an empty object
public static JSONObject arr { get { return Create(Type.ARRAY); } } //an empty array
public JSONObject(Type t) {
type = t;
switch(t) {
case Type.ARRAY:
list = new List<JSONObject>();
break;
case Type.OBJECT:
list = new List<JSONObject>();
keys = new List<string>();
break;
}
}
public JSONObject(bool b) {
type = Type.BOOL;
this.b = b;
}
#if USEFLOAT
public JSONObject(float f) {
type = Type.NUMBER;
n = f;
}
#else
public JSONObject(double d) {
type = Type.NUMBER;
n = d;
}
#endif
public JSONObject(Dictionary<string, string> dic) {
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach(KeyValuePair<string, string> kvp in dic) {
keys.Add(kvp.Key);
list.Add(CreateStringObject(kvp.Value));
}
}
public JSONObject(Dictionary<string, JSONObject> dic) {
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach(KeyValuePair<string, JSONObject> kvp in dic) {
keys.Add(kvp.Key);
list.Add(kvp.Value);
}
}
public JSONObject(AddJSONConents content) {
content.Invoke(this);
}
public JSONObject(JSONObject[] objs) {
type = Type.ARRAY;
list = new List<JSONObject>(objs);
}
//Convenience function for creating a JSONObject containing a string. This is not part of the constructor so that malformed JSON data doesn't just turn into a string object
public static JSONObject StringObject(string val) { return CreateStringObject(val); }
public void Absorb(JSONObject obj) {
list.AddRange(obj.list);
keys.AddRange(obj.keys);
str = obj.str;
n = obj.n;
b = obj.b;
type = obj.type;
}
public static JSONObject Create() {
#if POOLING
JSONObject result = null;
while(result == null && releaseQueue.Count > 0) {
result = releaseQueue.Dequeue();
#if DEV
//The following cases should NEVER HAPPEN (but they do...)
if(result == null)
Debug.Log("wtf " + releaseQueue.Count);
else if(result.list != null)
Debug.Log("wtflist " + result.list.Count);
#endif
}
if(result != null)
return result;
#endif
return new JSONObject();
}
public static JSONObject Create(Type t) {
JSONObject obj = Create();
obj.type = t;
switch(t) {
case Type.ARRAY:
obj.list = new List<JSONObject>();
break;
case Type.OBJECT:
obj.list = new List<JSONObject>();
obj.keys = new List<string>();
break;
}
return obj;
}
public static JSONObject Create(bool val) {
JSONObject obj = Create();
obj.type = Type.BOOL;
obj.b = val;
return obj;
}
public static JSONObject Create(float val) {
JSONObject obj = Create();
obj.type = Type.NUMBER;
obj.n = val;
return obj;
}
public static JSONObject Create(int val) {
JSONObject obj = Create();
obj.type = Type.NUMBER;
obj.n = val;
return obj;
}
public static JSONObject CreateStringObject(string val) {
JSONObject obj = Create();
obj.type = Type.STRING;
obj.str = val;
return obj;
}
public static JSONObject CreateBakedObject(string val) {
JSONObject bakedObject = Create();
bakedObject.type = Type.BAKED;
bakedObject.str = val;
return bakedObject;
}
/// <summary>
/// Create a JSONObject by parsing string data
/// </summary>
/// <param name="val">The string to be parsed</param>
/// <param name="maxDepth">The maximum depth for the parser to search. Set this to to 1 for the first level,
/// 2 for the first 2 levels, etc. It defaults to -2 because -1 is the depth value that is parsed (see below)</param>
/// <param name="storeExcessLevels">Whether to store levels beyond maxDepth in baked JSONObjects</param>
/// <param name="strict">Whether to be strict in the parsing. For example, non-strict parsing will successfully
/// parse "a string" into a string-type </param>
/// <returns></returns>
public static JSONObject Create(string val, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) {
JSONObject obj = Create();
obj.Parse(val, maxDepth, storeExcessLevels, strict);
return obj;
}
public static JSONObject Create(AddJSONConents content) {
JSONObject obj = Create();
content.Invoke(obj);
return obj;
}
public static JSONObject Create(Dictionary<string, string> dic) {
JSONObject obj = Create();
obj.type = Type.OBJECT;
obj.keys = new List<string>();
obj.list = new List<JSONObject>();
//Not sure if it's worth removing the foreach here
foreach(KeyValuePair<string, string> kvp in dic) {
obj.keys.Add(kvp.Key);
obj.list.Add(CreateStringObject(kvp.Value));
}
return obj;
}
public JSONObject() { }
#region PARSE
public JSONObject(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) { //create a new JSONObject from a string (this will also create any children, and parse the whole string)
Parse(str, maxDepth, storeExcessLevels, strict);
}
void Parse(string str, int maxDepth = -2, bool storeExcessLevels = false, bool strict = false) {
if(!string.IsNullOrEmpty(str)) {
str = str.Trim(WHITESPACE);
str = str.Replace("\\/", "/");
if(strict) {
if(str[0] != '[' && str[0] != '{') {
type = Type.NULL;
Debug.LogWarning("Improper (strict) JSON formatting. First character must be [ or {");
return;
}
}
if(str.Length > 0) {
if(string.Compare(str, "true", true) == 0) {
type = Type.BOOL;
b = true;
} else if(string.Compare(str, "false", true) == 0) {
type = Type.BOOL;
b = false;
} else if(string.Compare(str, "null", true) == 0) {
type = Type.NULL;
#if USEFLOAT
} else if(str == INFINITY) {
type = Type.NUMBER;
n = float.PositiveInfinity;
} else if(str == NEGINFINITY) {
type = Type.NUMBER;
n = float.NegativeInfinity;
} else if(str == NaN) {
type = Type.NUMBER;
n = float.NaN;
#else
} else if(str == INFINITY) {
type = Type.NUMBER;
n = double.PositiveInfinity;
} else if(str == NEGINFINITY) {
type = Type.NUMBER;
n = double.NegativeInfinity;
} else if(str == NaN) {
type = Type.NUMBER;
n = double.NaN;
#endif
} else if(str[0] == '"') {
type = Type.STRING;
this.str = str.Substring(1, str.Length - 2);
} else {
int tokenTmp = 1;
/*
* Checking for the following formatting (www.json.org)
* object - {"field1":value,"field2":value}
* array - [value,value,value]
* value - string - "string"
* - number - 0.0
* - bool - true -or- false
* - null - null
*/
int offset = 0;
switch(str[offset]) {
case '{':
type = Type.OBJECT;
keys = new List<string>();
list = new List<JSONObject>();
break;
case '[':
type = Type.ARRAY;
list = new List<JSONObject>();
break;
default:
try {
#if USEFLOAT
n = System.Convert.ToSingle(str);
#else
n = System.Convert.ToDouble(str);
#endif
type = Type.NUMBER;
} catch(System.FormatException) {
type = Type.NULL;
Debug.LogWarning("improper JSON formatting:" + str);
}
return;
}
string propName = "";
bool openQuote = false;
bool inProp = false;
int depth = 0;
while(++offset < str.Length) {
if(System.Array.IndexOf(WHITESPACE, str[offset]) > -1)
continue;
if(str[offset] == '\\')
offset += 2;
if(str[offset] == '"') {
if(openQuote) {
if(!inProp && depth == 0 && type == Type.OBJECT)
propName = str.Substring(tokenTmp + 1, offset - tokenTmp - 1);
openQuote = false;
} else {
if(depth == 0 && type == Type.OBJECT)
tokenTmp = offset;
openQuote = true;
}
}
if(openQuote)
continue;
if(type == Type.OBJECT && depth == 0) {
if(str[offset] == ':') {
tokenTmp = offset + 1;
inProp = true;
}
}
if(str[offset] == '[' || str[offset] == '{') {
depth++;
} else if(str[offset] == ']' || str[offset] == '}') {
depth--;
}
//if (encounter a ',' at top level) || a closing ]/}
if((str[offset] == ',' && depth == 0) || depth < 0) {
inProp = false;
string inner = str.Substring(tokenTmp, offset - tokenTmp).Trim(WHITESPACE);
if(inner.Length > 0) {
if(type == Type.OBJECT)
keys.Add(propName);
if(maxDepth != -1) //maxDepth of -1 is the end of the line
list.Add(Create(inner, (maxDepth < -1) ? -2 : maxDepth - 1));
else if(storeExcessLevels)
list.Add(CreateBakedObject(inner));
}
tokenTmp = offset + 1;
}
}
}
} else type = Type.NULL;
} else type = Type.NULL; //If the string is missing, this is a null
//Profiler.EndSample();
}
#endregion
public bool IsNumber { get { return type == Type.NUMBER; } }
public bool IsNull { get { return type == Type.NULL; } }
public bool IsString { get { return type == Type.STRING; } }
public bool IsBool { get { return type == Type.BOOL; } }
public bool IsArray { get { return type == Type.ARRAY; } }
public bool IsObject { get { return type == Type.OBJECT; } }
public void Add(bool val) {
Add(Create(val));
}
public void Add(float val) {
Add(Create(val));
}
public void Add(int val) {
Add(Create(val));
}
public void Add(string str) {
Add(CreateStringObject(str));
}
public void Add(AddJSONConents content) {
Add(Create(content));
}
public void Add(JSONObject obj) {
if(obj) { //Don't do anything if the object is null
if(type != Type.ARRAY) {
type = Type.ARRAY; //Congratulations, son, you're an ARRAY now
if(list == null)
list = new List<JSONObject>();
}
list.Add(obj);
}
}
public void AddField(string name, bool val) {
AddField(name, Create(val));
}
public void AddField(string name, float val) {
AddField(name, Create(val));
}
public void AddField(string name, int val) {
AddField(name, Create(val));
}
public void AddField(string name, AddJSONConents content) {
AddField(name, Create(content));
}
public void AddField(string name, string val) {
AddField(name, CreateStringObject(val));
}
public void AddField(string name, JSONObject obj) {
if(obj) { //Don't do anything if the object is null
if(type != Type.OBJECT) {
if(keys == null)
keys = new List<string>();
if(type == Type.ARRAY) {
for(int i = 0; i < list.Count; i++)
keys.Add(i + "");
} else
if(list == null)
list = new List<JSONObject>();
type = Type.OBJECT; //Congratulations, son, you're an OBJECT now
}
keys.Add(name);
list.Add(obj);
}
}
public void SetField(string name, bool val) { SetField(name, Create(val)); }
public void SetField(string name, float val) { SetField(name, Create(val)); }
public void SetField(string name, int val) { SetField(name, Create(val)); }
public void SetField(string name, JSONObject obj) {
if(HasField(name)) {
list.Remove(this[name]);
keys.Remove(name);
}
AddField(name, obj);
}
public void RemoveField(string name) {
if(keys.IndexOf(name) > -1) {
list.RemoveAt(keys.IndexOf(name));
keys.Remove(name);
}
}
public delegate void FieldNotFound(string name);
public delegate void GetFieldResponse(JSONObject obj);
public void GetField(ref bool field, string name, FieldNotFound fail = null) {
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = list[index].b;
return;
}
}
if(fail != null) fail.Invoke(name);
}
#if USEFLOAT
public void GetField(ref float field, string name, FieldNotFound fail = null) {
#else
public void GetField(ref double field, string name, FieldNotFound fail = null) {
#endif
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = list[index].n;
return;
}
}
if(fail != null) fail.Invoke(name);
}
public void GetField(ref int field, string name, FieldNotFound fail = null) {
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = (int)list[index].n;
return;
}
}
if(fail != null) fail.Invoke(name);
}
public void GetField(ref uint field, string name, FieldNotFound fail = null) {
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = (uint)list[index].n;
return;
}
}
if(fail != null) fail.Invoke(name);
}
public void GetField(ref string field, string name, FieldNotFound fail = null) {
if(type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
field = list[index].str;
return;
}
}
if(fail != null) fail.Invoke(name);
}
public void GetField(string name, GetFieldResponse response, FieldNotFound fail = null) {
if(response != null && type == Type.OBJECT) {
int index = keys.IndexOf(name);
if(index >= 0) {
response.Invoke(list[index]);
return;
}
}
if(fail != null) fail.Invoke(name);
}
public JSONObject GetField(string name) {
if(type == Type.OBJECT)
for(int i = 0; i < keys.Count; i++)
if(keys[i] == name)
return list[i];
return JSONObject.Empty;
}
public bool HasFields(string[] names) {
for(int i = 0; i < names.Length; i++)
if(!keys.Contains(names[i]))
return false;
return true;
}
public bool HasField(string name) {
if(type == Type.OBJECT)
for(int i = 0; i < keys.Count; i++)
if(keys[i] == name)
return true;
return false;
}
public void Clear() {
type = Type.NULL;
if(list != null)
list.Clear();
if(keys != null)
keys.Clear();
str = "";
n = 0;
b = false;
}
/// <summary>
/// Copy a JSONObject. This could probably work better
/// </summary>
/// <returns></returns>
public JSONObject Copy() {
return Create(Print());
}
/*
* The Merge function is experimental. Use at your own risk.
*/
public void Merge(JSONObject obj) {
MergeRecur(this, obj);
}
/// <summary>
/// Merge object right into left recursively
/// </summary>
/// <param name="left">The left (base) object</param>
/// <param name="right">The right (new) object</param>
static void MergeRecur(JSONObject left, JSONObject right) {
if(left.type == Type.NULL)
left.Absorb(right);
else if(left.type == Type.OBJECT && right.type == Type.OBJECT) {
for(int i = 0; i < right.list.Count; i++) {
string key = right.keys[i];
if(right[i].isContainer) {
if(left.HasField(key))
MergeRecur(left[key], right[i]);
else
left.AddField(key, right[i]);
} else {
if(left.HasField(key))
left.SetField(key, right[i]);
else
left.AddField(key, right[i]);
}
}
} else if(left.type == Type.ARRAY && right.type == Type.ARRAY) {
if(right.Count > left.Count) {
Debug.LogError("Cannot merge arrays when right object has more elements");
return;
}
for(int i = 0; i < right.list.Count; i++) {
if(left[i].type == right[i].type) { //Only overwrite with the same type
if(left[i].isContainer)
MergeRecur(left[i], right[i]);
else {
left[i] = right[i];
}
}
}
}
}
public void Bake() {
if(type != Type.BAKED) {
str = Print();
type = Type.BAKED;
}
}
public IEnumerable BakeAsync() {
if(type != Type.BAKED) {
foreach(string s in PrintAsync()) {
if(s == null)
yield return s;
else {
str = s;
}
}
type = Type.BAKED;
}
}
#pragma warning disable 219
public string Print(bool pretty = false) {
StringBuilder builder = new StringBuilder();
Stringify(0, builder, pretty);
return builder.ToString();
}
public IEnumerable<string> PrintAsync(bool pretty = false) {
StringBuilder builder = new StringBuilder();
printWatch.Reset();
printWatch.Start();
foreach(IEnumerable e in StringifyAsync(0, builder, pretty)) {
yield return null;
}
yield return builder.ToString();
}
#pragma warning restore 219
#region STRINGIFY
const float maxFrameTime = 0.008f;
static readonly Stopwatch printWatch = new Stopwatch();
IEnumerable StringifyAsync(int depth, StringBuilder builder, bool pretty = false) { //Convert the JSONObject into a string
//Profiler.BeginSample("JSONprint");
if(depth++ > MAX_DEPTH) {
Debug.Log("reached max depth!");
yield break;
}
if(printWatch.Elapsed.TotalSeconds > maxFrameTime) {
printWatch.Reset();
yield return null;
printWatch.Start();
}
switch(type) {
case Type.BAKED:
builder.Append(str);
break;
case Type.STRING:
builder.AppendFormat("\"{0}\"", str);
break;
case Type.NUMBER:
#if USEFLOAT
if(float.IsInfinity(n))
builder.Append(INFINITY);
else if(float.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(float.IsNaN(n))
builder.Append(NaN);
#else
if(double.IsInfinity(n))
builder.Append(INFINITY);
else if(double.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(double.IsNaN(n))
builder.Append(NaN);
#endif
else
builder.Append(n.ToString());
break;
case Type.OBJECT:
builder.Append("{");
if(list.Count > 0) {
#if(PRETTY) //for a bit more readability, comment the define above to disable system-wide
if(pretty)
builder.Append("\n");
#endif
for(int i = 0; i < list.Count; i++) {
string key = keys[i];
JSONObject obj = list[i];
if(obj) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
builder.AppendFormat("\"{0}\":", key);
foreach(IEnumerable e in obj.StringifyAsync(depth, builder, pretty))
yield return e;
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append("\n");
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append("\n");
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("}");
break;
case Type.ARRAY:
builder.Append("[");
if(list.Count > 0) {
#if(PRETTY)
if(pretty)
builder.Append("\n"); //for a bit more readability
#endif
for(int i = 0; i < list.Count; i++) {
if(list[i]) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
foreach(IEnumerable e in list[i].StringifyAsync(depth, builder, pretty))
yield return e;
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append("\n"); //for a bit more readability
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append("\n");
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("]");
break;
case Type.BOOL:
if(b)
builder.Append("true");
else
builder.Append("false");
break;
case Type.NULL:
builder.Append("null");
break;
}
//Profiler.EndSample();
}
//TODO: Refactor Stringify functions to share core logic
/*
* I know, I know, this is really bad form. It turns out that there is a
* significant amount of garbage created when calling as a coroutine, so this
* method is duplicated. Hopefully there won't be too many future changes, but
* I would still like a more elegant way to optionaly yield
*/
void Stringify(int depth, StringBuilder builder, bool pretty = false) { //Convert the JSONObject into a string
//Profiler.BeginSample("JSONprint");
if(depth++ > MAX_DEPTH) {
Debug.Log("reached max depth!");
return;
}
switch(type) {
case Type.BAKED:
builder.Append(str);
break;
case Type.STRING:
builder.AppendFormat("\"{0}\"", str);
break;
case Type.NUMBER:
#if USEFLOAT
if(float.IsInfinity(n))
builder.Append(INFINITY);
else if(float.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(float.IsNaN(n))
builder.Append(NaN);
#else
if(double.IsInfinity(n))
builder.Append(INFINITY);
else if(double.IsNegativeInfinity(n))
builder.Append(NEGINFINITY);
else if(double.IsNaN(n))
builder.Append(NaN);
#endif
else
builder.Append(n.ToString());
break;
case Type.OBJECT:
builder.Append("{");
if(list.Count > 0) {
#if(PRETTY) //for a bit more readability, comment the define above to disable system-wide
if(pretty)
builder.Append("\n");
#endif
for(int i = 0; i < list.Count; i++) {
string key = keys[i];
JSONObject obj = list[i];
if(obj) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
builder.AppendFormat("\"{0}\":", key);
obj.Stringify(depth, builder, pretty);
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append("\n");
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append("\n");
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("}");
break;
case Type.ARRAY:
builder.Append("[");
if(list.Count > 0) {
#if(PRETTY)
if(pretty)
builder.Append("\n"); //for a bit more readability
#endif
for(int i = 0; i < list.Count; i++) {
if(list[i]) {
#if(PRETTY)
if(pretty)
for(int j = 0; j < depth; j++)
builder.Append("\t"); //for a bit more readability
#endif
list[i].Stringify(depth, builder, pretty);
builder.Append(",");
#if(PRETTY)
if(pretty)
builder.Append("\n"); //for a bit more readability
#endif
}
}
#if(PRETTY)
if(pretty)
builder.Length -= 2;
else
#endif
builder.Length--;
}
#if(PRETTY)
if(pretty && list.Count > 0) {
builder.Append("\n");
for(int j = 0; j < depth - 1; j++)
builder.Append("\t"); //for a bit more readability
}
#endif
builder.Append("]");
break;
case Type.BOOL:
if(b)
builder.Append("true");
else
builder.Append("false");
break;
case Type.NULL:
builder.Append("null");
break;
}
//Profiler.EndSample();
}
#endregion
public static implicit operator WWWForm(JSONObject obj) {
WWWForm form = new WWWForm();
for(int i = 0; i < obj.list.Count; i++) {
string key = i + "";
if(obj.type == Type.OBJECT)
key = obj.keys[i];
string val = obj.list[i].ToString();
if(obj.list[i].type == Type.STRING)
val = val.Replace("\"", "");
form.AddField(key, val);
}
return form;
}
public JSONObject this[int index] {
get {
if(list.Count > index) return list[index];
return null;
}
set {
if(list.Count > index)
list[index] = value;
}
}
public JSONObject this[string index] {
get {
return GetField(index);
}
set {
SetField(index, value);
}
}
public override string ToString() {
return Print();
}
public string ToString(bool pretty) {
return Print(pretty);
}
public Dictionary<string, string> ToDictionary() {
if(type == Type.OBJECT) {
Dictionary<string, string> result = new Dictionary<string, string>();
for(int i = 0; i < list.Count; i++) {
JSONObject val = list[i];
switch(val.type) {
case Type.STRING: result.Add(keys[i], val.str); break;
case Type.NUMBER: result.Add(keys[i], val.n + ""); break;
case Type.BOOL: result.Add(keys[i], val.b + ""); break;
default: Debug.LogWarning("Omitting object: " + keys[i] + " in dictionary conversion"); break;
}
}
return result;
}
Debug.LogWarning("Tried to turn non-Object JSONObject into a dictionary");
return null;
}
public static implicit operator bool(JSONObject o) {
return o != null;
}
#if POOLING
static bool pool = true;
public static void ClearPool() {
pool = false;
releaseQueue.Clear();
pool = true;
}
~JSONObject() {
if(pool && releaseQueue.Count < MAX_POOL_SIZE) {
type = Type.NULL;
list = null;
keys = null;
str = "";
n = 0;
b = false;
releaseQueue.Enqueue(this);
}
}
#endif
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace SAEON.Observations.Data{
/// <summary>
/// Strongly-typed collection for the VProjectStation class.
/// </summary>
[Serializable]
public partial class VProjectStationCollection : ReadOnlyList<VProjectStation, VProjectStationCollection>
{
public VProjectStationCollection() {}
}
/// <summary>
/// This is Read-only wrapper class for the vProjectStation view.
/// </summary>
[Serializable]
public partial class VProjectStation : ReadOnlyRecord<VProjectStation>, IReadOnlyRecord
{
#region Default Settings
protected static void SetSQLProps()
{
GetTableSchema();
}
#endregion
#region Schema Accessor
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
{
SetSQLProps();
}
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("vProjectStation", TableType.View, DataService.GetInstance("ObservationsDB"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);
colvarId.ColumnName = "ID";
colvarId.DataType = DbType.Guid;
colvarId.MaxLength = 0;
colvarId.AutoIncrement = false;
colvarId.IsNullable = false;
colvarId.IsPrimaryKey = false;
colvarId.IsForeignKey = false;
colvarId.IsReadOnly = false;
schema.Columns.Add(colvarId);
TableSchema.TableColumn colvarProjectID = new TableSchema.TableColumn(schema);
colvarProjectID.ColumnName = "ProjectID";
colvarProjectID.DataType = DbType.Guid;
colvarProjectID.MaxLength = 0;
colvarProjectID.AutoIncrement = false;
colvarProjectID.IsNullable = false;
colvarProjectID.IsPrimaryKey = false;
colvarProjectID.IsForeignKey = false;
colvarProjectID.IsReadOnly = false;
schema.Columns.Add(colvarProjectID);
TableSchema.TableColumn colvarStationID = new TableSchema.TableColumn(schema);
colvarStationID.ColumnName = "StationID";
colvarStationID.DataType = DbType.Guid;
colvarStationID.MaxLength = 0;
colvarStationID.AutoIncrement = false;
colvarStationID.IsNullable = false;
colvarStationID.IsPrimaryKey = false;
colvarStationID.IsForeignKey = false;
colvarStationID.IsReadOnly = false;
schema.Columns.Add(colvarStationID);
TableSchema.TableColumn colvarStartDate = new TableSchema.TableColumn(schema);
colvarStartDate.ColumnName = "StartDate";
colvarStartDate.DataType = DbType.Date;
colvarStartDate.MaxLength = 0;
colvarStartDate.AutoIncrement = false;
colvarStartDate.IsNullable = true;
colvarStartDate.IsPrimaryKey = false;
colvarStartDate.IsForeignKey = false;
colvarStartDate.IsReadOnly = false;
schema.Columns.Add(colvarStartDate);
TableSchema.TableColumn colvarEndDate = new TableSchema.TableColumn(schema);
colvarEndDate.ColumnName = "EndDate";
colvarEndDate.DataType = DbType.Date;
colvarEndDate.MaxLength = 0;
colvarEndDate.AutoIncrement = false;
colvarEndDate.IsNullable = true;
colvarEndDate.IsPrimaryKey = false;
colvarEndDate.IsForeignKey = false;
colvarEndDate.IsReadOnly = false;
schema.Columns.Add(colvarEndDate);
TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema);
colvarUserId.ColumnName = "UserId";
colvarUserId.DataType = DbType.Guid;
colvarUserId.MaxLength = 0;
colvarUserId.AutoIncrement = false;
colvarUserId.IsNullable = false;
colvarUserId.IsPrimaryKey = false;
colvarUserId.IsForeignKey = false;
colvarUserId.IsReadOnly = false;
schema.Columns.Add(colvarUserId);
TableSchema.TableColumn colvarAddedAt = new TableSchema.TableColumn(schema);
colvarAddedAt.ColumnName = "AddedAt";
colvarAddedAt.DataType = DbType.DateTime;
colvarAddedAt.MaxLength = 0;
colvarAddedAt.AutoIncrement = false;
colvarAddedAt.IsNullable = true;
colvarAddedAt.IsPrimaryKey = false;
colvarAddedAt.IsForeignKey = false;
colvarAddedAt.IsReadOnly = false;
schema.Columns.Add(colvarAddedAt);
TableSchema.TableColumn colvarUpdatedAt = new TableSchema.TableColumn(schema);
colvarUpdatedAt.ColumnName = "UpdatedAt";
colvarUpdatedAt.DataType = DbType.DateTime;
colvarUpdatedAt.MaxLength = 0;
colvarUpdatedAt.AutoIncrement = false;
colvarUpdatedAt.IsNullable = true;
colvarUpdatedAt.IsPrimaryKey = false;
colvarUpdatedAt.IsForeignKey = false;
colvarUpdatedAt.IsReadOnly = false;
schema.Columns.Add(colvarUpdatedAt);
TableSchema.TableColumn colvarRowVersion = new TableSchema.TableColumn(schema);
colvarRowVersion.ColumnName = "RowVersion";
colvarRowVersion.DataType = DbType.Binary;
colvarRowVersion.MaxLength = 0;
colvarRowVersion.AutoIncrement = false;
colvarRowVersion.IsNullable = false;
colvarRowVersion.IsPrimaryKey = false;
colvarRowVersion.IsForeignKey = false;
colvarRowVersion.IsReadOnly = true;
schema.Columns.Add(colvarRowVersion);
TableSchema.TableColumn colvarProjectCode = new TableSchema.TableColumn(schema);
colvarProjectCode.ColumnName = "ProjectCode";
colvarProjectCode.DataType = DbType.AnsiString;
colvarProjectCode.MaxLength = 50;
colvarProjectCode.AutoIncrement = false;
colvarProjectCode.IsNullable = false;
colvarProjectCode.IsPrimaryKey = false;
colvarProjectCode.IsForeignKey = false;
colvarProjectCode.IsReadOnly = false;
schema.Columns.Add(colvarProjectCode);
TableSchema.TableColumn colvarProjectName = new TableSchema.TableColumn(schema);
colvarProjectName.ColumnName = "ProjectName";
colvarProjectName.DataType = DbType.AnsiString;
colvarProjectName.MaxLength = 150;
colvarProjectName.AutoIncrement = false;
colvarProjectName.IsNullable = false;
colvarProjectName.IsPrimaryKey = false;
colvarProjectName.IsForeignKey = false;
colvarProjectName.IsReadOnly = false;
schema.Columns.Add(colvarProjectName);
TableSchema.TableColumn colvarStationCode = new TableSchema.TableColumn(schema);
colvarStationCode.ColumnName = "StationCode";
colvarStationCode.DataType = DbType.AnsiString;
colvarStationCode.MaxLength = 50;
colvarStationCode.AutoIncrement = false;
colvarStationCode.IsNullable = false;
colvarStationCode.IsPrimaryKey = false;
colvarStationCode.IsForeignKey = false;
colvarStationCode.IsReadOnly = false;
schema.Columns.Add(colvarStationCode);
TableSchema.TableColumn colvarStationName = new TableSchema.TableColumn(schema);
colvarStationName.ColumnName = "StationName";
colvarStationName.DataType = DbType.AnsiString;
colvarStationName.MaxLength = 150;
colvarStationName.AutoIncrement = false;
colvarStationName.IsNullable = false;
colvarStationName.IsPrimaryKey = false;
colvarStationName.IsForeignKey = false;
colvarStationName.IsReadOnly = false;
schema.Columns.Add(colvarStationName);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["ObservationsDB"].AddSchema("vProjectStation",schema);
}
}
#endregion
#region Query Accessor
public static Query CreateQuery()
{
return new Query(Schema);
}
#endregion
#region .ctors
public VProjectStation()
{
SetSQLProps();
SetDefaults();
MarkNew();
}
public VProjectStation(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
{
ForceDefaults();
}
MarkNew();
}
public VProjectStation(object keyID)
{
SetSQLProps();
LoadByKey(keyID);
}
public VProjectStation(string columnName, object columnValue)
{
SetSQLProps();
LoadByParam(columnName,columnValue);
}
#endregion
#region Props
[XmlAttribute("Id")]
[Bindable(true)]
public Guid Id
{
get
{
return GetColumnValue<Guid>("ID");
}
set
{
SetColumnValue("ID", value);
}
}
[XmlAttribute("ProjectID")]
[Bindable(true)]
public Guid ProjectID
{
get
{
return GetColumnValue<Guid>("ProjectID");
}
set
{
SetColumnValue("ProjectID", value);
}
}
[XmlAttribute("StationID")]
[Bindable(true)]
public Guid StationID
{
get
{
return GetColumnValue<Guid>("StationID");
}
set
{
SetColumnValue("StationID", value);
}
}
[XmlAttribute("StartDate")]
[Bindable(true)]
public DateTime? StartDate
{
get
{
return GetColumnValue<DateTime?>("StartDate");
}
set
{
SetColumnValue("StartDate", value);
}
}
[XmlAttribute("EndDate")]
[Bindable(true)]
public DateTime? EndDate
{
get
{
return GetColumnValue<DateTime?>("EndDate");
}
set
{
SetColumnValue("EndDate", value);
}
}
[XmlAttribute("UserId")]
[Bindable(true)]
public Guid UserId
{
get
{
return GetColumnValue<Guid>("UserId");
}
set
{
SetColumnValue("UserId", value);
}
}
[XmlAttribute("AddedAt")]
[Bindable(true)]
public DateTime? AddedAt
{
get
{
return GetColumnValue<DateTime?>("AddedAt");
}
set
{
SetColumnValue("AddedAt", value);
}
}
[XmlAttribute("UpdatedAt")]
[Bindable(true)]
public DateTime? UpdatedAt
{
get
{
return GetColumnValue<DateTime?>("UpdatedAt");
}
set
{
SetColumnValue("UpdatedAt", value);
}
}
[XmlAttribute("RowVersion")]
[Bindable(true)]
public byte[] RowVersion
{
get
{
return GetColumnValue<byte[]>("RowVersion");
}
set
{
SetColumnValue("RowVersion", value);
}
}
[XmlAttribute("ProjectCode")]
[Bindable(true)]
public string ProjectCode
{
get
{
return GetColumnValue<string>("ProjectCode");
}
set
{
SetColumnValue("ProjectCode", value);
}
}
[XmlAttribute("ProjectName")]
[Bindable(true)]
public string ProjectName
{
get
{
return GetColumnValue<string>("ProjectName");
}
set
{
SetColumnValue("ProjectName", value);
}
}
[XmlAttribute("StationCode")]
[Bindable(true)]
public string StationCode
{
get
{
return GetColumnValue<string>("StationCode");
}
set
{
SetColumnValue("StationCode", value);
}
}
[XmlAttribute("StationName")]
[Bindable(true)]
public string StationName
{
get
{
return GetColumnValue<string>("StationName");
}
set
{
SetColumnValue("StationName", value);
}
}
#endregion
#region Columns Struct
public struct Columns
{
public static string Id = @"ID";
public static string ProjectID = @"ProjectID";
public static string StationID = @"StationID";
public static string StartDate = @"StartDate";
public static string EndDate = @"EndDate";
public static string UserId = @"UserId";
public static string AddedAt = @"AddedAt";
public static string UpdatedAt = @"UpdatedAt";
public static string RowVersion = @"RowVersion";
public static string ProjectCode = @"ProjectCode";
public static string ProjectName = @"ProjectName";
public static string StationCode = @"StationCode";
public static string StationName = @"StationName";
}
#endregion
#region IAbstractRecord Members
public new CT GetColumnValue<CT>(string columnName) {
return base.GetColumnValue<CT>(columnName);
}
public object GetColumnValue(string columnName) {
return base.GetColumnValue<object>(columnName);
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
using WeifenLuo.WinFormsUI.ThemeVS2005;
namespace WeifenLuo.WinFormsUI.Docking
{
[ToolboxItem(false)]
internal class VS2005DockPaneStrip : DockPaneStripBase
{
private class TabVS2005 : Tab
{
public TabVS2005(IDockContent content)
: base(content)
{
}
private int m_tabX;
public int TabX
{
get { return m_tabX; }
set { m_tabX = value; }
}
private int m_tabWidth;
public int TabWidth
{
get { return m_tabWidth; }
set { m_tabWidth = value; }
}
private int m_maxWidth;
public int MaxWidth
{
get { return m_maxWidth; }
set { m_maxWidth = value; }
}
private bool m_flag;
protected internal bool Flag
{
get { return m_flag; }
set { m_flag = value; }
}
}
protected override DockPaneStripBase.Tab CreateTab(IDockContent content)
{
return new TabVS2005(content);
}
[ToolboxItem(false)]
private sealed class InertButton : InertButtonBase
{
private Bitmap m_image0, m_image1;
public InertButton(Bitmap image0, Bitmap image1)
: base()
{
m_image0 = image0;
m_image1 = image1;
}
private int m_imageCategory = 0;
public int ImageCategory
{
get { return m_imageCategory; }
set
{
if (m_imageCategory == value)
return;
m_imageCategory = value;
Invalidate();
}
}
public override Bitmap Image
{
get { return ImageCategory == 0 ? m_image0 : m_image1; }
}
public override Bitmap HoverImage
{
get { return null; }
}
public override Bitmap PressImage
{
get { return null; }
}
}
#region Constants
private const int _ToolWindowStripGapTop = 0;
private const int _ToolWindowStripGapBottom = 1;
private const int _ToolWindowStripGapLeft = 0;
private const int _ToolWindowStripGapRight = 0;
private const int _ToolWindowImageHeight = 16;
private const int _ToolWindowImageWidth = 16;
private const int _ToolWindowImageGapTop = 3;
private const int _ToolWindowImageGapBottom = 1;
private const int _ToolWindowImageGapLeft = 2;
private const int _ToolWindowImageGapRight = 0;
private const int _ToolWindowTextGapRight = 3;
private const int _ToolWindowTabSeperatorGapTop = 3;
private const int _ToolWindowTabSeperatorGapBottom = 3;
private const int _DocumentStripGapTop = 0;
private const int _DocumentStripGapBottom = 1;
private const int _DocumentTabMaxWidth = 200;
private const int _DocumentButtonGapTop = 4;
private const int _DocumentButtonGapBottom = 4;
private const int _DocumentButtonGapBetween = 0;
private const int _DocumentButtonGapRight = 3;
private const int _DocumentTabGapTop = 3;
private const int _DocumentTabGapLeft = 3;
private const int _DocumentTabGapRight = 3;
private const int _DocumentIconGapBottom = 2;
private const int _DocumentIconGapLeft = 8;
private const int _DocumentIconGapRight = 0;
private const int _DocumentIconHeight = 16;
private const int _DocumentIconWidth = 16;
private const int _DocumentTextGapRight = 3;
#endregion
#region Members
private ContextMenuStrip m_selectMenu;
private Bitmap m_imageButtonClose;
private InertButton m_buttonClose;
private Bitmap m_imageButtonWindowList;
private Bitmap m_imageButtonWindowListOverflow;
private InertButton m_buttonWindowList;
private IContainer m_components;
private ToolTip m_toolTip;
private Font m_font;
private Font m_boldFont;
private int m_startDisplayingTab = 0;
private int m_endDisplayingTab = 0;
private int m_firstDisplayingTab = 0;
private bool m_documentTabsOverflow = false;
private string m_toolTipSelect;
private string m_toolTipClose;
private bool m_closeButtonVisible = false;
private int _selectMenuMargin = 5;
#endregion
#region Properties
private Rectangle TabStripRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.Document)
return TabStripRectangle_Document;
else
return TabStripRectangle_ToolWindow;
}
}
private Rectangle TabStripRectangle_ToolWindow
{
get
{
Rectangle rect = ClientRectangle;
return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom);
}
}
private Rectangle TabStripRectangle_Document
{
get
{
Rectangle rect = ClientRectangle;
return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height - DocumentStripGapTop - ToolWindowStripGapBottom);
}
}
private Rectangle TabsRectangle
{
get
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return TabStripRectangle;
Rectangle rectWindow = TabStripRectangle;
int x = rectWindow.X;
int y = rectWindow.Y;
int width = rectWindow.Width;
int height = rectWindow.Height;
x += DocumentTabGapLeft;
width -= DocumentTabGapLeft +
DocumentTabGapRight +
DocumentButtonGapRight +
ButtonClose.Width +
ButtonWindowList.Width +
2 * DocumentButtonGapBetween;
return new Rectangle(x, y, width, height);
}
}
private ContextMenuStrip SelectMenu
{
get { return m_selectMenu; }
}
public int SelectMenuMargin
{
get { return _selectMenuMargin; }
set { _selectMenuMargin = value; }
}
private Bitmap ImageButtonClose
{
get
{
if (m_imageButtonClose == null)
m_imageButtonClose = Resources.DockPane_Close;
return m_imageButtonClose;
}
}
private InertButton ButtonClose
{
get
{
if (m_buttonClose == null)
{
m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose);
m_toolTip.SetToolTip(m_buttonClose, ToolTipClose);
m_buttonClose.Click += new EventHandler(Close_Click);
Controls.Add(m_buttonClose);
}
return m_buttonClose;
}
}
private Bitmap ImageButtonWindowList
{
get
{
if (m_imageButtonWindowList == null)
m_imageButtonWindowList = Resources.DockPane_Option;
return m_imageButtonWindowList;
}
}
private Bitmap ImageButtonWindowListOverflow
{
get
{
if (m_imageButtonWindowListOverflow == null)
m_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow;
return m_imageButtonWindowListOverflow;
}
}
private InertButton ButtonWindowList
{
get
{
if (m_buttonWindowList == null)
{
m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow);
m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect);
m_buttonWindowList.Click += new EventHandler(WindowList_Click);
Controls.Add(m_buttonWindowList);
}
return m_buttonWindowList;
}
}
private GraphicsPath GraphicsPath { get; } = new GraphicsPath();
private IContainer Components
{
get { return m_components; }
}
public Font TextFont
{
get { return DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.TextFont; }
}
private Font BoldFont
{
get
{
if (IsDisposed)
return null;
if (m_boldFont == null)
{
m_font = TextFont;
m_boldFont = new Font(TextFont, FontStyle.Bold);
}
else if (m_font != TextFont)
{
m_boldFont.Dispose();
m_font = TextFont;
m_boldFont = new Font(TextFont, FontStyle.Bold);
}
return m_boldFont;
}
}
private int StartDisplayingTab
{
get { return m_startDisplayingTab; }
set
{
m_startDisplayingTab = value;
Invalidate();
}
}
private int EndDisplayingTab
{
get { return m_endDisplayingTab; }
set { m_endDisplayingTab = value; }
}
private int FirstDisplayingTab
{
get { return m_firstDisplayingTab; }
set { m_firstDisplayingTab = value; }
}
private bool DocumentTabsOverflow
{
set
{
if (m_documentTabsOverflow == value)
return;
m_documentTabsOverflow = value;
if (value)
ButtonWindowList.ImageCategory = 1;
else
ButtonWindowList.ImageCategory = 0;
}
}
#region Customizable Properties
private static int ToolWindowStripGapTop
{
get { return _ToolWindowStripGapTop; }
}
private static int ToolWindowStripGapBottom
{
get { return _ToolWindowStripGapBottom; }
}
private static int ToolWindowStripGapLeft
{
get { return _ToolWindowStripGapLeft; }
}
private static int ToolWindowStripGapRight
{
get { return _ToolWindowStripGapRight; }
}
private static int ToolWindowImageHeight
{
get { return _ToolWindowImageHeight; }
}
private static int ToolWindowImageWidth
{
get { return _ToolWindowImageWidth; }
}
private static int ToolWindowImageGapTop
{
get { return _ToolWindowImageGapTop; }
}
private static int ToolWindowImageGapBottom
{
get { return _ToolWindowImageGapBottom; }
}
private static int ToolWindowImageGapLeft
{
get { return _ToolWindowImageGapLeft; }
}
private static int ToolWindowImageGapRight
{
get { return _ToolWindowImageGapRight; }
}
private static int ToolWindowTextGapRight
{
get { return _ToolWindowTextGapRight; }
}
private static int ToolWindowTabSeperatorGapTop
{
get { return _ToolWindowTabSeperatorGapTop; }
}
private static int ToolWindowTabSeperatorGapBottom
{
get { return _ToolWindowTabSeperatorGapBottom; }
}
private string ToolTipClose
{
get
{
if (m_toolTipClose == null)
m_toolTipClose = Strings.DockPaneStrip_ToolTipClose;
return m_toolTipClose;
}
}
private string ToolTipSelect
{
get
{
if (m_toolTipSelect == null)
m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList;
return m_toolTipSelect;
}
}
private TextFormatFlags ToolWindowTextFormat
{
get
{
TextFormatFlags textFormat = TextFormatFlags.EndEllipsis |
TextFormatFlags.HorizontalCenter |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter;
if (RightToLeft == RightToLeft.Yes)
return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right;
else
return textFormat;
}
}
private static int DocumentStripGapTop
{
get { return _DocumentStripGapTop; }
}
private static int DocumentStripGapBottom
{
get { return _DocumentStripGapBottom; }
}
private TextFormatFlags DocumentTextFormat
{
get
{
TextFormatFlags textFormat = TextFormatFlags.EndEllipsis |
TextFormatFlags.SingleLine |
TextFormatFlags.VerticalCenter |
TextFormatFlags.HorizontalCenter;
if (RightToLeft == RightToLeft.Yes)
return textFormat | TextFormatFlags.RightToLeft;
else
return textFormat;
}
}
private static int DocumentTabMaxWidth
{
get { return _DocumentTabMaxWidth; }
}
private static int DocumentButtonGapTop
{
get { return _DocumentButtonGapTop; }
}
private static int DocumentButtonGapBottom
{
get { return _DocumentButtonGapBottom; }
}
private static int DocumentButtonGapBetween
{
get { return _DocumentButtonGapBetween; }
}
private static int DocumentButtonGapRight
{
get { return _DocumentButtonGapRight; }
}
private static int DocumentTabGapTop
{
get { return _DocumentTabGapTop; }
}
private static int DocumentTabGapLeft
{
get { return _DocumentTabGapLeft; }
}
private static int DocumentTabGapRight
{
get { return _DocumentTabGapRight; }
}
private static int DocumentIconGapBottom
{
get { return _DocumentIconGapBottom; }
}
private static int DocumentIconGapLeft
{
get { return _DocumentIconGapLeft; }
}
private static int DocumentIconGapRight
{
get { return _DocumentIconGapRight; }
}
private static int DocumentIconWidth
{
get { return _DocumentIconWidth; }
}
private static int DocumentIconHeight
{
get { return _DocumentIconHeight; }
}
private static int DocumentTextGapRight
{
get { return _DocumentTextGapRight; }
}
private Pen PenToolWindowTabBorder
{
get { return SystemPens.GrayText; }
}
private Pen PenDocumentTabActiveBorder
{
get { return SystemPens.ControlDarkDark; }
}
private Pen PenDocumentTabInactiveBorder
{
get { return SystemPens.GrayText; }
}
#endregion
#endregion
public VS2005DockPaneStrip(DockPane pane)
: base(pane)
{
SetStyle(ControlStyles.ResizeRedraw |
ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
ControlStyles.OptimizedDoubleBuffer, true);
SuspendLayout();
m_components = new Container();
m_toolTip = new ToolTip(Components);
m_selectMenu = new ContextMenuStrip(Components);
pane.DockPanel.Theme.ApplyTo(m_selectMenu);
ResumeLayout();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Components.Dispose();
if (m_boldFont != null)
{
m_boldFont.Dispose();
m_boldFont = null;
}
}
base.Dispose(disposing);
}
protected override int MeasureHeight()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return MeasureHeight_ToolWindow();
else
return MeasureHeight_Document();
}
private int MeasureHeight_ToolWindow()
{
if (DockPane.IsAutoHide || Tabs.Count <= 1)
return 0;
int height = Math.Max(TextFont.Height + (PatchController.EnableHighDpi == true ? DocumentIconGapBottom : 0),
ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom)
+ ToolWindowStripGapTop + ToolWindowStripGapBottom;
return height;
}
private int MeasureHeight_Document()
{
int height = Math.Max(TextFont.Height + DocumentTabGapTop + (PatchController.EnableHighDpi == true ? DocumentIconGapBottom : 0),
ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom)
+ DocumentStripGapBottom + DocumentStripGapTop;
return height;
}
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rect = TabsRectangle;
DockPanelGradient gradient = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient;
if (Appearance == DockPane.AppearanceStyle.Document)
{
rect.X -= DocumentTabGapLeft;
// Add these values back in so that the DockStrip color is drawn
// beneath the close button and window list button.
// It is possible depending on the DockPanel DocumentStyle to have
// a Document without a DockStrip.
rect.Width += DocumentTabGapLeft +
DocumentTabGapRight +
DocumentButtonGapRight +
ButtonClose.Width +
ButtonWindowList.Width;
}
else
{
gradient = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient;
}
Color startColor = gradient.StartColor;
Color endColor = gradient.EndColor;
LinearGradientMode gradientMode = gradient.LinearGradientMode;
DrawingRoutines.SafelyDrawLinearGradient(rect, startColor, endColor, gradientMode, e.Graphics);
base.OnPaint(e);
CalculateTabs();
if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null)
{
if (EnsureDocumentTabVisible(DockPane.ActiveContent, false))
CalculateTabs();
}
DrawTabStrip(e.Graphics);
}
protected override void OnRefreshChanges()
{
SetInertButtons();
Invalidate();
}
public override GraphicsPath GetOutline(int index)
{
if (Appearance == DockPane.AppearanceStyle.Document)
return GetOutline_Document(index);
else
return GetOutline_ToolWindow(index);
}
private GraphicsPath GetOutline_Document(int index)
{
Rectangle rectTab = Tabs[index].Rectangle.Value;
rectTab.X -= rectTab.Height / 2;
rectTab.Intersect(TabsRectangle);
rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab));
Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle);
GraphicsPath path = new GraphicsPath();
GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true);
path.AddPath(pathTab, true);
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top);
path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top);
path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top);
path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top);
path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top);
}
else
{
path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom);
path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom);
path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom);
path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom);
path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom);
}
return path;
}
private GraphicsPath GetOutline_ToolWindow(int index)
{
Rectangle rectTab = Tabs[index].Rectangle.Value;
rectTab.Intersect(TabsRectangle);
rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab));
Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle);
GraphicsPath path = new GraphicsPath();
GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true);
path.AddPath(pathTab, true);
path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top);
path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top);
path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top);
path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top);
path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top);
return path;
}
private void CalculateTabs()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
CalculateTabs_ToolWindow();
else
CalculateTabs_Document();
}
private void CalculateTabs_ToolWindow()
{
if (Tabs.Count <= 1 || DockPane.IsAutoHide)
return;
Rectangle rectTabStrip = TabStripRectangle;
// Calculate tab widths
int countTabs = Tabs.Count;
foreach (TabVS2005 tab in Tabs)
{
tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab));
tab.Flag = false;
}
// Set tab whose max width less than average width
bool anyWidthWithinAverage = true;
int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight;
int totalAllocatedWidth = 0;
int averageWidth = totalWidth / countTabs;
int remainedTabs = countTabs;
for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; )
{
anyWidthWithinAverage = false;
foreach (TabVS2005 tab in Tabs)
{
if (tab.Flag)
continue;
if (tab.MaxWidth <= averageWidth)
{
tab.Flag = true;
tab.TabWidth = tab.MaxWidth;
totalAllocatedWidth += tab.TabWidth;
anyWidthWithinAverage = true;
remainedTabs--;
}
}
if (remainedTabs != 0)
averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs;
}
// If any tab width not set yet, set it to the average width
if (remainedTabs > 0)
{
int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs);
foreach (TabVS2005 tab in Tabs)
{
if (tab.Flag)
continue;
tab.Flag = true;
if (roundUpWidth > 0)
{
tab.TabWidth = averageWidth + 1;
roundUpWidth--;
}
else
tab.TabWidth = averageWidth;
}
}
// Set the X position of the tabs
int x = rectTabStrip.X + ToolWindowStripGapLeft;
foreach (TabVS2005 tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index)
{
bool overflow = false;
TabVS2005 tab = Tabs[index] as TabVS2005;
tab.MaxWidth = GetMaxTabWidth(index);
int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth);
if (x + width < rectTabStrip.Right || index == StartDisplayingTab)
{
tab.TabX = x;
tab.TabWidth = width;
EndDisplayingTab = index;
}
else
{
tab.TabX = 0;
tab.TabWidth = 0;
overflow = true;
}
x += width;
return overflow;
}
/// <summary>
/// Calculate which tabs are displayed and in what order.
/// </summary>
private void CalculateTabs_Document()
{
if (m_startDisplayingTab >= Tabs.Count)
m_startDisplayingTab = 0;
Rectangle rectTabStrip = TabsRectangle;
int x = rectTabStrip.X + rectTabStrip.Height / 2;
bool overflow = false;
// Originally all new documents that were considered overflow
// (not enough pane strip space to show all tabs) were added to
// the far left (assuming not right to left) and the tabs on the
// right were dropped from view. If StartDisplayingTab is not 0
// then we are dealing with making sure a specific tab is kept in focus.
if (m_startDisplayingTab > 0)
{
int tempX = x;
TabVS2005 tab = Tabs[m_startDisplayingTab] as TabVS2005;
tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab);
// Add the active tab and tabs to the left
for (int i = StartDisplayingTab; i >= 0; i--)
CalculateDocumentTab(rectTabStrip, ref tempX, i);
// Store which tab is the first one displayed so that it
// will be drawn correctly (without part of the tab cut off)
FirstDisplayingTab = EndDisplayingTab;
tempX = x; // Reset X location because we are starting over
// Start with the first tab displayed - name is a little misleading.
// Loop through each tab and set its location. If there is not enough
// room for all of them overflow will be returned.
for (int i = EndDisplayingTab; i < Tabs.Count; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i);
// If not all tabs are shown then we have an overflow.
if (FirstDisplayingTab != 0)
overflow = true;
}
else
{
for (int i = StartDisplayingTab; i < Tabs.Count; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref x, i);
for (int i = 0; i < StartDisplayingTab; i++)
overflow = CalculateDocumentTab(rectTabStrip, ref x, i);
FirstDisplayingTab = StartDisplayingTab;
}
if (!overflow)
{
m_startDisplayingTab = 0;
FirstDisplayingTab = 0;
x = rectTabStrip.X + rectTabStrip.Height / 2;
foreach (TabVS2005 tab in Tabs)
{
tab.TabX = x;
x += tab.TabWidth;
}
}
DocumentTabsOverflow = overflow;
}
protected override void EnsureTabVisible(IDockContent content)
{
if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content))
return;
CalculateTabs();
EnsureDocumentTabVisible(content, true);
}
private bool EnsureDocumentTabVisible(IDockContent content, bool repaint)
{
int index = Tabs.IndexOf(content);
if (index == -1)
{
//somehow we've lost the content from the Tab collection
return false;
}
TabVS2005 tab = Tabs[index] as TabVS2005;
if (tab.TabWidth != 0)
return false;
StartDisplayingTab = index;
if (repaint)
Invalidate();
return true;
}
private int GetMaxTabWidth(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetMaxTabWidth_ToolWindow(index);
else
return GetMaxTabWidth_Document(index);
}
private int GetMaxTabWidth_ToolWindow(int index)
{
IDockContent content = Tabs[index].Content;
Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont);
return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft
+ ToolWindowImageGapRight + ToolWindowTextGapRight;
}
private int GetMaxTabWidth_Document(int index)
{
IDockContent content = Tabs[index].Content;
int height = GetTabRectangle_Document(index).Height;
Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat);
if (DockPane.DockPanel.ShowDocumentIcon)
return sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight;
else
return sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight;
}
private void DrawTabStrip(Graphics g)
{
if (Appearance == DockPane.AppearanceStyle.Document)
DrawTabStrip_Document(g);
else
DrawTabStrip_ToolWindow(g);
}
private void DrawTabStrip_Document(Graphics g)
{
int count = Tabs.Count;
if (count == 0)
return;
Rectangle rectTabStrip = TabStripRectangle;
// Draw the tabs
Rectangle rectTabOnly = TabsRectangle;
Rectangle rectTab = Rectangle.Empty;
TabVS2005 tabActive = null;
g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly));
for (int i = 0; i < count; i++)
{
rectTab = GetTabRectangle(i);
if (Tabs[i].Content == DockPane.ActiveContent)
{
tabActive = Tabs[i] as TabVS2005;
tabActive.Rectangle = rectTab;
continue;
}
if (rectTab.IntersectsWith(rectTabOnly))
{
var tab = Tabs[i] as TabVS2005;
tab.Rectangle = rectTab;
DrawTab(g, tab);
}
}
g.SetClip(rectTabStrip);
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1,
rectTabStrip.Right, rectTabStrip.Top + 1);
else
g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Bottom - 1,
rectTabStrip.Right, rectTabStrip.Bottom - 1);
g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly));
if (tabActive != null)
{
rectTab = tabActive.Rectangle.Value;
if (rectTab.IntersectsWith(rectTabOnly))
{
rectTab.Intersect(rectTabOnly);
tabActive.Rectangle = rectTab;
DrawTab(g, tabActive);
}
}
}
private void DrawTabStrip_ToolWindow(Graphics g)
{
Rectangle rectTabStrip = TabStripRectangle;
g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top,
rectTabStrip.Right, rectTabStrip.Top);
for (int i = 0; i < Tabs.Count; i++)
{
var tab = Tabs[i] as TabVS2005;
tab.Rectangle = GetTabRectangle(i);
DrawTab(g, tab);
}
}
private Rectangle GetTabRectangle(int index)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabRectangle_ToolWindow(index);
else
return GetTabRectangle_Document(index);
}
private Rectangle GetTabRectangle_ToolWindow(int index)
{
Rectangle rectTabStrip = TabStripRectangle;
TabVS2005 tab = (TabVS2005)(Tabs[index]);
return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height);
}
private Rectangle GetTabRectangle_Document(int index)
{
Rectangle rectTabStrip = TabStripRectangle;
TabVS2005 tab = (TabVS2005)Tabs[index];
Rectangle rect = new Rectangle();
rect.X = tab.TabX;
rect.Width = tab.TabWidth;
rect.Height = rectTabStrip.Height - DocumentTabGapTop;
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
rect.Y = rectTabStrip.Y + DocumentStripGapBottom;
else
rect.Y = rectTabStrip.Y + DocumentTabGapTop;
return rect;
}
private void DrawTab(Graphics g, TabVS2005 tab)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
DrawTab_ToolWindow(g, tab);
else
DrawTab_Document(g, tab);
}
private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen)
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen);
else
return GetTabOutline_Document(tab, rtlTransform, toScreen, false);
}
private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen)
{
Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab));
if (rtlTransform)
rect = DrawHelper.RtlTransform(this, rect);
if (toScreen)
rect = RectangleToScreen(rect);
DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false);
return GraphicsPath;
}
private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full)
{
int curveSize = 6;
GraphicsPath.Reset();
Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab));
// Shorten TabOutline so it doesn't get overdrawn by icons next to it
rect.Intersect(TabsRectangle);
rect.Width--;
if (rtlTransform)
rect = DrawHelper.RtlTransform(this, rect);
if (toScreen)
rect = RectangleToScreen(rect);
// Draws the full angle piece for active content (or first tab)
if (tab.Content == DockPane.ActiveContent || full || Tabs.IndexOf(tab) == FirstDisplayingTab)
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top.
// It is not needed so it has been commented out.
//GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Top, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Bottom, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top.
// It is not needed so it has been commented out.
//GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left - rect.Height / 2, rect.Top);
GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Top, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left - rect.Height / 2, rect.Bottom);
GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Bottom, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2);
}
}
}
// Draws the partial angle for non-active content
else
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Right, rect.Top, rect.Right, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2);
}
}
}
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Bottom, rect.Left + curveSize / 2, rect.Bottom);
// Drawing the rounded corner is not necessary. The path is automatically connected
//GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90);
}
else
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Top, rect.Left + curveSize / 2, rect.Top);
GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
// Draws the bottom horizontal line (short side)
GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Bottom, rect.Right - curveSize / 2, rect.Bottom);
// Drawing the rounded corner is not necessary. The path is automatically connected
//GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Bottom, curveSize, curveSize), 90, -90);
}
else
{
// Draws the top horizontal line (short side)
GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Top, rect.Right - curveSize / 2, rect.Top);
// Draws the rounded corner oppposite the angled side
GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Top, curveSize, curveSize), -90, 90);
}
}
if (Tabs.IndexOf(tab) != EndDisplayingTab &&
(Tabs.IndexOf(tab) != Tabs.Count - 1 && Tabs[Tabs.IndexOf(tab) + 1].Content == DockPane.ActiveContent)
&& !full)
{
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2, rect.Top);
}
else
{
GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2, rect.Bottom);
}
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
{
GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Bottom - rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2, rect.Top);
}
else
{
GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Top + rect.Height / 2);
GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2, rect.Bottom);
}
}
}
else
{
// Draw the vertical line opposite the angled side
if (RightToLeft == RightToLeft.Yes)
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Top);
else
GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Bottom);
}
else
{
if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom)
GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Top);
else
GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Bottom);
}
}
return GraphicsPath;
}
private void DrawTab_ToolWindow(Graphics g, TabVS2005 tab)
{
var rect = tab.Rectangle.Value;
Rectangle rectIcon = new Rectangle(
rect.X + ToolWindowImageGapLeft,
rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight,
ToolWindowImageWidth, ToolWindowImageHeight);
Rectangle rectText = PatchController.EnableHighDpi == true
? new Rectangle(
rect.X + ToolWindowImageGapLeft,
rect.Y - 1 + rect.Height - ToolWindowImageGapBottom - TextFont.Height,
ToolWindowImageWidth, TextFont.Height)
: rectIcon;
rectText.X += rectIcon.Width + ToolWindowImageGapRight;
rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft -
ToolWindowImageGapRight - ToolWindowTextGapRight;
Rectangle rectTab = DrawHelper.RtlTransform(this, rect);
rectText = DrawHelper.RtlTransform(this, rectText);
rectIcon = DrawHelper.RtlTransform(this, rectIcon);
GraphicsPath path = GetTabOutline(tab, true, false);
if (DockPane.ActiveContent == tab.Content)
{
Color startColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode;
using (LinearGradientBrush brush = new LinearGradientBrush(rectTab, startColor, endColor, gradientMode))
{
g.FillPath(brush, path);
}
g.DrawPath(PenToolWindowTabBorder, path);
Color textColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat);
}
else
{
Color startColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.LinearGradientMode;
using (LinearGradientBrush brush1 = new LinearGradientBrush(rectTab, startColor, endColor, gradientMode))
{
g.FillPath(brush1, path);
}
if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1)
{
Point pt1 = new Point(rect.Right, rect.Top + ToolWindowTabSeperatorGapTop);
Point pt2 = new Point(rect.Right, rect.Bottom - ToolWindowTabSeperatorGapBottom);
g.DrawLine(PenToolWindowTabBorder, DrawHelper.RtlTransform(this, pt1), DrawHelper.RtlTransform(this, pt2));
}
Color textColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat);
}
if (rectTab.Contains(rectIcon))
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
private void DrawTab_Document(Graphics g, TabVS2005 tab)
{
var rect = tab.Rectangle.Value;
if (tab.TabWidth == 0)
return;
Rectangle rectIcon = new Rectangle(
rect.X + DocumentIconGapLeft,
rect.Y + rect.Height - 1 - DocumentIconGapBottom - DocumentIconHeight,
DocumentIconWidth, DocumentIconHeight);
Rectangle rectText = PatchController.EnableHighDpi == true
? new Rectangle(
rect.X + DocumentIconGapLeft,
rect.Y + rect.Height - DocumentIconGapBottom - TextFont.Height,
DocumentIconWidth, TextFont.Height)
: rectIcon;
if (DockPane.DockPanel.ShowDocumentIcon)
{
rectText.X += rectIcon.Width + DocumentIconGapRight;
rectText.Y = rect.Y;
rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft -
DocumentIconGapRight - DocumentTextGapRight;
rectText.Height = rect.Height;
}
else
rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight;
Rectangle rectTab = DrawHelper.RtlTransform(this, rect);
Rectangle rectBack = DrawHelper.RtlTransform(this, rect);
rectBack.Width += DocumentIconGapLeft;
rectBack.X -= DocumentIconGapLeft;
rectText = DrawHelper.RtlTransform(this, rectText);
rectIcon = DrawHelper.RtlTransform(this, rectIcon);
GraphicsPath path = GetTabOutline(tab, true, false);
if (DockPane.ActiveContent == tab.Content)
{
Color startColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.LinearGradientMode;
using (LinearGradientBrush brush = new LinearGradientBrush(rectBack, startColor, endColor, gradientMode))
{
g.FillPath(brush, path);
}
g.DrawPath(PenDocumentTabActiveBorder, path);
Color textColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor;
if (DockPane.IsActiveDocumentPane)
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, BoldFont, rectText, textColor, DocumentTextFormat);
else
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat);
}
else
{
Color startColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor;
Color endColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor;
LinearGradientMode gradientMode = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.LinearGradientMode;
using (LinearGradientBrush brush1 = new LinearGradientBrush(rectBack, startColor, endColor, gradientMode))
{
g.FillPath(brush1, path);
}
g.DrawPath(PenDocumentTabInactiveBorder, path);
Color textColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor;
TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat);
}
if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon)
g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon);
}
private void WindowList_Click(object sender, EventArgs e)
{
SelectMenu.Items.Clear();
foreach (TabVS2005 tab in Tabs)
{
IDockContent content = tab.Content;
ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap());
item.Tag = tab.Content;
item.Click += new EventHandler(ContextMenuItem_Click);
}
var workingArea = Screen.GetWorkingArea(ButtonWindowList.PointToScreen(new Point(ButtonWindowList.Width / 2, ButtonWindowList.Height / 2)));
var menu = new Rectangle(ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Location.Y + ButtonWindowList.Height)), SelectMenu.Size);
var menuMargined = new Rectangle(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, menu.Width + SelectMenuMargin, menu.Height + SelectMenuMargin);
if (workingArea.Contains(menuMargined))
{
SelectMenu.Show(menu.Location);
}
else
{
var newPoint = menu.Location;
newPoint.X = DrawHelper.Balance(SelectMenu.Width, SelectMenuMargin, newPoint.X, workingArea.Left, workingArea.Right);
newPoint.Y = DrawHelper.Balance(SelectMenu.Size.Height, SelectMenuMargin, newPoint.Y, workingArea.Top, workingArea.Bottom);
var button = ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Height));
if (newPoint.Y < button.Y)
{
// flip the menu up to be above the button.
newPoint.Y = button.Y - ButtonWindowList.Height;
SelectMenu.Show(newPoint, ToolStripDropDownDirection.AboveRight);
}
else
{
SelectMenu.Show(newPoint);
}
}
}
private void ContextMenuItem_Click(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
if (item != null)
{
IDockContent content = (IDockContent)item.Tag;
DockPane.ActiveContent = content;
}
}
private void SetInertButtons()
{
if (Appearance == DockPane.AppearanceStyle.ToolWindow)
{
if (m_buttonClose != null)
m_buttonClose.Left = -m_buttonClose.Width;
if (m_buttonWindowList != null)
m_buttonWindowList.Left = -m_buttonWindowList.Width;
}
else
{
ButtonClose.Enabled = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton;
m_closeButtonVisible = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButtonVisible;
ButtonClose.Visible = m_closeButtonVisible;
ButtonClose.RefreshChanges();
ButtonWindowList.RefreshChanges();
}
}
protected override void OnLayout(LayoutEventArgs levent)
{
if (Appearance == DockPane.AppearanceStyle.Document)
{
LayoutButtons();
OnRefreshChanges();
}
base.OnLayout(levent);
}
private void LayoutButtons()
{
Rectangle rectTabStrip = TabStripRectangle;
// Set position and size of the buttons
int buttonWidth = ButtonClose.Image.Width;
int buttonHeight = ButtonClose.Image.Height;
int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom;
if (buttonHeight < height)
{
buttonWidth = buttonWidth * height / buttonHeight;
buttonHeight = height;
}
Size buttonSize = new Size(buttonWidth, buttonHeight);
int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft
- DocumentButtonGapRight - buttonWidth;
int y = rectTabStrip.Y + DocumentButtonGapTop;
Point point = new Point(x, y);
ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
// If the close button is not visible draw the window list button overtop.
// Otherwise it is drawn to the left of the close button.
if (m_closeButtonVisible)
point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0);
ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize));
}
private void Close_Click(object sender, EventArgs e)
{
DockPane.CloseActiveContent();
if (PatchController.EnableMemoryLeakFix == true)
{
ContentClosed();
}
}
protected override int HitTest(Point point)
{
if (!TabsRectangle.Contains(point))
return -1;
foreach (Tab tab in Tabs)
{
GraphicsPath path = GetTabOutline(tab, true, false);
if (path.IsVisible(point))
return Tabs.IndexOf(tab);
}
return -1;
}
protected override Rectangle GetTabBounds(Tab tab)
{
GraphicsPath path = GetTabOutline(tab, true, false);
RectangleF rectangle = path.GetBounds();
return new Rectangle((int)rectangle.Left, (int)rectangle.Top, (int)rectangle.Width, (int)rectangle.Height);
}
protected override void OnMouseHover(EventArgs e)
{
int index = HitTest(PointToClient(Control.MousePosition));
string toolTip = string.Empty;
base.OnMouseHover(e);
if (index != -1)
{
TabVS2005 tab = Tabs[index] as TabVS2005;
if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText))
toolTip = tab.Content.DockHandler.ToolTipText;
else if (tab.MaxWidth > tab.TabWidth)
toolTip = tab.Content.DockHandler.TabText;
}
if (m_toolTip.GetToolTip(this) != toolTip)
{
m_toolTip.Active = false;
m_toolTip.SetToolTip(this, toolTip);
m_toolTip.Active = true;
}
// requires further tracking of mouse hover behavior,
ResetMouseEventArgs();
}
protected override void OnRightToLeftChanged(EventArgs e)
{
base.OnRightToLeftChanged(e);
PerformLayout();
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
using Rimss.GraphicsProcessing.Palette.Helpers.Pixels;
using Rimss.GraphicsProcessing.Palette.Helpers.Pixels.Indexed;
using Rimss.GraphicsProcessing.Palette.Helpers.Pixels.NonIndexed;
namespace Rimss.GraphicsProcessing.Palette.Helpers
{
/// <summary>
/// This is a pixel format independent pixel.
/// </summary>
public class Pixel : IDisposable
{
#region | Constants |
internal const Byte Zero = 0;
internal const Byte One = 1;
internal const Byte Two = 2;
internal const Byte Four = 4;
internal const Byte Eight = 8;
internal const Byte NibbleMask = 0xF;
internal const Byte ByteMask = 0xFF;
internal const Int32 AlphaShift = 24;
internal const Int32 RedShift = 16;
internal const Int32 GreenShift = 8;
internal const Int32 BlueShift = 0;
internal const Int32 AlphaMask = ByteMask << AlphaShift;
internal const Int32 RedGreenBlueMask = 0xFFFFFF;
#endregion
#region | Fields |
private Type pixelType;
private Int32 bitOffset;
private Object pixelData;
private IntPtr pixelDataPointer;
#endregion
#region | Properties |
/// <summary>
/// Gets the X.
/// </summary>
public Int32 X { get; private set; }
/// <summary>
/// Gets the Y.
/// </summary>
public Int32 Y { get; private set; }
/// <summary>
/// Gets the parent buffer.
/// </summary>
public ImageBuffer Parent { get; private set; }
#endregion
#region | Calculated properties |
/// <summary>
/// Gets or sets the index.
/// </summary>
/// <value>The index.</value>
public Byte Index
{
get { return ((IIndexedPixel) pixelData).GetIndex(bitOffset); }
set { ((IIndexedPixel) pixelData).SetIndex(bitOffset, value); }
}
/// <summary>
/// Gets or sets the color.
/// </summary>
/// <value>The color.</value>
public Color Color
{
get { return ((INonIndexedPixel) pixelData).GetColor(); }
set { ((INonIndexedPixel) pixelData).SetColor(value); }
}
/// <summary>
/// Gets a value indicating whether this instance is indexed.
/// </summary>
/// <value>
/// <c>true</c> if this instance is indexed; otherwise, <c>false</c>.
/// </value>
public Boolean IsIndexed
{
get { return Parent.IsIndexed; }
}
#endregion
#region | Constructors |
/// <summary>
/// Initializes a new instance of the <see cref="Pixel"/> struct.
/// </summary>
public Pixel(ImageBuffer parent)
{
Parent = parent;
Initialize();
}
private void Initialize()
{
// creates pixel data
pixelType = IsIndexed ? GetIndexedType(Parent.PixelFormat) : GetNonIndexedType(Parent.PixelFormat);
NewExpression newType = Expression.New(pixelType);
UnaryExpression convertNewType = Expression.Convert(newType, typeof (Object));
Expression<Func<Object>> indexedExpression = Expression.Lambda<Func<Object>>(convertNewType);
pixelData = indexedExpression.Compile().Invoke();
pixelDataPointer = MarshalToPointer(pixelData);
}
#endregion
#region | Methods |
/// <summary>
/// Gets the type of the indexed pixel format.
/// </summary>
internal Type GetIndexedType(PixelFormat pixelFormat)
{
switch (pixelFormat)
{
case PixelFormat.Format1bppIndexed: return typeof(PixelData1Indexed);
case PixelFormat.Format4bppIndexed: return typeof(PixelData4Indexed);
case PixelFormat.Format8bppIndexed: return typeof(PixelData8Indexed);
default:
String message = String.Format("This pixel format '{0}' is either non-indexed, or not supported.", pixelFormat);
throw new NotSupportedException(message);
}
}
/// <summary>
/// Gets the type of the non-indexed pixel format.
/// </summary>
internal Type GetNonIndexedType(PixelFormat pixelFormat)
{
switch (pixelFormat)
{
case PixelFormat.Format16bppArgb1555: return typeof(PixelDataArgb1555);
case PixelFormat.Format16bppGrayScale: return typeof(PixelDataGray16);
case PixelFormat.Format16bppRgb555: return typeof(PixelDataRgb555);
case PixelFormat.Format16bppRgb565: return typeof(PixelDataRgb565);
case PixelFormat.Format24bppRgb: return typeof(PixelDataRgb888);
case PixelFormat.Format32bppRgb: return typeof(PixelDataRgb8888);
case PixelFormat.Format32bppArgb: return typeof(PixelDataArgb8888);
case PixelFormat.Format48bppRgb: return typeof(PixelDataRgb48);
case PixelFormat.Format64bppArgb: return typeof(PixelDataArgb64);
default:
String message = String.Format("This pixel format '{0}' is either indexed, or not supported.", pixelFormat);
throw new NotSupportedException(message);
}
}
private static IntPtr MarshalToPointer(Object data)
{
Int32 size = Marshal.SizeOf(data);
IntPtr pointer = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(data, pointer, false);
return pointer;
}
#endregion
#region | Update methods |
/// <param name="x">The X coordinate.</param>
/// <param name="y">The Y coordinate.</param>
public void Update(Int32 x, Int32 y)
{
X = x;
Y = y;
bitOffset = Parent.GetBitOffset(x);
}
/// <summary>
/// Reads the raw data.
/// </summary>
/// <param name="imagePointer">The image pointer.</param>
public void ReadRawData(IntPtr imagePointer)
{
pixelData = Marshal.PtrToStructure(imagePointer, pixelType);
}
/// <summary>
/// Reads the data.
/// </summary>
/// <param name="buffer">The buffer.</param>
/// <param name="offset">The offset.</param>
public void ReadData(Byte[] buffer, Int32 offset)
{
Marshal.Copy(buffer, offset, pixelDataPointer, Parent.BytesPerPixel);
pixelData = Marshal.PtrToStructure(pixelDataPointer, pixelType);
}
/// <summary>
/// Writes the raw data.
/// </summary>
/// <param name="imagePointer">The image pointer.</param>
public void WriteRawData(IntPtr imagePointer)
{
Marshal.StructureToPtr(pixelData, imagePointer, false);
}
/// <summary>
/// Writes the data.
/// </summary>
/// <param name="buffer">The buffer.</param>
/// <param name="offset">The offset.</param>
public void WriteData(Byte[] buffer, Int32 offset)
{
Marshal.Copy(pixelDataPointer, buffer, offset, Parent.BytesPerPixel);
}
#endregion
#region << IDisposable >>
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Marshal.FreeHGlobal(pixelDataPointer);
}
#endregion
}
}
| |
//////////////////////////////////////////////////////////////////////////////////////////////////
//
// file: layerShadow.cs
//
// composition toolkit
//
// Author Sergey Solokhin (Neill3d)
//
// GitHub page - https://github.com/Neill3d/MoPlugs
// Licensed under BSD 3-Clause - https://github.com/Neill3d/MoPlugs/blob/master/LICENSE
//
///////////////////////////////////////////////////////////////////////////////////////////////////
uniform vec2 outputSize; // stored in a format ( 1.0/w, 1.0/h )
uniform vec2 renderSize;
uniform vec2 renderBorder;
uniform float previewScaleFactor; // 1.0 for full image, 0.5 for half size
layout(binding=0, rgba8) uniform writeonly image2D resultImage;
//layout(binding=5) uniform sampler2D positionSampler;
// #define SAMPLES 4
#ifdef USE_MS
layout(binding=5) uniform sampler2DMS positionSampler;
#else
layout(binding=5) uniform sampler2D positionSampler;
#endif
// custom sampler
//layout(binding=3) uniform sampler2DArrayShadow shadowsSampler;
#ifdef ENABLE_MS
layout(binding=3) uniform sampler2DMSArray shadowsSampler;
#else
layout(binding=3) uniform sampler2DArray shadowsSampler;
#endif
struct LayerData
{
float density;
float feather;
float near;
float far;
vec4 zoneInfo; // x - number of volume models
};
struct ZoneData
{
float density;
float feather;
float bias;
float Id;
vec4 volumeMin;
vec4 volumeMax;
mat4 lightMatrix;
mat4 invMatrix;
};
layout (std430, binding = 0) buffer LayerBuffer
{
LayerData data;
} layerBuffer;
layout (std430, binding = 1) buffer ZoneBuffer
{
ZoneData zones[];
} zoneBuffer;
///////////////////////////////////////////////////////////////////////////////
//
#ifdef ENABLE_MS
const int samplerSamples = 8;
#endif
const int ditherSamples = 9;
vec2 poissonDisk[16] = vec2[](
vec2( -0.94201624, -0.39906216 ),
vec2( 0.94558609, -0.76890725 ),
vec2( -0.094184101, -0.92938870 ),
vec2( 0.34495938, 0.29387760 ),
vec2( -0.84201624, -0.49906216 ),
vec2( 0.74558609, -0.66890725 ),
vec2( -0.294184101, -0.72938870 ),
vec2( 0.24495938, 0.19387760 ),
vec2( -0.54201624, -0.29906216 ),
vec2( 0.64558609, -0.36890725 ),
vec2( -0.394184101, -0.62938870 ),
vec2( 0.14495938, 0.49387760 ),
vec2( -0.14201624, -0.32906216 ),
vec2( 0.14558609, -0.86890725 ),
vec2( -0.994184101, -0.12938870 ),
vec2( 0.49495938, 0.22387760 )
);
void ComputeVolumeShadow(inout float shadow, in float shadowSize, in int index, in vec3 position, in vec2 texCoord)
{
vec4 p = zoneBuffer.zones[index].invMatrix * vec4(position, 1.0);
vec4 volumeMax = zoneBuffer.zones[index].volumeMax;
vec4 volumeMin = zoneBuffer.zones[index].volumeMin;
float distToBorder = p.x - volumeMin.x;
distToBorder = min(distToBorder, volumeMax.x - p.x);
distToBorder = min(distToBorder, p.y - volumeMin.y);
distToBorder = min(distToBorder, volumeMax.y - p.y);
distToBorder = min(distToBorder, p.z - volumeMin.z);
distToBorder = min(distToBorder, volumeMax.z - p.z);
distToBorder = clamp(distToBorder, 0.0, 1.0);
float zoneFactor = smoothstep(0.0, zoneBuffer.zones[index].feather, distToBorder);
if (zoneFactor <= 0.0)
return;
vec4 ShadowCoord = zoneBuffer.zones[index].lightMatrix * vec4(position, 1.0);
ShadowCoord /= ShadowCoord.w;
ShadowCoord.xyz = ShadowCoord.xyz * vec3 (0.5) + vec3 (0.5);
//float a = texture(shadowsSampler, vec4(ShadowCoord.x, ShadowCoord.y, 0.0, ShadowCoord.z) ); // vec3(ShadowCoord.xy, 0.0)
//color = vec4(a, a, a, 1.0);
vec3 coords = vec3(ShadowCoord.x, ShadowCoord.y, zoneBuffer.zones[index].Id);
float bias = zoneBuffer.zones[index].bias;
float visibility = 0.0;
if (coords.x >= 0.0 && coords.x <= 1.0 && coords.y >= 0.0 && coords.y <=1.0)
{
vec2 vShadowSize = vec2(shadowSize, shadowSize);
#ifdef ENABLE_MS
for (int i=0; i<4; ++i)
{
//coords.xy = ShadowSize * (ShadowCoord.xy + poissonDisk[i]/700.0);
coords.xy = vShadowSize * ShadowCoord.xy;
float value = texelFetch(shadowsSampler, ivec3(coords), i ).z;
if (value > ShadowCoord.z-bias)
visibility += 0.25;
}
#else
for (int i=0; i<4; ++i)
{
coords.xy = vShadowSize * (ShadowCoord.xy + poissonDisk[i]/700.0);
//coords.xy = vShadowSize * ShadowCoord.xy;
float value = texelFetch(shadowsSampler, ivec3(coords), 0 ).z;
if (value > ShadowCoord.z-bias)
visibility += 0.25;
}
#endif
// we are on a shadow edge, do a strong filtering !
if (visibility > 0.01 || visibility < 0.99)
{
visibility = 0.0;
#ifdef ENABLE_MS
const float fstep = 1.0 / samplerSamples;
#else
const float fstep = 1.0;
#endif
for (int nsample=0; nsample<ditherSamples; ++nsample)
{
coords.xy = vShadowSize * (ShadowCoord.xy + poissonDisk[nsample]/700.0);
float value = texelFetch(shadowsSampler, ivec3(coords), 0 ).z; // vec3(ShadowCoord.xy, 0.0)
if ( value < ShadowCoord.z-bias )
{
visibility += fstep;
}
#ifdef ENABLE_MS
for (int i=1; i<samplerSamples; ++i)
{
float value = texelFetch(shadowsSampler, ivec3(coords), i ).z; // vec3(ShadowCoord.xy, 0.0)
if ( value < ShadowCoord.z-bias )
{
visibility += fstep;
}
}
#endif
}
visibility /= ditherSamples;
//visibility = 1.0 - visibility;
}
}
float density = zoneBuffer.zones[index].density;
//visibility *= (1.0 - density * zoneFactor);
//shadow = min(shadow, visibility);
shadow = max(shadow, clamp(visibility * density * zoneFactor, 0.0, 1.0) );
//shadow = shadow + clamp(visibility * density * zoneFactor, 0.0, 1.0);
//shadow = mix(shadow, visibility, density * zoneFactor);
//color.rgb = mix(color.rgb, vec3(visibility), density * zoneFactor);
}
float ComputeShadows(in int nsample, in vec2 texCoord, in ivec2 pixelPosition)
{
#ifdef USE_MS
vec4 p = texelFetch(positionSampler, pixelPosition, nsample); // we store receiveShadows in .w
#else
vec4 p = texture(positionSampler, texCoord); // we store receiveShadows in .w
#endif
float shadow = 0.0;
if (p.w > 0.0)
{
#ifdef ENABLE_MS
ivec3 iShadowSize = textureSize(shadowsSampler);
#else
ivec3 iShadowSize = textureSize(shadowsSampler, 0);
#endif
float shadowSize = float(iShadowSize.x);
int count = int(layerBuffer.data.zoneInfo.x);
for (int i=0; i<count; ++i)
{
ComputeVolumeShadow(shadow, shadowSize, i, p.xyz, texCoord);
}
}
return shadow;
}
void main ()
{
ivec2 pixelPosition = ivec2(gl_GlobalInvocationID.xy);
vec2 texCoord = vec2(outputSize.x * (0.5 + pixelPosition.x), outputSize.y * (0.5 + pixelPosition.y));
//vec2 texRenderCoord = vec2(renderSize.x * (0.5 + 2.0*pixelPosition.x), renderSize.y * (0.5 + 2.0*pixelPosition.y));
float shadow = 0.0;
/*
vec4 p = texture(positionSampler, texCoord); // we store receiveShadows in .w
float shadow = 0.0;
if (p.w > 0.0)
{
#ifdef ENABLE_MS
ivec3 iShadowSize = textureSize(shadowsSampler);
#else
ivec3 iShadowSize = textureSize(shadowsSampler, 0);
#endif
float shadowSize = float(iShadowSize.x);
int count = int(layerBuffer.data.zoneInfo.x);
for (int i=0; i<count; ++i)
{
ComputeVolumeShadow(shadow, shadowSize, i, p.xyz, texCoord);
}
}
*/
#ifdef USE_MS
for (int i=0; i<SAMPLES; ++i)
{
shadow = shadow + ComputeShadows(i, texCoord, pixelPosition);
}
shadow = shadow / SAMPLES;
#else
shadow = ComputeShadows(0, texCoord, pixelPosition);
#endif
shadow = 1.0 - clamp(shadow, 0.0, 1.0);
imageStore(resultImage, pixelPosition, vec4(shadow, shadow, shadow, 1.0));
}
| |
//
// Certificate.cs: Implements the managed SecCertificate wrapper.
//
// Authors:
// Miguel de Icaza
// Sebastien Pouliot <[email protected]>
//
// Copyright 2010 Novell, Inc
// Copyright 2012 Xamarin Inc.
//
// 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.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using MonoMac.ObjCRuntime;
using MonoMac.CoreFoundation;
using MonoMac.Foundation;
namespace MonoMac.Security {
public class SecCertificate : INativeObject, IDisposable {
internal IntPtr handle;
// invoked by marshallers
internal SecCertificate (IntPtr handle)
: this (handle, false)
{
}
[Preserve (Conditional = true)]
internal SecCertificate (IntPtr handle, bool owns)
{
if (handle == IntPtr.Zero)
throw new Exception ("Invalid handle");
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
[DllImport (Constants.SecurityLibrary, EntryPoint="SecCertificateGetTypeID")]
public extern static int GetTypeID ();
[DllImport (Constants.SecurityLibrary)]
extern static IntPtr SecCertificateCreateWithData (IntPtr allocator, IntPtr cfData);
public SecCertificate (NSData data)
{
if (data == null)
throw new ArgumentNullException ("data");
Initialize (data);
}
public SecCertificate (byte[] data)
{
if (data == null)
throw new ArgumentNullException ("data");
using (NSData cert = NSData.FromArray (data)) {
Initialize (cert);
}
}
public SecCertificate (X509Certificate certificate)
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
using (NSData cert = NSData.FromArray (certificate.GetRawCertData ())) {
Initialize (cert);
}
}
public SecCertificate (X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException ("certificate");
using (NSData cert = NSData.FromArray (certificate.RawData)) {
Initialize (cert);
}
}
void Initialize (NSData data)
{
handle = SecCertificateCreateWithData (IntPtr.Zero, data.Handle);
if (handle == IntPtr.Zero)
throw new ArgumentException ("Not a valid DER-encoded X.509 certificate");
}
[DllImport (Constants.SecurityLibrary)]
extern static IntPtr SecCertificateCopySubjectSummary (IntPtr cert);
public string SubjectSummary {
get {
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecCertificate");
IntPtr cfstr = SecCertificateCopySubjectSummary (handle);
string ret = CFString.FetchString (cfstr);
CFObject.CFRelease (cfstr);
return ret;
}
}
[DllImport (Constants.SecurityLibrary)]
extern static IntPtr SecCertificateCopyData (IntPtr cert);
public NSData DerData {
get {
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecCertificate");
IntPtr data = SecCertificateCopyData (handle);
if (data == IntPtr.Zero)
throw new ArgumentException ("Not a valid certificate");
return new NSData (data);
}
}
~SecCertificate ()
{
Dispose (false);
}
public IntPtr Handle {
get {
return handle;
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
}
public class SecIdentity : INativeObject, IDisposable {
internal IntPtr handle;
// invoked by marshallers
internal SecIdentity (IntPtr handle)
: this (handle, false)
{
}
[Preserve (Conditional = true)]
internal SecIdentity (IntPtr handle, bool owns)
{
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
[DllImport (Constants.SecurityLibrary, EntryPoint="SecIdentityGetTypeID")]
public extern static int GetTypeID ();
[DllImport (Constants.SecurityLibrary)]
extern static IntPtr SecIdentityCopyCertificate (IntPtr handle, out IntPtr cert);
public SecCertificate Certificate {
get {
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecIdentity");
IntPtr cert;
SecIdentityCopyCertificate (handle, out cert);
return new SecCertificate (handle, true);
}
}
~SecIdentity ()
{
Dispose (false);
}
public IntPtr Handle {
get {
return handle;
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
}
public class SecKey : INativeObject, IDisposable {
internal IntPtr handle;
// invoked by marshallers
internal SecKey (IntPtr handle)
: this (handle, false)
{
}
[Preserve (Conditional = true)]
internal SecKey (IntPtr handle, bool owns)
{
this.handle = handle;
if (!owns)
CFObject.CFRetain (handle);
}
[DllImport (Constants.SecurityLibrary, EntryPoint="SecKeyGetTypeID")]
public extern static int GetTypeID ();
[DllImport (Constants.SecurityLibrary)]
extern static SecStatusCode SecKeyGeneratePair (IntPtr dictHandle, out IntPtr pubKey, out IntPtr privKey);
// TODO: pull all the TypeRefs needed for the NSDictionary
public static SecStatusCode GenerateKeyPair (NSDictionary parameters, out SecKey publicKey, out SecKey privateKey)
{
if (parameters == null)
throw new ArgumentNullException ("parameters");
IntPtr pub, priv;
var res = SecKeyGeneratePair (parameters.Handle, out pub, out priv);
if (res == SecStatusCode.Success){
publicKey = new SecKey (pub, true);
privateKey = new SecKey (priv, true);
} else
publicKey = privateKey = null;
return res;
}
[DllImport (Constants.SecurityLibrary)]
extern static IntPtr SecKeyGetBlockSize (IntPtr handle);
long BlockSize {
get {
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecKey");
return (long) SecKeyGetBlockSize (handle);
}
}
[DllImport (Constants.SecurityLibrary)]
extern static SecStatusCode SecKeyRawSign (IntPtr handle, SecPadding padding, IntPtr dataToSign, IntPtr dataToSignLen, IntPtr sig, IntPtr sigLen);
SecStatusCode RawSign (SecPadding padding, IntPtr dataToSign, int dataToSignLen, out byte [] result)
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecKey");
result = new byte [(int) SecKeyGetBlockSize (handle)];
unsafe {
fixed (byte *p = &result [0])
return SecKeyRawSign (handle, padding, dataToSign, (IntPtr) dataToSignLen, (IntPtr) p, (IntPtr)result.Length);
}
}
SecStatusCode RawSign (SecPadding padding, byte [] dataToSign, out byte [] result)
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecKey");
if (dataToSign == null)
throw new ArgumentNullException ("dataToSign");
result = new byte [(int) SecKeyGetBlockSize (handle)];
unsafe {
fixed (byte *bp = &dataToSign [0]){
fixed (byte *p = &result [0])
return SecKeyRawSign (handle, padding, (IntPtr) bp, (IntPtr)dataToSign.Length, (IntPtr) p, (IntPtr) result.Length);
}
}
}
[DllImport (Constants.SecurityLibrary)]
extern static SecStatusCode SecKeyRawVerify (IntPtr handle, SecPadding padding, IntPtr signedData, IntPtr signedLen, IntPtr sign, IntPtr signLen);
public unsafe SecStatusCode RawVerify (SecPadding padding, IntPtr signedData, int signedDataLen, IntPtr signature, int signatureLen)
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecKey");
return SecKeyRawVerify (handle, padding, signedData, (IntPtr) signedDataLen, signature, (IntPtr) signatureLen);
}
public SecStatusCode RawVerify (SecPadding padding, byte [] signedData, byte [] signature)
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecKey");
if (signature == null)
throw new ArgumentNullException ("signature");
if (signedData == null)
throw new ArgumentNullException ("signedData");
unsafe {
fixed (byte *sp = &signature[0]){
fixed (byte *dp = &signedData [0]){
return SecKeyRawVerify (handle, padding, (IntPtr) dp, (IntPtr) signedData.Length, (IntPtr) sp, (IntPtr) signature.Length);
}
}
}
}
[DllImport (Constants.SecurityLibrary)]
extern static SecStatusCode SecKeyEncrypt (IntPtr handle, SecPadding padding, IntPtr plainText, IntPtr playLen, IntPtr cipherText, IntPtr cipherLen);
public unsafe SecStatusCode Encrypt (SecPadding padding, IntPtr plainText, int playLen, IntPtr cipherText, int cipherLen)
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecKey");
return SecKeyEncrypt (handle, padding, plainText, (IntPtr) playLen, cipherText, (IntPtr) cipherLen);
}
public SecStatusCode Encrypt (SecPadding padding, byte [] plainText, byte [] cipherText)
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecKey");
if (cipherText == null)
throw new ArgumentNullException ("cipherText");
if (plainText == null)
throw new ArgumentNullException ("plainText");
unsafe {
fixed (byte *cp = &cipherText[0]){
fixed (byte *pp = &plainText [0]){
return SecKeyEncrypt (handle, padding, (IntPtr) pp, (IntPtr) plainText.Length, (IntPtr) cp, (IntPtr) cipherText.Length);
}
}
}
}
[DllImport (Constants.SecurityLibrary)]
extern static SecStatusCode SecKeyDecrypt (IntPtr handle, SecPadding padding, IntPtr cipherText, IntPtr cipherLen, IntPtr plainText, IntPtr playLen);
public unsafe SecStatusCode Decrypt (SecPadding padding, IntPtr cipherText, int cipherLen, IntPtr plainText, int playLen)
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecKey");
return SecKeyDecrypt (handle, padding, cipherText, (IntPtr) cipherLen, plainText, (IntPtr) playLen);
}
public SecStatusCode Decrypt (SecPadding padding, byte [] cipherText, byte [] plainText)
{
if (handle == IntPtr.Zero)
throw new ObjectDisposedException ("SecKey");
if (cipherText == null)
throw new ArgumentNullException ("cipherText");
if (plainText == null)
throw new ArgumentNullException ("plainText");
unsafe {
fixed (byte *cp = &cipherText[0]){
fixed (byte *pp = &plainText [0]){
return SecKeyDecrypt (handle, padding, (IntPtr) cp, (IntPtr) cipherText.Length, (IntPtr) pp, (IntPtr) plainText.Length);
}
}
}
}
~SecKey ()
{
Dispose (false);
}
public IntPtr Handle {
get {
return handle;
}
}
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
public virtual void Dispose (bool disposing)
{
if (handle != IntPtr.Zero){
CFObject.CFRelease (handle);
handle = IntPtr.Zero;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using System.Xml;
using System.IO;
using System.Reflection;
using UnityEngine;
using Ecosim;
using Ecosim.SceneData;
using Ecosim.EcoScript;
namespace Ecosim.SceneData.Action
{
/**
* Actions can be a lot, it can be a measure taken in the field, like starting mowing, or it can be some research
* like placing a pijlbuis or counting species
*/
public abstract class BasicAction
{
public const string GENERATED_DIR = "GeneratedScripts";
public volatile bool finishedProcessing;
public readonly int id = -1;
public bool isActive = true;
protected readonly Scene scene;
protected EcoBase ecoBase; // the compiled ecoscript holder
private string _affectedAreaName;
public string affectedAreaName { // Use to store the affected area for internal purposes
get {
// Save the affected area (if it's not yet there)
if (_affectedAreaName == null) {
_affectedAreaName = "_area" + id.ToString();
}
return _affectedAreaName;
}
}
public Data AffectedArea {
get {
if (scene == null || scene.progression == null)
return null;
Data data = null;
if (scene.progression.HasData (affectedAreaName)) {
data = scene.progression.GetData (affectedAreaName);
} else {
data = new BitMap8 (scene);
scene.progression.AddData (affectedAreaName, data);
}
return data;
}
}
private string ecoScript = null;
private System.DateTime fileLastModified = System.DateTime.MinValue;
public CompilerErrorCollection errors = null;
public List<UserInteraction> uiList;
private MethodInfo prepareSuccessionMI;
private MethodInfo doSuccessionMI;
private MethodInfo finalizeSuccessionMI;
private MethodInfo loadProgressMI;
private MethodInfo saveProgressMI;
private MethodInfo encyclopediaOpenedMI;
private MethodInfo measureTakenMI;
private MethodInfo researchConductedMI;
private MethodInfo actionSelectedMI;
private MethodInfo getVariablePresentationDataMI;
private MethodInfo getFormulaPresentationDataMI;
private MethodInfo debugFnMI;
public bool HasDebugFn {
get { return (debugFnMI != null); }
}
protected BasicAction (Scene scene, int id)
{
this.scene = scene;
this.id = id;
uiList = new List<UserInteraction> ();
}
public virtual string GetDescription ()
{
return GetType ().Name;
}
public virtual void SetDescription (string descr)
{
throw new System.ArgumentException ("Description can not be set for " + GetType ().ToString ());
}
public virtual bool DescriptionIsWritable ()
{
return false;
}
public virtual int GetMinUICount ()
{
return 0;
}
public virtual int GetMaxUICount ()
{
return 0;
}
public string Script {
get { return ecoScript; }
set {
string newScript = value.Trim ();
if (newScript != ecoScript) {
ecoScript = newScript;
}
}
}
/// <summary>
/// Creates the default script (loaded as template from Resources.
/// The script will be compiled (any errors/warnings will be stored in errors)
/// </summary>
/// <returns>
/// true if template was found, otherwise false
/// </returns>
public virtual bool CreateDefaultScript ()
{
string resourcePath = "EcoScriptTemplates/" + GetType ().Name;
TextAsset textAsset = Resources.Load (resourcePath) as TextAsset;
if (textAsset != null) {
Debug.Log ("Loaded script for '" + GetType ().Name + "'");
Script = textAsset.text;
} else {
Debug.Log ("Couldn't load script for '" + GetType ().Name + "'");
return false;
}
return true;
}
/// <summary>
/// Deletes the script from the Scripts directory, unloads the class if compiled and set action to have no script
/// </summary>
public virtual void DeleteScript ()
{
string path = GetScriptPath ();
ecoScript = null;
if (File.Exists (path)) {
try {
File.Delete (path);
} catch (System.Exception e) {
Log.LogException (e);
}
}
}
public string GetScriptPath ()
{
return GetScriptPath (GameSettings.GetPathForScene (scene.sceneName));
}
public string GetScriptPath (string scenePath)
{
return scenePath + "Scripts" + Path.DirectorySeparatorChar + "script" + id + ".txt";
}
public bool HasScript ()
{
return ecoScript != null;
}
/**
* Link the generated EcoScript class instance to this action
*/
public void SetEcoScriptInstance(EcoBase instance) {
if (ecoBase != null) {
UnlinkEcoBase ();
}
ecoBase = instance;
LinkEcoBase ();
}
/**
* Generates C# code from EcoScript (actual compiling is not done yet)
*/
public virtual bool CompileScript ()
{
return CompileScript (null);
}
protected virtual void UnlinkEcoBase ()
{
ecoBase = null;
prepareSuccessionMI = null;
doSuccessionMI = null;
finalizeSuccessionMI = null;
loadProgressMI = null;
saveProgressMI = null;
encyclopediaOpenedMI = null;
measureTakenMI = null;
researchConductedMI = null;
actionSelectedMI = null;
getVariablePresentationDataMI = null;
getFormulaPresentationDataMI = null;
debugFnMI = null;
}
protected virtual void LinkEcoBase ()
{
if (ecoBase != null) {
prepareSuccessionMI = ecoBase.GetType ().GetMethod ("PrepareSuccession",
BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] {}, null);
doSuccessionMI = ecoBase.GetType ().GetMethod ("DoSuccession",
BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] {}, null);
finalizeSuccessionMI = ecoBase.GetType ().GetMethod ("FinalizeSuccession",
BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] {}, null);
loadProgressMI = ecoBase.GetType ().GetMethod ("LoadProgress",
BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] {typeof(bool)}, null);
saveProgressMI = ecoBase.GetType ().GetMethod ("SaveProgress",
BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] {}, null);
encyclopediaOpenedMI = ecoBase.GetType ().GetMethod ("EncyclopediaOpened",
BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(int), typeof(string) }, null);
measureTakenMI = ecoBase.GetType ().GetMethod ("MeasureTaken",
BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(string), typeof(string), typeof(int) }, null);
researchConductedMI = ecoBase.GetType ().GetMethod ("ResearchConducted",
BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(string), typeof(string), typeof(int) }, null);
actionSelectedMI = ecoBase.GetType ().GetMethod ("ActionSelected",
BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(UserInteraction) }, null);
getVariablePresentationDataMI = ecoBase.GetType ().GetMethod ("GetVariablePresentationData",
BindingFlags.NonPublic | BindingFlags.Instance, null, new Type [] {}, null);
getFormulaPresentationDataMI = ecoBase.GetType ().GetMethod ("GetFormulaPresentationData",
BindingFlags.NonPublic | BindingFlags.Instance, null, new Type [] {}, null);
debugFnMI = ecoBase.GetType ().GetMethod ("Debug",
BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(string) }, null);
}
}
/**
* Loads in script if script is not already loaded in or script on disk has changed
* returns true if a script is attached to this action.
*/
public bool LoadScript () {
string path = GetScriptPath ();
if (File.Exists (path)) {
DateTime modified = File.GetLastWriteTime (path);
if ((ecoScript == null) || (DateTime.Compare (fileLastModified, modified) < 0)) {
// script not yet loaded or older than currently on disk
ecoScript = File.ReadAllText (path).Trim ();
fileLastModified = modified;
if (ecoScript == "") {
ecoScript = null;
}
}
}
return (ecoScript != null);
}
/**
* Saves script if a script is attached to this action
*/
public void SaveScriptIfNeeded (string newPath)
{
if (ecoScript != null) {
ecoScript = ecoScript.Trim ();
if (ecoScript != "") {
File.WriteAllText (GetScriptPath (newPath), ecoScript);
fileLastModified = File.GetLastWriteTime (GetScriptPath ());
} else {
ecoScript = null;
}
}
}
public string ClassName () {
return "EcoScript" + id;
}
public string GetFullClassPath () {
string dir = GameSettings.GetPathForScene (scene.sceneName) + GENERATED_DIR;
return dir + Path.DirectorySeparatorChar + ClassName() + ".cs";
}
/**
* Generates the actual C# code from the EcoScript
*/
protected bool CompileScript (Dictionary<string, string> constants)
{
LoadScript ();
if (ecoScript == null) return false;
try {
string script = Compiler.GenerateCode (scene, this, ecoScript, constants);
string dir = GameSettings.GetPathForScene (scene.sceneName) + GENERATED_DIR;
if (!Directory.Exists(dir)) {
Directory.CreateDirectory (dir);
}
string path = dir + Path.DirectorySeparatorChar + ClassName() + ".cs";
File.WriteAllText (path, script);
// ecoBase = Compiler.EcoCompile (scene, this, script, out errors);
return true;
}
catch (Exception e) {
Log.LogException (e);
}
return false;
}
/**
* Called at start of succession, before any DoSuccessions are called, given the action
* a chance to prepare data for handling during DoSuccession
*/
public virtual void PrepareSuccession ()
{
if (prepareSuccessionMI != null) {
try {
prepareSuccessionMI.Invoke (ecoBase, null);
} catch (Exception e) {
Log.LogException (e);
}
}
}
/**
* Called when succession is done for this action
*/
public virtual void DoSuccession ()
{
if (doSuccessionMI != null) {
try {
doSuccessionMI.Invoke (ecoBase, null);
} catch (Exception e) {
Log.LogException (e);
}
}
}
/**
* Called to finalize succession, called after all DoSuccessions have been called to
* all action. Here cleanup of temporary data can be done.
*/
public virtual void FinalizeSuccession ()
{
if (finalizeSuccessionMI != null) {
try {
finalizeSuccessionMI.Invoke (ecoBase, null);
} catch (Exception e) {
Log.LogException (e);
}
}
}
/**
* When user selects an action from game interface this method is called to present
* the user with the necessary interface (dialog or anything).
* ui is the user interaction element that the user selected.
*/
public virtual void ActionSelected (UserInteraction ui)
{
if (actionSelectedMI != null) {
try {
actionSelectedMI.Invoke (ecoBase, new object[] { ui });
} catch (Exception e) {
Log.LogException (e);
}
}
}
/**
* Debug function, has string argument
*/
public virtual bool DebugFn (string str)
{
if (debugFnMI != null) {
try {
debugFnMI.Invoke (ecoBase, new object[] { str });
return true;
} catch (Exception e) {
Log.LogException (e);
}
}
return false;
}
/**
* Called when game is started or continue (progress is loaded)
* initScene will be true when game is new game intead of a save game
* properties will contain a property dictionary, can _not_ be null if no properties are
* defined.
*/
public virtual void LoadProgress (bool initScene, Dictionary <string, string> properties)
{
if (ecoBase != null) {
ecoBase.properties = properties;
if (loadProgressMI != null) {
try {
loadProgressMI.Invoke (ecoBase, new object[] { initScene });
} catch (Exception e) {
Log.LogException (e);
}
}
}
}
/**
* Gets a dictionary of properties to persistence the action. The dictionary can be empty.
* The dictionary will be used again when loading the save game or starting new game to
* restore the data in the action.
*/
public virtual Dictionary<string, string> SaveProgress ()
{
if (saveProgressMI != null) {
try {
saveProgressMI.Invoke (ecoBase, null);
} catch (Exception e) {
Log.LogException (e);
}
}
if ((ecoBase != null) && (ecoBase.properties.Count > 0)) {
return ecoBase.properties;
} else {
return null;
}
}
/**
* Called when a measure is taken.
*/
public virtual void MeasureTaken (string name, string group, int count)
{
if (measureTakenMI != null) {
try {
measureTakenMI.Invoke (ecoBase, new object[] {name, group, count});
} catch (Exception e) {
Log.LogException (e);
}
}
}
/**
* Called when research is conducted.
*/
public virtual void ResearchConducted (string name, string group, int count)
{
if (researchConductedMI != null) {
try {
researchConductedMI.Invoke (ecoBase, new object[] {name, group, count});
} catch (Exception e) {
Log.LogException (e);
}
}
}
/**
* Called when a encylcopedia item is consulted.
*/
public virtual void EncyclopediaOpened (int itemNr, string itemTitle)
{
if (encyclopediaOpenedMI != null) {
try {
encyclopediaOpenedMI.Invoke (ecoBase, new object[] {itemNr, itemTitle});
} catch (Exception e) {
Log.LogException (e);
}
}
}
/*public virtual List<VariablePresentData> GetVariablePresentationsData ()
{
if (getVariablePresentationDataMI != null) {
try {
object result = getVariablePresentationDataMI.Invoke (ecoBase, null);
return result as List<VariablePresentData>;
} catch (Exception e) {
Log.LogException (e);
}
}
List<VariablePresentData> list = new List<VariablePresentData> ();
return list;
}
public virtual List<FormulaPresentData> GetFormulaPresentationData ()
{
if (getFormulaPresentationDataMI != null) {
try {
object result = getFormulaPresentationDataMI.Invoke (ecoBase, null);
return result as List<FormulaPresentData>;
} catch (Exception e) {
Log.LogException (e);
}
}
List<FormulaPresentData> list = new List<FormulaPresentData> ();
return list;
}*/
public abstract void Save (XmlTextWriter writer);
public virtual void UpdateReferences ()
{
}
}
}
| |
using J2N.Runtime.CompilerServices;
using Lucene.Net.Diagnostics;
using Lucene.Net.Util;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Codec = Lucene.Net.Codecs.Codec;
using CompoundFileDirectory = Lucene.Net.Store.CompoundFileDirectory;
using Directory = Lucene.Net.Store.Directory;
using DocValuesFormat = Lucene.Net.Codecs.DocValuesFormat;
using DocValuesProducer = Lucene.Net.Codecs.DocValuesProducer;
using IBits = Lucene.Net.Util.IBits;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using StoredFieldsReader = Lucene.Net.Codecs.StoredFieldsReader;
using TermVectorsReader = Lucene.Net.Codecs.TermVectorsReader;
/// <summary>
/// <see cref="IndexReader"/> implementation over a single segment.
/// <para/>
/// Instances pointing to the same segment (but with different deletes, etc)
/// may share the same core data.
/// <para/>
/// @lucene.experimental
/// </summary>
public sealed class SegmentReader : AtomicReader
{
private readonly SegmentCommitInfo si;
private readonly IBits liveDocs;
// Normally set to si.docCount - si.delDocCount, unless we
// were created as an NRT reader from IW, in which case IW
// tells us the docCount:
private readonly int numDocs;
internal readonly SegmentCoreReaders core;
internal readonly SegmentDocValues segDocValues;
internal readonly DisposableThreadLocal<IDictionary<string, object>> docValuesLocal =
new DisposableThreadLocal<IDictionary<string, object>>(() => new Dictionary<string, object>());
internal readonly DisposableThreadLocal<IDictionary<string, IBits>> docsWithFieldLocal =
new DisposableThreadLocal<IDictionary<string, IBits>>(() => new Dictionary<string, IBits>());
internal readonly IDictionary<string, DocValuesProducer> dvProducersByField = new Dictionary<string, DocValuesProducer>();
internal readonly ISet<DocValuesProducer> dvProducers = new JCG.HashSet<DocValuesProducer>(IdentityEqualityComparer<DocValuesProducer>.Default);
private readonly FieldInfos fieldInfos; // LUCENENET specific - since it is readonly, made all internal classes use property
private readonly IList<long?> dvGens = new List<long?>();
/// <summary>
/// Constructs a new <see cref="SegmentReader"/> with a new core. </summary>
/// <exception cref="CorruptIndexException"> if the index is corrupt </exception>
/// <exception cref="IOException"> if there is a low-level IO error </exception>
// TODO: why is this public?
public SegmentReader(SegmentCommitInfo si, int termInfosIndexDivisor, IOContext context)
{
this.si = si;
// TODO if the segment uses CFS, we may open the CFS file twice: once for
// reading the FieldInfos (if they are not gen'd) and second time by
// SegmentCoreReaders. We can open the CFS here and pass to SCR, but then it
// results in less readable code (resource not closed where it was opened).
// Best if we could somehow read FieldInfos in SCR but not keep it there, but
// constructors don't allow returning two things...
fieldInfos = ReadFieldInfos(si);
core = new SegmentCoreReaders(this, si.Info.Dir, si, context, termInfosIndexDivisor);
segDocValues = new SegmentDocValues();
bool success = false;
Codec codec = si.Info.Codec;
try
{
if (si.HasDeletions)
{
// NOTE: the bitvector is stored using the regular directory, not cfs
liveDocs = codec.LiveDocsFormat.ReadLiveDocs(Directory, si, IOContext.READ_ONCE);
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(si.DelCount == 0);
liveDocs = null;
}
numDocs = si.Info.DocCount - si.DelCount;
if (FieldInfos.HasDocValues)
{
InitDocValuesProducers(codec);
}
success = true;
}
finally
{
// With lock-less commits, it's entirely possible (and
// fine) to hit a FileNotFound exception above. In
// this case, we want to explicitly close any subset
// of things that were opened so that we don't have to
// wait for a GC to do so.
if (!success)
{
DoClose();
}
}
}
/// <summary>
/// Create new <see cref="SegmentReader"/> sharing core from a previous
/// <see cref="SegmentReader"/> and loading new live docs from a new
/// deletes file. Used by <see cref="DirectoryReader.OpenIfChanged(DirectoryReader)"/>.
/// </summary>
internal SegmentReader(SegmentCommitInfo si, SegmentReader sr)
: this(si, sr, si.Info.Codec.LiveDocsFormat.ReadLiveDocs(si.Info.Dir, si, IOContext.READ_ONCE), si.Info.DocCount - si.DelCount)
{
}
/// <summary>
/// Create new <see cref="SegmentReader"/> sharing core from a previous
/// <see cref="SegmentReader"/> and using the provided in-memory
/// liveDocs. Used by <see cref="IndexWriter"/> to provide a new NRT
/// reader
/// </summary>
internal SegmentReader(SegmentCommitInfo si, SegmentReader sr, IBits liveDocs, int numDocs)
{
this.si = si;
this.liveDocs = liveDocs;
this.numDocs = numDocs;
this.core = sr.core;
core.IncRef();
this.segDocValues = sr.segDocValues;
// System.out.println("[" + Thread.currentThread().getName() + "] SR.init: sharing reader: " + sr + " for gens=" + sr.genDVProducers.keySet());
// increment refCount of DocValuesProducers that are used by this reader
bool success = false;
try
{
Codec codec = si.Info.Codec;
if (si.FieldInfosGen == -1)
{
fieldInfos = sr.FieldInfos;
}
else
{
fieldInfos = ReadFieldInfos(si);
}
if (FieldInfos.HasDocValues)
{
InitDocValuesProducers(codec);
}
success = true;
}
finally
{
if (!success)
{
DoClose();
}
}
}
// initialize the per-field DocValuesProducer
private void InitDocValuesProducers(Codec codec)
{
Directory dir = core.cfsReader != null ? core.cfsReader : si.Info.Dir;
DocValuesFormat dvFormat = codec.DocValuesFormat;
IDictionary<long?, IList<FieldInfo>> genInfos = GetGenInfos();
// System.out.println("[" + Thread.currentThread().getName() + "] SR.initDocValuesProducers: segInfo=" + si + "; gens=" + genInfos.keySet());
// TODO: can we avoid iterating over fieldinfos several times and creating maps of all this stuff if dv updates do not exist?
foreach (KeyValuePair<long?, IList<FieldInfo>> e in genInfos)
{
long? gen = e.Key;
IList<FieldInfo> infos = e.Value;
DocValuesProducer dvp = segDocValues.GetDocValuesProducer(gen, si, IOContext.READ, dir, dvFormat, infos, TermInfosIndexDivisor);
foreach (FieldInfo fi in infos)
{
dvProducersByField[fi.Name] = dvp;
dvProducers.Add(dvp);
}
}
dvGens.AddRange(genInfos.Keys);
}
/// <summary>
/// Reads the most recent <see cref="Index.FieldInfos"/> of the given segment info.
/// <para/>
/// @lucene.internal
/// </summary>
internal static FieldInfos ReadFieldInfos(SegmentCommitInfo info)
{
Directory dir;
bool closeDir;
if (info.FieldInfosGen == -1 && info.Info.UseCompoundFile)
{
// no fieldInfos gen and segment uses a compound file
dir = new CompoundFileDirectory(info.Info.Dir, IndexFileNames.SegmentFileName(info.Info.Name, "", IndexFileNames.COMPOUND_FILE_EXTENSION), IOContext.READ_ONCE, false);
closeDir = true;
}
else
{
// gen'd FIS are read outside CFS, or the segment doesn't use a compound file
dir = info.Info.Dir;
closeDir = false;
}
try
{
string segmentSuffix = info.FieldInfosGen == -1 ? "" : info.FieldInfosGen.ToString(CultureInfo.InvariantCulture);//Convert.ToString(info.FieldInfosGen, Character.MAX_RADIX));
return info.Info.Codec.FieldInfosFormat.FieldInfosReader.Read(dir, info.Info.Name, segmentSuffix, IOContext.READ_ONCE);
}
finally
{
if (closeDir)
{
dir.Dispose();
}
}
}
// returns a gen->List<FieldInfo> mapping. Fields without DV updates have gen=-1
private IDictionary<long?, IList<FieldInfo>> GetGenInfos()
{
IDictionary<long?, IList<FieldInfo>> genInfos = new Dictionary<long?, IList<FieldInfo>>();
foreach (FieldInfo fi in FieldInfos)
{
if (fi.DocValuesType == DocValuesType.NONE)
{
continue;
}
long gen = fi.DocValuesGen;
IList<FieldInfo> infos;
genInfos.TryGetValue(gen, out infos);
if (infos == null)
{
infos = new List<FieldInfo>();
genInfos[gen] = infos;
}
infos.Add(fi);
}
return genInfos;
}
public override IBits LiveDocs
{
get
{
EnsureOpen();
return liveDocs;
}
}
protected internal override void DoClose()
{
//System.out.println("SR.close seg=" + si);
try
{
core.DecRef();
}
finally
{
dvProducersByField.Clear();
try
{
IOUtils.Dispose(docValuesLocal, docsWithFieldLocal);
}
finally
{
segDocValues.DecRef(dvGens);
}
}
}
public override FieldInfos FieldInfos
{
get
{
EnsureOpen();
return fieldInfos;
}
}
/// <summary>
/// Expert: retrieve thread-private
/// <see cref="StoredFieldsReader"/>
/// <para/>
/// @lucene.internal
/// </summary>
public StoredFieldsReader FieldsReader
{
get
{
EnsureOpen();
return core.fieldsReaderLocal.Value;
}
}
public override void Document(int docID, StoredFieldVisitor visitor)
{
CheckBounds(docID);
FieldsReader.VisitDocument(docID, visitor);
}
public override Fields Fields
{
get
{
EnsureOpen();
return core.fields;
}
}
public override int NumDocs =>
// Don't call ensureOpen() here (it could affect performance)
numDocs;
public override int MaxDoc =>
// Don't call ensureOpen() here (it could affect performance)
si.Info.DocCount;
/// <summary>
/// Expert: retrieve thread-private
/// <see cref="Codecs.TermVectorsReader"/>
/// <para/>
/// @lucene.internal
/// </summary>
public TermVectorsReader TermVectorsReader
{
get
{
EnsureOpen();
return core.termVectorsLocal.Value;
}
}
public override Fields GetTermVectors(int docID)
{
TermVectorsReader termVectorsReader = TermVectorsReader;
if (termVectorsReader == null)
{
return null;
}
CheckBounds(docID);
return termVectorsReader.Get(docID);
}
private void CheckBounds(int docID)
{
if (docID < 0 || docID >= MaxDoc)
{
throw new IndexOutOfRangeException("docID must be >= 0 and < maxDoc=" + MaxDoc + " (got docID=" + docID + ")");
}
}
public override string ToString()
{
// SegmentInfo.toString takes dir and number of
// *pending* deletions; so we reverse compute that here:
return si.ToString(si.Info.Dir, si.Info.DocCount - numDocs - si.DelCount);
}
/// <summary>
/// Return the name of the segment this reader is reading.
/// </summary>
public string SegmentName => si.Info.Name;
/// <summary>
/// Return the <see cref="SegmentCommitInfo"/> of the segment this reader is reading.
/// </summary>
public SegmentCommitInfo SegmentInfo => si;
/// <summary>
/// Returns the directory this index resides in. </summary>
public Directory Directory =>
// Don't ensureOpen here -- in certain cases, when a
// cloned/reopened reader needs to commit, it may call
// this method on the closed original reader
si.Info.Dir;
// this is necessary so that cloned SegmentReaders (which
// share the underlying postings data) will map to the
// same entry in the FieldCache. See LUCENE-1579.
public override object CoreCacheKey =>
// NOTE: if this ever changes, be sure to fix
// SegmentCoreReader.notifyCoreClosedListeners to match!
// Today it passes "this" as its coreCacheKey:
core;
public override object CombinedCoreAndDeletesKey => this;
/// <summary>
/// Returns term infos index divisor originally passed to
/// <see cref="SegmentReader(SegmentCommitInfo, int, IOContext)"/>.
/// </summary>
public int TermInfosIndexDivisor => core.termsIndexDivisor;
// returns the FieldInfo that corresponds to the given field and type, or
// null if the field does not exist, or not indexed as the requested
// DovDocValuesType.
private FieldInfo GetDVField(string field, DocValuesType type)
{
FieldInfo fi = FieldInfos.FieldInfo(field);
if (fi == null)
{
// Field does not exist
return null;
}
if (fi.DocValuesType == DocValuesType.NONE)
{
// Field was not indexed with doc values
return null;
}
if (fi.DocValuesType != type)
{
// Field DocValues are different than requested type
return null;
}
return fi;
}
public override NumericDocValues GetNumericDocValues(string field)
{
EnsureOpen();
FieldInfo fi = GetDVField(field, DocValuesType.NUMERIC);
if (fi == null)
{
return null;
}
IDictionary<string, object> dvFields = docValuesLocal.Value;
NumericDocValues dvs;
object dvsDummy;
dvFields.TryGetValue(field, out dvsDummy);
dvs = (NumericDocValues)dvsDummy;
if (dvs == null)
{
DocValuesProducer dvProducer;
dvProducersByField.TryGetValue(field, out dvProducer);
if (Debugging.AssertsEnabled) Debugging.Assert(dvProducer != null);
dvs = dvProducer.GetNumeric(fi);
dvFields[field] = dvs;
}
return dvs;
}
public override IBits GetDocsWithField(string field)
{
EnsureOpen();
FieldInfo fi = FieldInfos.FieldInfo(field);
if (fi == null)
{
// Field does not exist
return null;
}
if (fi.DocValuesType == DocValuesType.NONE)
{
// Field was not indexed with doc values
return null;
}
IDictionary<string, IBits> dvFields = docsWithFieldLocal.Value;
dvFields.TryGetValue(field, out IBits dvs);
if (dvs == null)
{
DocValuesProducer dvProducer;
dvProducersByField.TryGetValue(field, out dvProducer);
if (Debugging.AssertsEnabled) Debugging.Assert(dvProducer != null);
dvs = dvProducer.GetDocsWithField(fi);
dvFields[field] = dvs;
}
return dvs;
}
public override BinaryDocValues GetBinaryDocValues(string field)
{
EnsureOpen();
FieldInfo fi = GetDVField(field, DocValuesType.BINARY);
if (fi == null)
{
return null;
}
IDictionary<string, object> dvFields = docValuesLocal.Value;
object ret;
BinaryDocValues dvs;
dvFields.TryGetValue(field, out ret);
dvs = (BinaryDocValues)ret;
if (dvs == null)
{
dvProducersByField.TryGetValue(field, out DocValuesProducer dvProducer);
if (Debugging.AssertsEnabled) Debugging.Assert(dvProducer != null);
dvs = dvProducer.GetBinary(fi);
dvFields[field] = dvs;
}
return dvs;
}
public override SortedDocValues GetSortedDocValues(string field)
{
EnsureOpen();
FieldInfo fi = GetDVField(field, DocValuesType.SORTED);
if (fi == null)
{
return null;
}
IDictionary<string, object> dvFields = docValuesLocal.Value;
SortedDocValues dvs;
object ret;
dvFields.TryGetValue(field, out ret);
dvs = (SortedDocValues)ret;
if (dvs == null)
{
dvProducersByField.TryGetValue(field, out DocValuesProducer dvProducer);
if (Debugging.AssertsEnabled) Debugging.Assert(dvProducer != null);
dvs = dvProducer.GetSorted(fi);
dvFields[field] = dvs;
}
return dvs;
}
public override SortedSetDocValues GetSortedSetDocValues(string field)
{
EnsureOpen();
FieldInfo fi = GetDVField(field, DocValuesType.SORTED_SET);
if (fi == null)
{
return null;
}
IDictionary<string, object> dvFields = docValuesLocal.Value;
object ret;
SortedSetDocValues dvs;
dvFields.TryGetValue(field, out ret);
dvs = (SortedSetDocValues)ret;
if (dvs == null)
{
dvProducersByField.TryGetValue(field, out DocValuesProducer dvProducer);
if (Debugging.AssertsEnabled) Debugging.Assert(dvProducer != null);
dvs = dvProducer.GetSortedSet(fi);
dvFields[field] = dvs;
}
return dvs;
}
public override NumericDocValues GetNormValues(string field)
{
EnsureOpen();
FieldInfo fi = FieldInfos.FieldInfo(field);
if (fi == null || !fi.HasNorms)
{
// Field does not exist or does not index norms
return null;
}
return core.GetNormValues(fi);
}
/// <summary>
/// Called when the shared core for this <see cref="SegmentReader"/>
/// is disposed.
/// <para/>
/// This listener is called only once all <see cref="SegmentReader"/>s
/// sharing the same core are disposed. At this point it
/// is safe for apps to evict this reader from any caches
/// keyed on <see cref="CoreCacheKey"/>. This is the same
/// interface that <see cref="Search.IFieldCache"/> uses, internally,
/// to evict entries.
/// <para/>
/// NOTE: This was CoreClosedListener in Lucene.
/// <para/>
/// @lucene.experimental
/// </summary>
public interface ICoreDisposedListener
{
/// <summary>
/// Invoked when the shared core of the original
/// <see cref="SegmentReader"/> has disposed.
/// </summary>
void OnDispose(object ownerCoreCacheKey);
}
/// <summary>
/// Expert: adds a <see cref="ICoreDisposedListener"/> to this reader's shared core </summary>
public void AddCoreDisposedListener(ICoreDisposedListener listener)
{
EnsureOpen();
core.AddCoreDisposedListener(listener);
}
/// <summary>
/// Expert: removes a <see cref="ICoreDisposedListener"/> from this reader's shared core </summary>
public void RemoveCoreDisposedListener(ICoreDisposedListener listener)
{
EnsureOpen();
core.RemoveCoreDisposedListener(listener);
}
/// <summary>
/// Returns approximate RAM Bytes used </summary>
public long RamBytesUsed()
{
EnsureOpen();
long ramBytesUsed = 0;
if (dvProducers != null)
{
foreach (DocValuesProducer producer in dvProducers)
{
ramBytesUsed += producer.RamBytesUsed();
}
}
if (core != null)
{
ramBytesUsed += core.RamBytesUsed();
}
return ramBytesUsed;
}
public override void CheckIntegrity()
{
EnsureOpen();
// stored fields
FieldsReader.CheckIntegrity();
// term vectors
TermVectorsReader termVectorsReader = TermVectorsReader;
if (termVectorsReader != null)
{
termVectorsReader.CheckIntegrity();
}
// terms/postings
if (core.fields != null)
{
core.fields.CheckIntegrity();
}
// norms
if (core.normsProducer != null)
{
core.normsProducer.CheckIntegrity();
}
// docvalues
if (dvProducers != null)
{
foreach (DocValuesProducer producer in dvProducers)
{
producer.CheckIntegrity();
}
}
}
}
}
| |
/*
* Copyright 2007 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace ZXing.Client.Result
{
/// <summary> <p>Abstract class representing the result of decoding a barcode, as more than
/// a String -- as some type of structured data. This might be a subclass which represents
/// a URL, or an e-mail address. {@link #parseResult(com.google.zxing.Result)} will turn a raw
/// decoded string into the most appropriate type of structured representation.</p>
///
/// <p>Thanks to Jeff Griffin for proposing rewrite of these classes that relies less
/// on exception-based mechanisms during parsing.</p>
///
/// </summary>
/// <author> Sean Owen
/// </author>
/// <author>www.Redivivus.in ([email protected]) - Ported from ZXING Java Source
/// </author>
public abstract class ResultParser
{
private static ResultParser[] PARSERS = {
new BookmarkDoCoMoResultParser(),
new AddressBookDoCoMoResultParser(),
new EmailDoCoMoResultParser(),
new AddressBookAUResultParser(),
new VCardResultParser(),
new BizcardResultParser(),
new VEventResultParser(),
new EmailAddressResultParser(),
new SMTPResultParser(),
new TelResultParser(),
new SMSMMSResultParser(),
new SMSTOMMSTOResultParser(),
new GeoResultParser(),
new WifiResultParser(),
new URLTOResultParser(),
new URIResultParser(),
new ISBNResultParser(),
new ProductResultParser(),
new ExpandedProductResultParser()
};
#if SILVERLIGHT4 || SILVERLIGHT5 || NETFX_CORE
private static readonly Regex DIGITS = new Regex("\\d*");
private static readonly Regex ALPHANUM = new Regex("[a-zA-Z0-9]*");
private static readonly Regex AMPERSAND = new Regex("&");
private static readonly Regex EQUALS = new Regex("=");
#else
private static readonly Regex DIGITS = new Regex("\\d*", RegexOptions.Compiled);
private static readonly Regex ALPHANUM = new Regex("[a-zA-Z0-9]*", RegexOptions.Compiled);
private static readonly Regex AMPERSAND = new Regex("&", RegexOptions.Compiled);
private static readonly Regex EQUALS = new Regex("=", RegexOptions.Compiled);
#endif
/// <summary>
/// Attempts to parse the raw {@link Result}'s contents as a particular type
/// of information (email, URL, etc.) and return a {@link ParsedResult} encapsulating
/// the result of parsing.
/// </summary>
/// <param name="theResult">The result.</param>
/// <returns></returns>
public abstract ParsedResult parse(ZXing.Result theResult);
public static ParsedResult parseResult(ZXing.Result theResult)
{
foreach (var parser in PARSERS)
{
var result = parser.parse(theResult);
if (result != null)
{
return result;
}
}
return new TextParsedResult(theResult.Text, null);
}
protected static void maybeAppend(String value_Renamed, System.Text.StringBuilder result)
{
if (value_Renamed != null)
{
result.Append('\n');
result.Append(value_Renamed);
}
}
protected static void maybeAppend(String[] value_Renamed, System.Text.StringBuilder result)
{
if (value_Renamed != null)
{
for (int i = 0; i < value_Renamed.Length; i++)
{
result.Append('\n');
result.Append(value_Renamed[i]);
}
}
}
protected static String[] maybeWrap(System.String value_Renamed)
{
return value_Renamed == null ? null : new System.String[] { value_Renamed };
}
protected static String unescapeBackslash(System.String escaped)
{
if (escaped != null)
{
int backslash = escaped.IndexOf('\\');
if (backslash >= 0)
{
int max = escaped.Length;
System.Text.StringBuilder unescaped = new System.Text.StringBuilder(max - 1);
unescaped.Append(escaped.ToCharArray(), 0, backslash);
bool nextIsEscaped = false;
for (int i = backslash; i < max; i++)
{
char c = escaped[i];
if (nextIsEscaped || c != '\\')
{
unescaped.Append(c);
nextIsEscaped = false;
}
else
{
nextIsEscaped = true;
}
}
return unescaped.ToString();
}
}
return escaped;
}
protected static int parseHexDigit(char c)
{
if (c >= 'a')
{
if (c <= 'f')
{
return 10 + (c - 'a');
}
}
else if (c >= 'A')
{
if (c <= 'F')
{
return 10 + (c - 'A');
}
}
else if (c >= '0')
{
if (c <= '9')
{
return c - '0';
}
}
return -1;
}
protected static bool isStringOfDigits(String value, int length)
{
return value != null && length == value.Length && DIGITS.Match(value).Success;
}
protected static bool isSubstringOfDigits(String value, int offset, int length)
{
if (value == null)
{
return false;
}
int max = offset + length;
return value.Length >= max && DIGITS.Match(value.Substring(offset, length)).Success;
}
protected static bool isSubstringOfAlphaNumeric(String value, int offset, int length)
{
if (value == null)
{
return false;
}
int max = offset + length;
return value.Length >= max && ALPHANUM.Match(value.Substring(offset, length)).Success;
}
internal static IDictionary<string, string> parseNameValuePairs(String uri)
{
int paramStart = uri.IndexOf('?');
if (paramStart < 0)
{
return null;
}
var result = new Dictionary<String, String>(3);
foreach (var keyValue in AMPERSAND.Split(uri.Substring(paramStart + 1)))
{
appendKeyValue(keyValue, result);
}
return result;
}
private static void appendKeyValue(String keyValue,
IDictionary<String, String> result)
{
String[] keyValueTokens = EQUALS.Split(keyValue, 2);
if (keyValueTokens.Length == 2)
{
String key = keyValueTokens[0];
String value = keyValueTokens[1];
try
{
//value = URLDecoder.decode(value, "UTF-8");
value = urlDecode(value);
result[key] = value;
}
catch (Exception uee)
{
throw new InvalidOperationException("url decoding failed", uee); // can't happen
}
result[key] = value;
}
}
internal static String[] matchPrefixedField(String prefix, String rawText, char endChar, bool trim)
{
IList<string> matches = null;
int i = 0;
int max = rawText.Length;
while (i < max)
{
//UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'"
i = rawText.IndexOf(prefix, i);
if (i < 0)
{
break;
}
i += prefix.Length; // Skip past this prefix we found to start
int start = i; // Found the start of a match here
bool done = false;
while (!done)
{
//UPGRADE_WARNING: Method 'java.lang.String.indexOf' was converted to 'System.String.IndexOf' which may throw an exception. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1101'"
i = rawText.IndexOf(endChar, i);
if (i < 0)
{
// No terminating end character? uh, done. Set i such that loop terminates and break
i = rawText.Length;
done = true;
}
else if (rawText[i - 1] == '\\')
{
// semicolon was escaped so continue
i++;
}
else
{
// found a match
if (matches == null)
{
matches = new List<string>();
}
String element = unescapeBackslash(rawText.Substring(start, (i) - (start)));
if (trim)
{
element = element.Trim();
}
matches.Add(element);
i++;
done = true;
}
}
}
if (matches == null || (matches.Count == 0))
{
return null;
}
return SupportClass.toStringArray(matches);
}
internal static String matchSinglePrefixedField(System.String prefix, System.String rawText, char endChar, bool trim)
{
String[] matches = matchPrefixedField(prefix, rawText, endChar, trim);
return matches == null ? null : matches[0];
}
private static String urlDecode(String escaped)
{
// No we can't use java.net.URLDecoder here. JavaME doesn't have it.
if (escaped == null)
{
return null;
}
char[] escapedArray = escaped.ToCharArray();
int first = findFirstEscape(escapedArray);
if (first < 0)
{
return escaped;
}
int max = escapedArray.Length;
// final length is at most 2 less than original due to at least 1 unescaping
var unescaped = new System.Text.StringBuilder(max - 2);
// Can append everything up to first escape character
unescaped.Append(escapedArray, 0, first);
for (int i = first; i < max; i++)
{
char c = escapedArray[i];
if (c == '+')
{
// + is translated directly into a space
unescaped.Append(' ');
}
else if (c == '%')
{
// Are there even two more chars? if not we will just copy the escaped sequence and be done
if (i >= max - 2)
{
unescaped.Append('%'); // append that % and move on
}
else
{
int firstDigitValue = parseHexDigit(escapedArray[++i]);
int secondDigitValue = parseHexDigit(escapedArray[++i]);
if (firstDigitValue < 0 || secondDigitValue < 0)
{
// bad digit, just move on
unescaped.Append('%');
unescaped.Append(escapedArray[i - 1]);
unescaped.Append(escapedArray[i]);
}
unescaped.Append((char)((firstDigitValue << 4) + secondDigitValue));
}
}
else
{
unescaped.Append(c);
}
}
return unescaped.ToString();
}
private static int findFirstEscape(char[] escapedArray)
{
int max = escapedArray.Length;
for (int i = 0; i < max; i++)
{
char c = escapedArray[i];
if (c == '+' || c == '%')
{
return i;
}
}
return -1;
}
}
}
| |
// 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.
using Xunit;
namespace System.Runtime.CompilerServices.Tests
{
public static partial class AttributesTests
{
[Fact]
public static void AccessedThroughPropertyAttributeTests()
{
var attr1 = new AccessedThroughPropertyAttribute(null);
Assert.Null(attr1.PropertyName);
var attr2 = new AccessedThroughPropertyAttribute("MyProperty");
Assert.Equal("MyProperty", attr2.PropertyName);
}
[Fact]
public static void CallerFilePathAttributeTests()
{
new CallerFilePathAttribute();
}
[Fact]
public static void CallerLineNumberAttributeTests()
{
new CallerLineNumberAttribute();
}
[Fact]
public static void CallerMemberNameAttributeTests()
{
new CallerMemberNameAttribute();
}
[Fact]
public static void CompilationRelaxationsAttributeTests()
{
var attr1 = new CompilationRelaxationsAttribute(42);
Assert.Equal(42, attr1.CompilationRelaxations);
var attr2 = new CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning);
Assert.Equal((int)CompilationRelaxations.NoStringInterning, attr2.CompilationRelaxations);
}
[Fact]
public static void CompilerGeneratedAttributeTests()
{
new CompilerGeneratedAttribute();
}
[Fact]
public static void CompilerGlobalScopeAttributeTests()
{
new CompilerGlobalScopeAttribute();
}
[Fact]
public static void DateTimeConstantAttributeTests()
{
long ticks = DateTime.Now.Ticks;
var attr = new DateTimeConstantAttribute(ticks);
Assert.Equal(new DateTime(ticks), attr.Value);
Assert.Throws<ArgumentOutOfRangeException>(() => new DateTimeConstantAttribute(-1));
}
[Fact]
public static void DecimalConstantAttributeTests()
{
var attrSigned = new DecimalConstantAttribute(scale: 10, sign: 20, hi: 30, mid: 40, low: 50);
Assert.Equal(-55340232238.3085240370m, attrSigned.Value);
var attrUnsigned = new DecimalConstantAttribute(scale: 0, sign: 0, hi: 12u, mid: 13u, low: 14u);
Assert.Equal(221360928940349194254m, attrUnsigned.Value);
Assert.Throws<ArgumentOutOfRangeException>(() => new DecimalConstantAttribute(scale: 50, sign: 55, hi: 60, mid: 65, low: 70));
Assert.Throws<ArgumentOutOfRangeException>(() => new DecimalConstantAttribute(scale: 100, sign: 101, hi: 102u, mid: 103u, low: 104u));
}
[Fact]
public static void DefaultDependencyAttributeTests()
{
var attr1 = new DefaultDependencyAttribute(LoadHint.Sometimes);
Assert.Equal(LoadHint.Sometimes, attr1.LoadHint);
var attr2 = new DefaultDependencyAttribute((LoadHint)(-1));
Assert.Equal((LoadHint)(-1), attr2.LoadHint);
}
[Fact]
public static void DependencyAttributeTests()
{
var attr1 = new DependencyAttribute("DependentAssembly", LoadHint.Always);
Assert.Equal("DependentAssembly", attr1.DependentAssembly);
Assert.Equal(LoadHint.Always, attr1.LoadHint);
var attr2 = new DependencyAttribute(null, (LoadHint)(-2));
Assert.Null(attr2.DependentAssembly);
Assert.Equal((LoadHint)(-2), attr2.LoadHint);
}
[Fact]
public static void DisablePrivateReflectionAttributeTests()
{
new DisablePrivateReflectionAttribute();
}
[Fact]
public static void DiscardableAttributeTests()
{
new DiscardableAttribute();
}
[Fact]
public static void ExtensionAttributeTests()
{
new ExtensionAttribute();
}
[Fact]
public static void FixedAddressValueTypeAttributeTests()
{
new FixedAddressValueTypeAttribute();
}
[Fact]
public static void FixedBufferAttributeTests()
{
var attr1 = new FixedBufferAttribute(typeof(AttributesTests), 5);
Assert.Equal(typeof(AttributesTests), attr1.ElementType);
Assert.Equal(5, attr1.Length);
var attr2 = new FixedBufferAttribute(null, -1);
Assert.Null(attr2.ElementType);
Assert.Equal(-1, attr2.Length);
}
[Fact]
public static void IndexerNameAttributeTests()
{
new IndexerNameAttribute("Indexer");
new IndexerNameAttribute(null);
}
[Fact]
public static void InternalsVisibleToAttributeTests()
{
var attr1 = new InternalsVisibleToAttribute("MyAssembly");
Assert.Equal("MyAssembly", attr1.AssemblyName);
Assert.True(attr1.AllInternalsVisible);
attr1.AllInternalsVisible = false;
Assert.False(attr1.AllInternalsVisible);
var attr2 = new InternalsVisibleToAttribute(null);
Assert.Null(attr2.AssemblyName);
}
[Fact]
public static void IteratorStateMachineAttributeTests()
{
new IteratorStateMachineAttribute(typeof(AttributesTests));
new IteratorStateMachineAttribute(null);
}
[Fact]
public static void MethodImplAttributeTests()
{
var attr1 = new MethodImplAttribute();
Assert.Equal(default(MethodImplOptions), attr1.Value);
var attr2 = new MethodImplAttribute(-1);
Assert.Equal((MethodImplOptions)(-1), attr2.Value);
var attr3 = new MethodImplAttribute(MethodImplOptions.Unmanaged);
Assert.Equal(MethodImplOptions.Unmanaged, attr3.Value);
}
[Fact]
public static void ReferenceAssemblyAttributeTests()
{
var attr1 = new ReferenceAssemblyAttribute(null);
Assert.Null(attr1.Description);
var attr2 = new ReferenceAssemblyAttribute("description");
Assert.Equal("description", attr2.Description);
}
[Fact]
public static void RuntimeCompatibilityAttributeTests()
{
var attr = new RuntimeCompatibilityAttribute();
Assert.False(attr.WrapNonExceptionThrows);
attr.WrapNonExceptionThrows = true;
Assert.True(attr.WrapNonExceptionThrows);
}
[Fact]
public static void SpecialNameAttributeTests()
{
new SpecialNameAttribute();
}
[Fact]
public static void StateMachineAttributeTests()
{
var attr1 = new StateMachineAttribute(null);
Assert.Null(attr1.StateMachineType);
var attr2 = new StateMachineAttribute(typeof(AttributesTests));
Assert.Equal(typeof(AttributesTests), attr2.StateMachineType);
}
[Fact]
public static void StringFreezingAttributeTests()
{
new StringFreezingAttribute();
}
[Fact]
public static void SuppressIldasmAttributeTests()
{
new SuppressIldasmAttribute();
}
[Fact]
public static void TypeForwardedFromAttributeTests()
{
string assemblyFullName = "MyAssembly";
var attr = new TypeForwardedFromAttribute(assemblyFullName);
Assert.Equal(assemblyFullName, attr.AssemblyFullName);
AssertExtensions.Throws<ArgumentNullException>("assemblyFullName", () => new TypeForwardedFromAttribute(null));
AssertExtensions.Throws<ArgumentNullException>("assemblyFullName", () => new TypeForwardedFromAttribute(""));
}
[Fact]
public static void TypeForwardedToAttributeTests()
{
var attr1 = new TypeForwardedToAttribute(null);
Assert.Null(attr1.Destination);
var attr2 = new TypeForwardedToAttribute(typeof(AttributesTests));
Assert.Equal(typeof(AttributesTests), attr2.Destination);
}
[Fact]
public static void UnsafeValueTypeAttributeTests()
{
new UnsafeValueTypeAttribute();
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com [email protected]
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Threading;
using Autofac;
using log4net;
using MindTouch.Tasking;
using MindTouch.Xml;
namespace MindTouch.Dream.Test {
/// <summary>
/// A static helper class for creating <see cref="DreamHost"/> and services for testing.
/// </summary>
public static class DreamTestHelper {
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
private static int _port = 1024;
//--- Extension Methods ---
/// <summary>
/// Create a <see cref="IDreamService"/> on a given <see cref="DreamHost"/>.
/// </summary>
/// <typeparam name="T">The <see cref="IDreamService"/> to create.</typeparam>
/// <param name="hostInfo">The info instance for the target <see cref="DreamHost"/>.</param>
/// <param name="pathPrefix">Path prefix to use for randomly generated path (primarily used to more easily recognize the service in logs).</param>
/// <param name="extraConfig">Additional configuration to use for service instantiation.</param>
/// <returns>An instance of <see cref="DreamServiceInfo"/> for easy service access</returns>
public static DreamServiceInfo CreateService<T>(this DreamHostInfo hostInfo, string pathPrefix, XDoc extraConfig) where T : IDreamService {
return CreateService(hostInfo, typeof(T), pathPrefix, extraConfig);
}
/// <summary>
/// Create a <see cref="IDreamService"/> on a given <see cref="DreamHost"/>.
/// </summary>
/// <typeparam name="T">The <see cref="IDreamService"/> to create.</typeparam>
/// <param name="hostInfo">The info instance for the target <see cref="DreamHost"/>.</param>
/// <param name="pathPrefix">Path prefix to use for randomly generated path (primarily used to more easily recognize the service in logs).</param>
/// <returns>An instance of <see cref="DreamServiceInfo"/> for easy service access</returns>
public static DreamServiceInfo CreateService<T>(this DreamHostInfo hostInfo, string pathPrefix) where T : IDreamService {
return CreateService(hostInfo, typeof(T), pathPrefix);
}
/// <summary>
/// Create a <see cref="IDreamService"/> on a given <see cref="DreamHost"/>.
/// </summary>
/// <param name="hostInfo">The info instance for the target <see cref="DreamHost"/>.</param>
/// <param name="serviceType">Type of the <see cref="IDreamService"/> to create.</param>
/// <param name="pathPrefix">Path prefix to use for randomly generated path (primarily used to more easily recognize the service in logs).</param>
/// <param name="extraConfig">Additional configuration to use for service instantiation.</param>
/// <returns>An instance of <see cref="DreamServiceInfo"/> for easy service access</returns>
public static DreamServiceInfo CreateService(this DreamHostInfo hostInfo, Type serviceType, string pathPrefix, XDoc extraConfig) {
string path = (string.IsNullOrEmpty(pathPrefix)) ? StringUtil.CreateAlphaNumericKey(6).ToLower() : pathPrefix + "_" + StringUtil.CreateAlphaNumericKey(3).ToLower();
XDoc config = new XDoc("config")
.Elem("class", serviceType.FullName)
.Elem("path", path);
if(extraConfig != null) {
foreach(XDoc extra in extraConfig["*"]) {
config.Add(extra);
}
}
return CreateService(hostInfo, config);
}
/// <summary>
/// Create a <see cref="IDreamService"/> on a given <see cref="DreamHost"/>.
/// </summary>
/// <param name="hostInfo">The info instance for the target <see cref="DreamHost"/>.</param>
/// <param name="sid">Service Identifier</param>
/// <param name="pathPrefix">Path prefix to use for randomly generated path (primarily used to more easily recognize the service in logs).</param>
/// <param name="extraConfig">Additional configuration to use for service instantiation.</param>
/// <returns>An instance of <see cref="DreamServiceInfo"/> for easy service access</returns>
public static DreamServiceInfo CreateService(this DreamHostInfo hostInfo, string sid, string pathPrefix, XDoc extraConfig) {
string path = (string.IsNullOrEmpty(pathPrefix)) ? StringUtil.CreateAlphaNumericKey(6).ToLower() : pathPrefix + "_" + StringUtil.CreateAlphaNumericKey(3).ToLower();
XDoc config = new XDoc("config")
.Elem("sid", sid)
.Elem("path", path);
if(extraConfig != null) {
foreach(XDoc extra in extraConfig["*"]) {
config.Add(extra);
}
}
return CreateService(hostInfo, config);
}
/// <summary>
/// Create a <see cref="IDreamService"/> on a given <see cref="DreamHost"/>.
/// </summary>
/// <param name="hostInfo">The info instance for the target <see cref="DreamHost"/>.</param>
/// <param name="serviceType">Type of the <see cref="IDreamService"/> to create.</param>
/// <param name="pathPrefix">Path prefix to use for randomly generated path (primarily used to more easily recognize the service in logs).</param>
/// <returns>An instance of <see cref="DreamServiceInfo"/> for easy service access</returns>
public static DreamServiceInfo CreateService(this DreamHostInfo hostInfo, Type serviceType, string pathPrefix) {
string path = (string.IsNullOrEmpty(pathPrefix)) ? StringUtil.CreateAlphaNumericKey(6).ToLower() : pathPrefix + "_" + StringUtil.CreateAlphaNumericKey(3).ToLower();
XDoc config = new XDoc("config")
.Elem("class", serviceType.FullName)
.Elem("path", path);
return CreateService(hostInfo, config);
}
/// <summary>
/// Create a <see cref="IDreamService"/> on a given <see cref="DreamHost"/>.
/// </summary>
/// <param name="hostInfo">The info instance for the target <see cref="DreamHost"/>.</param>
/// <param name="config">Configuration to use for service instantiation.</param>
/// <returns>An instance of <see cref="DreamServiceInfo"/> for easy service access</returns>
public static DreamServiceInfo CreateService(this DreamHostInfo hostInfo, XDoc config) {
string path = config["path"].AsText;
DreamMessage result = hostInfo.Host.Self.At("services").Post(config, new Result<DreamMessage>()).Wait();
if(!result.IsSuccessful) {
throw new Exception(string.Format(
"Unable to start service with config:\r\n{0}\r\n{1}",
config.ToPrettyString(),
result.HasDocument
? string.Format("{0}: {1}", result.Status, result.ToDocument()["message"].AsText)
: result.Status.ToString()));
}
return new DreamServiceInfo(hostInfo, path, result.ToDocument());
}
/// <summary>
/// Create a new mock service instance.
/// </summary>
/// <param name="hostInfo">Host info.</param>
/// <returns>New mock service info instance.</returns>
public static MockServiceInfo CreateMockService(this DreamHostInfo hostInfo) {
return MockService.CreateMockService(hostInfo);
}
/// <summary>
/// Create a new mock service instance.
/// </summary>
/// <param name="hostInfo">Host info.</param>
/// <param name="extraConfig">Additional service configuration.</param>
/// <returns>New mock service info instance.</returns>
public static MockServiceInfo CreateMockService(this DreamHostInfo hostInfo, XDoc extraConfig) {
return MockService.CreateMockService(hostInfo, extraConfig);
}
/// <summary>
/// Create a new mock service instance.
/// </summary>
/// <param name="hostInfo">Host info.</param>
/// <param name="extraConfig">Additional service configuration.</param>
/// <param name="privateStorage">Use private storage</param>
/// <returns>New mock service info instance.</returns>
public static MockServiceInfo CreateMockService(this DreamHostInfo hostInfo, XDoc extraConfig, bool privateStorage) {
return MockService.CreateMockService(hostInfo, extraConfig, privateStorage);
}
//--- Class Methods ---
/// <summary>
/// Create a <see cref="DreamHost"/> at a random port (to avoid collisions in tests).
/// </summary>
/// <param name="config">Additional configuration for the host.</param>
/// <param name="container">IoC Container to use.</param>
/// <returns>A <see cref="DreamHostInfo"/> instance for easy access to the host.</returns>
public static DreamHostInfo CreateRandomPortHost(XDoc config, IContainer container) {
var port = GetPort();
var path = "/";
if(!config["uri.public"].IsEmpty) {
path = config["uri.public"].AsText;
}
var localhost = string.Format("http://localhost:{0}{1}", port, path);
UpdateElement(config, "http-port", port.ToString());
UpdateElement(config, "uri.public", localhost);
var apikey = config["apikey"].Contents;
if(string.IsNullOrEmpty(apikey)) {
apikey = StringUtil.CreateAlphaNumericKey(32); //generate a random api key
config.Elem("apikey", apikey);
}
_log.DebugFormat("api key: {0}", apikey);
_log.DebugFormat("port: {0}", port);
var host = container == null ? new DreamHost(config) : new DreamHost(config, container);
host.Self.At("load").With("name", "mindtouch.dream.test").Post(DreamMessage.Ok());
return new DreamHostInfo(Plug.New(localhost), host, apikey);
}
private static int GetPort() {
var port = Interlocked.Increment(ref _port);
if(port > 30000) {
Interlocked.CompareExchange(ref _port, 1024, port);
return GetPort();
}
return port;
}
/// <summary>
/// Create a <see cref="DreamHost"/> at a random port (to avoid collisions in tests).
/// </summary>
/// <param name="config">Additional configuration for the host.</param>
/// <returns>A <see cref="DreamHostInfo"/> instance for easy access to the host.</returns>
public static DreamHostInfo CreateRandomPortHost(XDoc config) {
return CreateRandomPortHost(config, null);
}
/// <summary>
/// Create a <see cref="DreamHost"/> at a random port (to avoid collisions in tests).
/// </summary>
/// <returns>A <see cref="DreamHostInfo"/> instance for easy access to the host.</returns>
public static DreamHostInfo CreateRandomPortHost() {
return CreateRandomPortHost(new XDoc("config"));
}
private static void UpdateElement(XDoc config, string element, string value) {
if(config[element].IsEmpty) {
config.Elem(element, value);
} else {
config[element].Replace(new XDoc(element).Value(value));
}
}
}
}
| |
/*
Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.
The MIT License(MIT)
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 Shield.Communication;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
namespace Shield
{
public enum ConnectionState
{
NotConnected = 0,
Connecting = 1,
Connected = 2,
CouldNotConnect = 3,
Disconnecting = 4
}
public class AppSettings : INotifyPropertyChanged
{
private Windows.Storage.ApplicationDataContainer localSettings;
private Connections connectionList;
public event PropertyChangedEventHandler PropertyChanged;
private string[] ConnectionStateText;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public static AppSettings Instance;
private bool isLogging;
private StringBuilder log = new StringBuilder();
private bool isListening = false;
public AppSettings()
{
if (Instance == null)
{
Instance = this;
}
var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
ConnectionStateText = new[]
{
loader.GetString("NotConnected"), loader.GetString("Connecting"), loader.GetString("Connected"),
loader.GetString("CouldNotConnect"), loader.GetString("Disconnecting")
};
DeviceNames = new List<string>
{
loader.GetString("Bluetooth"),
loader.GetString("NetworkDiscovery"),
loader.GetString("NetworkDirect")
};
try
{
localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
connectionList = new Connections();
}
catch (Exception e)
{
Debug.WriteLine("Exception while using LocalSettings: " + e.ToString());
throw;
}
}
public bool AddOrUpdateValue(Object value, [CallerMemberName] string Key = null)
{
bool valueChanged = false;
if (localSettings.Values.ContainsKey(Key))
{
if (localSettings.Values[Key] != value)
{
localSettings.Values[Key] = value;
valueChanged = true;
}
}
else
{
localSettings.Values.Add(Key, value);
valueChanged = true;
}
return valueChanged;
}
public T GetValueOrDefault<T>(T defaultValue, [CallerMemberName] string Key = null)
{
T value;
// If the key exists, retrieve the value.
if (localSettings.Values.ContainsKey(Key))
{
try
{
value = (T)localSettings.Values[Key];
}
catch (InvalidCastException)
{
value = defaultValue;
}
}
else
{
value = defaultValue;
}
return value;
}
public bool Remove(Object value, [CallerMemberName] string Key = null)
{
if (localSettings.Values.ContainsKey(Key))
{
localSettings.DeleteContainer(Key);
return true;
}
return false;
}
public bool AutoConnect
{
get { return GetValueOrDefault(true); }
set { AddOrUpdateValue(value); }
}
public bool IsListening
{
get { return isListening; }
set
{
isListening = value;
OnPropertyChanged("IsListening");
}
}
public bool AlwaysRunning
{
get { return GetValueOrDefault(true); }
set { AddOrUpdateValue(value); }
}
public bool NoListVisible => !ListVisible;
public bool ListVisible => ConnectionList != null && ConnectionList.Any();
public int ConnectionIndex
{
get
{
return GetValueOrDefault(0);
}
set
{
AddOrUpdateValue(value);
OnPropertyChanged("BluetoothVisible");
OnPropertyChanged("NetworkDirectVisible");
OnPropertyChanged("NotNetworkDirectVisible");
MainPage.Instance.SetService();
}
}
internal const int CONNECTION_BLUETOOTH = 0;
internal const int CONNECTION_WIFI = 1;
internal const int CONNECTION_MANUAL = 2;
internal const int CONNECTION_USB = 3;
internal static readonly int BroadcastPort = 1235;
public string[] ConnectionItems => new[] {"Bluetooth", "Network", "Manual", "USB"};
public bool NotNetworkDirectVisible => !NetworkDirectVisible;
public bool BluetoothVisible => ConnectionIndex == 0;
public bool NetworkVisible => ConnectionIndex == 1;
public bool NetworkDirectVisible => ConnectionIndex == 2;
public bool USBVisible => ConnectionIndex == 3;
public string Hostname
{
get { return GetValueOrDefault(""); }
set { AddOrUpdateValue(value); }
}
public string UserInfo1
{
get { return GetValueOrDefault(""); }
set { AddOrUpdateValue(value); }
}
public string UserInfo2
{
get { return GetValueOrDefault(""); }
set { AddOrUpdateValue(value); }
}
public string UserInfo3
{
get { return GetValueOrDefault(""); }
set { AddOrUpdateValue(value); }
}
public string UserInfo4
{
get { return GetValueOrDefault(""); }
set { AddOrUpdateValue(value); }
}
public int Hostport
{
get { return GetValueOrDefault(0); }
set { AddOrUpdateValue(value); }
}
public string PreviousConnectionName
{
get { return GetValueOrDefault(""); }
set { AddOrUpdateValue(value); }
}
public string BlobAccountName
{
get { return GetValueOrDefault(""); }
set { AddOrUpdateValue(value); }
}
public string BlobAccountKey
{
get { return GetValueOrDefault(""); }
set { AddOrUpdateValue(value); }
}
public Connections ConnectionList
{
get { return connectionList; }
set
{
connectionList = value;
OnPropertyChanged("ConnectionList");
OnPropertyChanged("ListVisible");
OnPropertyChanged("NoListVisible");
}
}
public bool IsFullscreen
{
get { return GetValueOrDefault(true); }
set {
AddOrUpdateValue(value);
OnPropertyChanged("IsFullscreen");
OnPropertyChanged("IsControlscreen");
}
}
public bool IsControlscreen
{
get { return !IsFullscreen; }
set
{
IsFullscreen = !value;
}
}
public bool IsLogging
{
get { return isLogging; }
set
{
isLogging = value;
OnPropertyChanged("IsLoggingSwitchText");
}
}
public string IsLoggingSwitchText
{
get { return isLogging ? "Turn OFF" : "Turn ON"; }
}
public string LogText
{
get
{
return log.ToString();
}
set
{
log.Append(value);
OnPropertyChanged("LogText");
}
}
public StringBuilder Log
{
get { return log; }
}
public int CurrentConnectionState
{
get { return GetValueOrDefault((int) ConnectionState.NotConnected); }
set {
AddOrUpdateValue(value);
OnPropertyChanged("CurrentConnectionStateText");
}
}
public string CurrentConnectionStateText
{
get { return this.ConnectionStateText[CurrentConnectionState]; }
}
public List<string> DeviceNames { get; set; }
public void ReportChanged(string key)
{
OnPropertyChanged(key);
}
public bool MissingBackButton => !Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons");
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Linq;
namespace MixpanelSDK.UnityEditor.iOS.Xcode.PBX
{
class PropertyCommentChecker
{
private int m_Level;
private bool m_All;
private List<List<string>> m_Props;
/* The argument is an array of matcher strings each of which determine
whether a property with a certain path needs to be decorated with a
comment.
A path is a number of path elements concatenated by '/'. The last path
element is either:
the key if we're referring to a dict key
the value if we're referring to a value in an array
the value if we're referring to a value in a dict
All other path elements are either:
the key if the container is dict
'*' if the container is array
Path matcher has the same structure as a path, except that any of the
elements may be '*'. Matcher matches a path if both have the same number
of elements and for each pair matcher element is the same as path element
or is '*'.
a/b/c matches a/b/c but not a/b nor a/b/c/d
a/* /c matches a/d/c but not a/b nor a/b/c/d
* /* /* matches any path from three elements
*/
protected PropertyCommentChecker(int level, List<List<string>> props)
{
m_Level = level;
m_All = false;
m_Props = props;
}
public PropertyCommentChecker()
{
m_Level = 0;
m_All = false;
m_Props = new List<List<string>>();
}
public PropertyCommentChecker(IEnumerable<string> props)
{
m_Level = 0;
m_All = false;
m_Props = new List<List<string>>();
foreach (var prop in props)
{
m_Props.Add(new List<string>(prop.Split('/')));
}
}
bool CheckContained(string prop)
{
if (m_All)
return true;
foreach (var list in m_Props)
{
if (list.Count == m_Level+1)
{
if (list[m_Level] == prop)
return true;
if (list[m_Level] == "*")
{
m_All = true; // short-circuit all at this level
return true;
}
}
}
return false;
}
public bool CheckStringValueInArray(string value) { return CheckContained(value); }
public bool CheckKeyInDict(string key) { return CheckContained(key); }
public bool CheckStringValueInDict(string key, string value)
{
foreach (var list in m_Props)
{
if (list.Count == m_Level + 2)
{
if ((list[m_Level] == "*" || list[m_Level] == key) &&
list[m_Level+1] == "*" || list[m_Level+1] == value)
return true;
}
}
return false;
}
public PropertyCommentChecker NextLevel(string prop)
{
var newList = new List<List<string>>();
foreach (var list in m_Props)
{
if (list.Count <= m_Level+1)
continue;
if (list[m_Level] == "*" || list[m_Level] == prop)
newList.Add(list);
}
return new PropertyCommentChecker(m_Level + 1, newList);
}
}
class Serializer
{
public static PBXElementDict ParseTreeAST(TreeAST ast, TokenList tokens, string text)
{
var el = new PBXElementDict();
foreach (var kv in ast.values)
{
PBXElementString key = ParseIdentifierAST(kv.key, tokens, text);
PBXElement value = ParseValueAST(kv.value, tokens, text);
el[key.value] = value;
}
return el;
}
public static PBXElementArray ParseArrayAST(ArrayAST ast, TokenList tokens, string text)
{
var el = new PBXElementArray();
foreach (var v in ast.values)
{
el.values.Add(ParseValueAST(v, tokens, text));
}
return el;
}
public static PBXElement ParseValueAST(ValueAST ast, TokenList tokens, string text)
{
if (ast is TreeAST)
return ParseTreeAST((TreeAST)ast, tokens, text);
if (ast is ArrayAST)
return ParseArrayAST((ArrayAST)ast, tokens, text);
if (ast is IdentifierAST)
return ParseIdentifierAST((IdentifierAST)ast, tokens, text);
return null;
}
public static PBXElementString ParseIdentifierAST(IdentifierAST ast, TokenList tokens, string text)
{
Token tok = tokens[ast.value];
string value;
switch (tok.type)
{
case TokenType.String:
value = text.Substring(tok.begin, tok.end - tok.begin);
return new PBXElementString(value);
case TokenType.QuotedString:
value = text.Substring(tok.begin, tok.end - tok.begin);
value = PBXStream.UnquoteString(value);
return new PBXElementString(value);
default:
throw new Exception("Internal parser error");
}
}
static string k_Indent = "\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t";
static string GetIndent(int indent)
{
return k_Indent.Substring(0, indent);
}
static void WriteStringImpl(StringBuilder sb, string s, bool comment, GUIDToCommentMap comments)
{
if (comment)
comments.WriteStringBuilder(sb, s);
else
sb.Append(PBXStream.QuoteStringIfNeeded(s));
}
public static void WriteDictKeyValue(StringBuilder sb, string key, PBXElement value, int indent, bool compact,
PropertyCommentChecker checker, GUIDToCommentMap comments)
{
if (!compact)
{
sb.Append("\n");
sb.Append(GetIndent(indent));
}
WriteStringImpl(sb, key, checker.CheckKeyInDict(key), comments);
sb.Append(" = ");
if (value is PBXElementString)
WriteStringImpl(sb, value.AsString(), checker.CheckStringValueInDict(key, value.AsString()), comments);
else if (value is PBXElementDict)
WriteDict(sb, value.AsDict(), indent, compact, checker.NextLevel(key), comments);
else if (value is PBXElementArray)
WriteArray(sb, value.AsArray(), indent, compact, checker.NextLevel(key), comments);
sb.Append(";");
if (compact)
sb.Append(" ");
}
public static void WriteDict(StringBuilder sb, PBXElementDict el, int indent, bool compact,
PropertyCommentChecker checker, GUIDToCommentMap comments)
{
sb.Append("{");
if (el.Contains("isa"))
WriteDictKeyValue(sb, "isa", el["isa"], indent+1, compact, checker, comments);
var keys = new List<string>(el.values.Keys);
keys.Sort(StringComparer.Ordinal);
foreach (var key in keys)
{
if (key != "isa")
WriteDictKeyValue(sb, key, el[key], indent+1, compact, checker, comments);
}
if (!compact)
{
sb.Append("\n");
sb.Append(GetIndent(indent));
}
sb.Append("}");
}
public static void WriteArray(StringBuilder sb, PBXElementArray el, int indent, bool compact,
PropertyCommentChecker checker, GUIDToCommentMap comments)
{
sb.Append("(");
foreach (var value in el.values)
{
if (!compact)
{
sb.Append("\n");
sb.Append(GetIndent(indent+1));
}
if (value is PBXElementString)
WriteStringImpl(sb, value.AsString(), checker.CheckStringValueInArray(value.AsString()), comments);
else if (value is PBXElementDict)
WriteDict(sb, value.AsDict(), indent+1, compact, checker.NextLevel("*"), comments);
else if (value is PBXElementArray)
WriteArray(sb, value.AsArray(), indent+1, compact, checker.NextLevel("*"), comments);
sb.Append(",");
if (compact)
sb.Append(" ");
}
if (!compact)
{
sb.Append("\n");
sb.Append(GetIndent(indent));
}
sb.Append(")");
}
}
} // namespace MixpanelSDK.UnityEditor.iOS.Xcode
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using Microsoft.PowerShell.Activities;
using System.Management.Automation;
using System.Activities;
using System.Collections.Generic;
using System.ComponentModel;
namespace Microsoft.PowerShell.Core.Activities
{
/// <summary>
/// Activity to invoke the Microsoft.PowerShell.Core\Register-PSSessionConfiguration command in a Workflow.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")]
public sealed class RegisterPSSessionConfiguration : PSRemotingActivity
{
/// <summary>
/// Gets the display name of the command invoked by this activity.
/// </summary>
public RegisterPSSessionConfiguration()
{
this.DisplayName = "Register-PSSessionConfiguration";
}
/// <summary>
/// Gets the fully qualified name of the command invoked by this activity.
/// </summary>
public override string PSCommandName { get { return "Microsoft.PowerShell.Core\\Register-PSSessionConfiguration"; } }
// Arguments
/// <summary>
/// Provides access to the ProcessorArchitecture parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> ProcessorArchitecture { get; set; }
/// <summary>
/// Provides access to the SessionType parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.Runspaces.PSSessionType> SessionType { get; set; }
/// <summary>
/// Provides access to the Name parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Name { get; set; }
/// <summary>
/// Provides access to the AssemblyName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> AssemblyName { get; set; }
/// <summary>
/// Provides access to the ApplicationBase parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> ApplicationBase { get; set; }
/// <summary>
/// Provides access to the ConfigurationTypeName parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> ConfigurationTypeName { get; set; }
/// <summary>
/// Provides access to the RunAsCredential parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSCredential> RunAsCredential { get; set; }
/// <summary>
/// Provides access to the ThreadApartmentState parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Threading.ApartmentState> ThreadApartmentState { get; set; }
/// <summary>
/// Provides access to the ThreadOptions parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.Runspaces.PSThreadOptions> ThreadOptions { get; set; }
/// <summary>
/// Provides access to the AccessMode parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.Runspaces.PSSessionConfigurationAccessMode> AccessMode { get; set; }
/// <summary>
/// Provides access to the UseSharedProcess parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> UseSharedProcess { get; set; }
/// <summary>
/// Provides access to the StartupScript parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> StartupScript { get; set; }
/// <summary>
/// Provides access to the MaximumReceivedDataSizePerCommandMB parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Nullable<System.Double>> MaximumReceivedDataSizePerCommandMB { get; set; }
/// <summary>
/// Provides access to the MaximumReceivedObjectSizeMB parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Nullable<System.Double>> MaximumReceivedObjectSizeMB { get; set; }
/// <summary>
/// Provides access to the SecurityDescriptorSddl parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> SecurityDescriptorSddl { get; set; }
/// <summary>
/// Provides access to the ShowSecurityDescriptorUI parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> ShowSecurityDescriptorUI { get; set; }
/// <summary>
/// Provides access to the Force parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> Force { get; set; }
/// <summary>
/// Provides access to the NoServiceRestart parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.SwitchParameter> NoServiceRestart { get; set; }
/// <summary>
/// Provides access to the PSVersion parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Version> PSVersion { get; set; }
/// <summary>
/// Provides access to the SessionTypeOption parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSSessionTypeOption> SessionTypeOption { get; set; }
/// <summary>
/// Provides access to the TransportOption parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Management.Automation.PSTransportOption> TransportOption { get; set; }
/// <summary>
/// Provides access to the ModulesToImport parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.Object[]> ModulesToImport { get; set; }
/// <summary>
/// Provides access to the Path parameter.
/// </summary>
[ParameterSpecificCategory]
[DefaultValue(null)]
public InArgument<System.String> Path { get; set; }
// Module defining this command
// Optional custom code for this activity
/// <summary>
/// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run.
/// </summary>
/// <param name="context">The NativeActivityContext for the currently running activity.</param>
/// <returns>A populated instance of System.Management.Automation.PowerShell</returns>
/// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks>
protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context)
{
System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create();
System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName);
// Initialize the arguments
if(ProcessorArchitecture.Expression != null)
{
targetCommand.AddParameter("ProcessorArchitecture", ProcessorArchitecture.Get(context));
}
if(SessionType.Expression != null)
{
targetCommand.AddParameter("SessionType", SessionType.Get(context));
}
if(Name.Expression != null)
{
targetCommand.AddParameter("Name", Name.Get(context));
}
if(AssemblyName.Expression != null)
{
targetCommand.AddParameter("AssemblyName", AssemblyName.Get(context));
}
if(ApplicationBase.Expression != null)
{
targetCommand.AddParameter("ApplicationBase", ApplicationBase.Get(context));
}
if(ConfigurationTypeName.Expression != null)
{
targetCommand.AddParameter("ConfigurationTypeName", ConfigurationTypeName.Get(context));
}
if(RunAsCredential.Expression != null)
{
targetCommand.AddParameter("RunAsCredential", RunAsCredential.Get(context));
}
if(ThreadApartmentState.Expression != null)
{
targetCommand.AddParameter("ThreadApartmentState", ThreadApartmentState.Get(context));
}
if(ThreadOptions.Expression != null)
{
targetCommand.AddParameter("ThreadOptions", ThreadOptions.Get(context));
}
if(AccessMode.Expression != null)
{
targetCommand.AddParameter("AccessMode", AccessMode.Get(context));
}
if(UseSharedProcess.Expression != null)
{
targetCommand.AddParameter("UseSharedProcess", UseSharedProcess.Get(context));
}
if(StartupScript.Expression != null)
{
targetCommand.AddParameter("StartupScript", StartupScript.Get(context));
}
if(MaximumReceivedDataSizePerCommandMB.Expression != null)
{
targetCommand.AddParameter("MaximumReceivedDataSizePerCommandMB", MaximumReceivedDataSizePerCommandMB.Get(context));
}
if(MaximumReceivedObjectSizeMB.Expression != null)
{
targetCommand.AddParameter("MaximumReceivedObjectSizeMB", MaximumReceivedObjectSizeMB.Get(context));
}
if(SecurityDescriptorSddl.Expression != null)
{
targetCommand.AddParameter("SecurityDescriptorSddl", SecurityDescriptorSddl.Get(context));
}
if(ShowSecurityDescriptorUI.Expression != null)
{
targetCommand.AddParameter("ShowSecurityDescriptorUI", ShowSecurityDescriptorUI.Get(context));
}
if(Force.Expression != null)
{
targetCommand.AddParameter("Force", Force.Get(context));
}
if(NoServiceRestart.Expression != null)
{
targetCommand.AddParameter("NoServiceRestart", NoServiceRestart.Get(context));
}
if(PSVersion.Expression != null)
{
targetCommand.AddParameter("PSVersion", PSVersion.Get(context));
}
if(SessionTypeOption.Expression != null)
{
targetCommand.AddParameter("SessionTypeOption", SessionTypeOption.Get(context));
}
if(TransportOption.Expression != null)
{
targetCommand.AddParameter("TransportOption", TransportOption.Get(context));
}
if(ModulesToImport.Expression != null)
{
targetCommand.AddParameter("ModulesToImport", ModulesToImport.Get(context));
}
if(Path.Expression != null)
{
targetCommand.AddParameter("Path", Path.Get(context));
}
return new ActivityImplementationContext() { PowerShellInstance = invoker };
}
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at [email protected]
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.IO;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Principal;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using MbUnit.Framework;
using Microsoft.ApplicationBlocks.Data;
using Moq;
using Ninject;
using Ninject.Activation;
using Ninject.Parameters;
using Ninject.Planning.Bindings;
using Subtext.Configuration;
using Subtext.Extensibility;
using Subtext.Framework;
using Subtext.Framework.Components;
using Subtext.Framework.Configuration;
using Subtext.Framework.Data;
using Subtext.Framework.Emoticons;
using Subtext.Framework.Providers;
using Subtext.Framework.Routing;
using Subtext.Framework.Services;
using Subtext.Framework.Services.SearchEngine;
using Subtext.Framework.Text;
using Subtext.Framework.Web;
using Subtext.Framework.Web.HttpModules;
using Subtext.Infrastructure;
namespace UnitTests.Subtext
{
/// <summary>
/// Contains helpful methods for packing and unpacking resources
/// </summary>
public static class UnitTestHelper
{
internal static HostInfo CreateHostInfo()
{
return new HostInfo(new NameValueCollection());
}
/// <summary>
/// Unpacks an embedded resource into the specified directory. The resource name should
/// be everything after 'UnitTests.Subtext.Resources.'.
/// </summary>
/// <remarks>Omit the UnitTests.Subtext.Resources. part of the
/// resource name.</remarks>
/// <param name="resourceName"></param>
/// <param name="outputPath">The path to write the file as.</param>
public static void UnpackEmbeddedResource(string resourceName, string outputPath)
{
Stream stream = UnpackEmbeddedResource(resourceName);
using (var reader = new StreamReader(stream))
{
using (StreamWriter writer = File.CreateText(outputPath))
{
writer.Write(reader.ReadToEnd());
writer.Flush();
}
}
}
/// <summary>
/// Unpacks an embedded resource as a string. The resource name should
/// be everything after 'UnitTests.Subtext.Resources.'.
/// </summary>
/// <remarks>Omit the UnitTests.Subtext.Resources. part of the
/// resource name.</remarks>
/// <param name="resourceName"></param>
/// <param name="encoding">The path to write the file as.</param>
public static string UnpackEmbeddedResource(string resourceName, Encoding encoding)
{
Stream stream = UnpackEmbeddedResource(resourceName);
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
/// <summary>
/// Unpacks an embedded binary resource into the specified directory. The resource name should
/// be everything after 'UnitTests.Subtext.Resources.'.
/// </summary>
/// <remarks>Omit the UnitTests.Subtext.Resources. part of the
/// resource name.</remarks>
/// <param name="resourceName"></param>
/// <param name="fileName">The file to write the resourcce.</param>
public static string UnpackEmbeddedBinaryResource(string resourceName, string fileName)
{
using (Stream stream = UnpackEmbeddedResource(resourceName))
{
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
string filePath = !Path.IsPathRooted(fileName) ? GetPathInExecutingAssemblyLocation(fileName) : Path.GetFullPath(fileName);
using (FileStream outStream = File.Create(filePath))
{
outStream.Write(buffer, 0, buffer.Length);
}
return filePath;
}
}
public static string GetPathInExecutingAssemblyLocation(string fileName)
{
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fileName);
}
/// <summary>
/// Unpacks an embedded resource into a Stream. The resource name should
/// be everything after 'UnitTests.Subtext.Resources.'.
/// </summary>
/// <remarks>Omit the UnitTests.Subtext.Resources. part of the
/// resource name.</remarks>
/// <param name="resourceName">Name of the resource.</param>
public static Stream UnpackEmbeddedResource(string resourceName)
{
Assembly assembly = Assembly.GetExecutingAssembly();
return assembly.GetManifestResourceStream("UnitTests.Subtext.Resources." + resourceName);
}
/// <summary>
/// Generates a unique string.
/// </summary>
/// <returns></returns>
public static string GenerateUniqueString()
{
return Guid.NewGuid().ToString().Replace("-", "");
}
/// <summary>
/// Generates a unique host name.
/// </summary>
/// <returns></returns>
public static string GenerateUniqueHostname()
{
return GenerateUniqueString() + ".com";
}
/// <summary>
/// Sets the HTTP context with a valid request for the blog specified
/// by the host and application.
/// </summary>
/// <param name="host">Host.</param>
/// <param name="subfolder">Subfolder Name.</param>
public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, string subfolder)
{
return SetHttpContextWithBlogRequest(host, subfolder, string.Empty);
}
/// <summary>
/// Sets the HTTP context with a valid request for the blog specified
/// by the host and subfolder hosted in a virtual directory.
/// </summary>
/// <param name="host">Host.</param>
/// <param name="subfolder">Subfolder Name.</param>
/// <param name="applicationPath"></param>
public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, string subfolder,
string applicationPath)
{
return SetHttpContextWithBlogRequest(host, subfolder, applicationPath, "default.aspx");
}
public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, int port, string subfolder,
string applicationPath)
{
return SetHttpContextWithBlogRequest(host, port, subfolder, applicationPath, "default.aspx");
}
public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, string subfolder,
string applicationPath, string page)
{
return SetHttpContextWithBlogRequest(host, 80, subfolder, applicationPath, page);
}
public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, int port, string subfolder,
string applicationPath, string page)
{
return SetHttpContextWithBlogRequest(host, port, subfolder, applicationPath, page, null, "GET");
}
public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, string subfolder,
string applicationPath, string page,
TextWriter output)
{
return SetHttpContextWithBlogRequest(host, subfolder, applicationPath, page, output, "GET");
}
public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, string subfolder,
string applicationPath, string page,
TextWriter output, string httpVerb)
{
return SetHttpContextWithBlogRequest(host, 80, subfolder, applicationPath, page, output, httpVerb);
}
public static SimulatedHttpRequest SetHttpContextWithBlogRequest(string host, int port, string subfolder,
string applicationPath, string page,
TextWriter output, string httpVerb)
{
HttpContext.Current = null;
applicationPath = HttpHelper.StripSurroundingSlashes(applicationPath); // Subtext.Web
subfolder = StripSlashes(subfolder); // MyBlog
string appPhysicalDir = @"c:\projects\SubtextSystem\";
if (applicationPath.Length == 0)
{
applicationPath = "/";
}
else
{
appPhysicalDir += applicationPath + @"\"; // c:\projects\SubtextSystem\Subtext.Web\
applicationPath = "/" + applicationPath; // /Subtext.Web
}
SetHttpRequestApplicationPath(applicationPath);
if (subfolder.Length > 0)
{
page = subfolder + "/" + page; // MyBlog/default.aspx
}
string query = string.Empty;
var workerRequest = new SimulatedHttpRequest(applicationPath, appPhysicalDir, appPhysicalDir + page, page,
query, output, host, port, httpVerb);
HttpContext.Current = new HttpContext(workerRequest);
BlogRequest.Current = new BlogRequest(host, subfolder, HttpContext.Current.Request.Url, host == "localhost");
return workerRequest;
}
static void SetHttpRequestApplicationPath(string applicationPath)
{
//We cheat by using reflection.
FieldInfo runtimeField = typeof(HttpRuntime).GetField("_theRuntime",
BindingFlags.NonPublic | BindingFlags.Static);
Assert.IsNotNull(runtimeField);
var currentRuntime = runtimeField.GetValue(null) as HttpRuntime;
Assert.IsNotNull(currentRuntime);
FieldInfo appDomainAppVPathField = typeof(HttpRuntime).GetField("_appDomainAppVPath",
BindingFlags.NonPublic |
BindingFlags.Instance);
Assert.IsNotNull(appDomainAppVPathField);
Type virtualPathType =
Type.GetType(
"System.Web.VirtualPath, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
true);
Assert.IsNotNull(virtualPathType);
MethodInfo createMethod = virtualPathType.GetMethod("Create", BindingFlags.Static | BindingFlags.Public,
null, new[] { typeof(string) }, null);
object virtualPath = createMethod.Invoke(null, new object[] { applicationPath });
appDomainAppVPathField.SetValue(currentRuntime, virtualPath);
}
/// <summary>
/// Strips the slashes from the target string.
/// </summary>
/// <param name="target">Target.</param>
/// <returns></returns>
public static string StripSlashes(string target)
{
if (target.Length == 0)
{
return target;
}
return target.Replace(@"\", string.Empty).Replace("/", string.Empty);
}
/// <summary>
/// Strips the outer slashes.
/// </summary>
/// <param name="target">Target.</param>
/// <returns></returns>
public static string StripOuterSlashes(string target)
{
if (target.Length == 0)
{
return target;
}
char firstChar = target[0];
if (firstChar == '\\' || firstChar == '/')
{
target = target.Substring(1);
}
if (target.Length > 0)
{
char lastChar = target[target.Length - 1];
if (lastChar == '\\' || lastChar == '/')
{
target = target.Substring(0, target.Length - 1);
}
}
return target;
}
/// <summary>
/// This is useful when two strings appear to be but Assert.AreEqual says they are not.
/// </summary>
/// <param name="result"></param>
/// <param name="expected"></param>
public static void AssertStringsEqualCharacterByCharacter(string expected, string result)
{
if (result != expected)
{
int unequalPos = 0;
for (int i = 0; i < Math.Max(result.Length, expected.Length); i++)
{
var originalChar = (char)0;
var expectedChar = (char)0;
if (i < result.Length)
{
originalChar = result[i];
}
if (i < expected.Length)
{
expectedChar = expected[i];
}
if (unequalPos == 0 && originalChar != expectedChar)
{
unequalPos = i;
}
string expectedCharText = "" + originalChar;
if (char.IsWhiteSpace(originalChar))
{
expectedCharText = "{" + (int)originalChar + "}";
}
string expectedCharDisplay = "" + expectedChar;
if (char.IsWhiteSpace(expectedChar))
{
expectedCharDisplay = "{" + (int)expectedChar + "}";
}
Console.WriteLine("{0}:\t{1} ({2})\t{3} ({4})", i, expectedCharDisplay, (int)expectedChar,
expectedCharText, (int)originalChar);
}
int snippetLength = 40;
string sourceSnippet = result.Substring(unequalPos, Math.Min(snippetLength, expected.Length - unequalPos));
string expectedSnippet = expected.Substring(unequalPos, Math.Min(snippetLength, expected.Length - unequalPos));
Assert.AreEqual(expectedSnippet, sourceSnippet, "Strings are not equal starting at character {0}.", unequalPos);
}
}
public static Entry CreateEntryInstanceForSyndication(string author, string title, string body)
{
return CreateEntryInstanceForSyndication(Config.CurrentBlog, author, title, body);
}
public static Entry CreateEntryInstanceForSyndication(Blog blog, string author, string title, string body)
{
return CreateEntryInstanceForSyndication(blog, author, title, body, null, DateTime.UtcNow, DateTime.UtcNow);
}
public static Entry CreateEntryInstanceForSyndication(string author, string title, string body, string entryName,
DateTime dateCreatedUtc)
{
return CreateEntryInstanceForSyndication(Config.CurrentBlog, author, title, body, entryName, dateCreatedUtc);
}
public static Entry CreateEntryInstanceForSyndication(string author, string title, string body, string entryName,
DateTime dateCreatedUtc, DateTime datePublishedUtc)
{
return CreateEntryInstanceForSyndication(Config.CurrentBlog, author, title, body, entryName, dateCreatedUtc, datePublishedUtc);
}
public static Entry CreateEntryInstanceForSyndication(Blog blog, string author, string title, string body,
string entryName, DateTime dateCreatedUtc)
{
return CreateEntryInstanceForSyndication(blog, author, title, body, entryName, dateCreatedUtc, NullValue.NullDateTime);
}
public static Entry CreateEntryInstanceForSyndication(Blog blog, string author, string title, string body,
string entryName, DateTime dateCreatedUtc, DateTime datePublishedUtc)
{
var entry = new Entry(PostType.BlogPost);
if (entryName != null)
{
entry.EntryName = entryName;
}
entry.BlogId = blog.Id;
if (dateCreatedUtc != NullValue.NullDateTime)
{
if (dateCreatedUtc.Kind != DateTimeKind.Utc)
{
throw new InvalidOperationException("DateCreated must be UTC");
}
if (!datePublishedUtc.IsNull() && datePublishedUtc.Kind != DateTimeKind.Utc)
{
throw new InvalidOperationException("DatePublished must be UTC");
}
entry.DateCreatedUtc = dateCreatedUtc;
entry.DateModifiedUtc = entry.DateCreatedUtc;
entry.DatePublishedUtc = datePublishedUtc;
}
entry.Title = title;
entry.Author = author;
entry.Body = body;
entry.DisplayOnHomePage = true;
entry.IsAggregated = true;
entry.IsActive = true;
entry.AllowComments = true;
entry.IncludeInMainSyndication = true;
return entry;
}
public static Entry CreateAndSaveEntryForSyndication(string author, string title, string body, string entryName, DateTime dateCreatedUtc, DateTime datePublishedUtc)
{
var entry = UnitTestHelper.CreateEntryInstanceForSyndication(author, title, body, entryName, dateCreatedUtc, datePublishedUtc);
UnitTestHelper.Create(entry);
return entry;
}
public static Link CreateLinkInDb(ObjectRepository repository, int categoryId, string title, int? entryId, string rel)
{
var link = new Link
{
BlogId = Config.CurrentBlog.Id,
IsActive = true,
CategoryId = categoryId,
Title = title,
Url = "http://noneofyourbusiness.com/",
Relation = rel
};
if (entryId != null)
{
link.PostId = (int)entryId;
}
link.Id = repository.CreateLink(link);
return link;
}
/// <summary>
/// Creates a blog post link category.
/// </summary>
/// <param name="blogId"></param>
/// <param name="title"></param>
/// <returns></returns>
public static int CreateCategory(int blogId, string title)
{
var category = new LinkCategory
{
BlogId = Config.CurrentBlog.Id,
Title = title,
CategoryType = CategoryType.PostCollection,
IsActive = true
};
return new DatabaseObjectProvider().CreateLinkCategory(category);
}
/// <summary>
/// Creates a blog post link category.
/// </summary>
/// <param name="blogId">The blog id.</param>
/// <param name="title">The title.</param>
/// <param name="categoryType">Type of the category.</param>
/// <returns></returns>
public static int CreateCategory(int blogId, string title, CategoryType categoryType)
{
var category = new LinkCategory
{
BlogId = Config.CurrentBlog.Id,
Title = title,
CategoryType = categoryType,
IsActive = true
};
return new DatabaseObjectProvider().CreateLinkCategory(category);
}
/// <summary>
/// Useful for unit testing that classes implement serialization. This simply takes in a class,
/// serializes it into a byte array, deserializes the byte array, and returns the result.
/// The unit test should check that all the properties are set correctly.
/// </summary>
/// <param name="serializableObject">The serializable object.</param>
/// <returns></returns>
public static T SerializeRoundTrip<T>(T serializableObject)
{
var stream = new MemoryStream();
var formatter = new BinaryFormatter();
formatter.Serialize(stream, serializableObject);
byte[] serialized = stream.ToArray();
stream = new MemoryStream(serialized) { Position = 0 };
formatter = new BinaryFormatter();
object o = formatter.Deserialize(stream);
return (T)o;
}
public static Blog CreateBlogAndSetupContext(string hostName = null, string subfolder = "")
{
hostName = hostName ?? GenerateUniqueString();
var repository = new DatabaseObjectProvider();
repository.CreateBlog("Just A Test Blog", "test", "test", hostName, subfolder /* subfolder */);
Blog blog = repository.GetBlog(hostName, subfolder);
SetHttpContextWithBlogRequest(hostName, subfolder);
BlogRequest.Current.Blog = blog;
Assert.IsNotNull(Config.CurrentBlog, "Current Blog is null.");
// NOTE- is this OK?
return Config.CurrentBlog;
}
public static BlogAlias CreateBlogAlias(Blog info, string host, string subfolder)
{
return CreateBlogAlias(info, host, subfolder, true);
}
public static BlogAlias CreateBlogAlias(Blog info, string host, string subfolder, bool active)
{
var alias = new BlogAlias { BlogId = info.Id, Host = host, Subfolder = subfolder, IsActive = active };
var repository = new DatabaseObjectProvider();
repository.AddBlogAlias(alias);
return alias;
}
public static MetaTag BuildMetaTag(string content, string name, string httpEquiv, int blogId, int? entryId,
DateTime created)
{
if (created.Kind != DateTimeKind.Utc)
{
throw new ArgumentException("The create date must me UTC", "created");
}
var mt = new MetaTag { Name = name, HttpEquiv = httpEquiv, Content = content, BlogId = blogId };
if (entryId.HasValue)
{
mt.EntryId = entryId.Value;
}
mt.DateCreatedUtc = created;
return mt;
}
public static ICollection<MetaTag> BuildMetaTagsFor(Blog blog, Entry entry, int numberOfTags)
{
var tags = new List<MetaTag>(numberOfTags);
int? entryId = null;
if (entry != null)
{
entryId = entry.Id;
}
for (int i = 0; i < numberOfTags; i++)
{
MetaTag aTag = BuildMetaTag(
GenerateUniqueString().Left(50),
// if even, make a name attribute, else http-equiv
(i % 2 == 0) ? GenerateUniqueString().Left(25) : null,
(i % 2 == 1) ? GenerateUniqueString().Left(25) : null,
blog.Id,
entryId,
DateTime.UtcNow);
tags.Add(aTag);
}
return tags;
}
public static Enclosure BuildEnclosure(string title, string url, string mimetype, int entryId, long size, bool addToFeed, bool showWithPost)
{
var enc = new Enclosure
{
EntryId = entryId,
Title = title,
Url = url,
Size = size,
MimeType = mimetype,
ShowWithPost = showWithPost,
AddToFeed = addToFeed
};
return enc;
}
public static void AssertSimpleProperties(object o, params string[] excludedProperties)
{
var excludes = new StringDictionary();
foreach (string exclude in excludedProperties)
{
excludes.Add(exclude, "");
}
Type t = o.GetType();
PropertyInfo[] props = t.GetProperties();
foreach (PropertyInfo property in props)
{
if (excludes.ContainsKey(property.Name))
{
continue;
}
if (property.CanRead && property.CanWrite)
{
object valueToSet;
if (property.PropertyType == typeof(int)
|| property.PropertyType == typeof(short)
|| property.PropertyType == typeof(decimal)
|| property.PropertyType == typeof(double)
|| property.PropertyType == typeof(long))
{
valueToSet = 42;
}
else if (property.PropertyType == typeof(string))
{
valueToSet = "This Is a String";
}
else if (property.PropertyType == typeof(DateTime))
{
valueToSet = DateTime.UtcNow;
}
else if (property.PropertyType == typeof(Uri))
{
valueToSet = new Uri("http://subtextproject.com/");
}
else if (property.PropertyType == typeof(IPAddress))
{
valueToSet = IPAddress.Parse("127.0.0.1");
}
else if (property.PropertyType == typeof(bool))
{
valueToSet = true;
}
else if (property.PropertyType == typeof(PageType))
{
valueToSet = PageType.HomePage;
}
else if (property.PropertyType == typeof(ICollection<Link>))
{
valueToSet = new List<Link>();
}
else if (property.PropertyType == typeof(ICollection<Image>))
{
valueToSet = new List<Image>();
}
else
{
//Don't know what to do.
continue;
}
property.SetValue(o, valueToSet, null);
object retrievedValue = property.GetValue(o, null);
Assert.AreEqual(valueToSet, retrievedValue,
string.Format(CultureInfo.InvariantCulture,
"Could not set and get this property '{0}'", property.Name));
}
}
}
public static IPrincipal MockPrincipalWithRoles(params string[] roles)
{
var principal = new Mock<IPrincipal>();
principal.Setup(p => p.Identity.IsAuthenticated).Returns(true);
principal.Setup(p => p.Identity.Name).Returns("Username");
Array.ForEach(roles, role => principal.Setup(p => p.IsInRole(role)).Returns(true));
return principal.Object;
}
public static void AssertEnclosures(Enclosure expected, Enclosure result)
{
Assert.AreEqual(expected.Title, result.Title, "Wrong title.");
Assert.AreEqual(expected.Url, result.Url, "Wrong Url.");
Assert.AreEqual(expected.MimeType, result.MimeType, "Wrong mimetype.");
Assert.AreEqual(expected.Size, result.Size, "Wrong size.");
Assert.AreEqual(expected.AddToFeed, result.AddToFeed, "Wrong AddToFeed flag.");
Assert.AreEqual(expected.ShowWithPost, result.ShowWithPost, "Wrong ShowWithPost flag.");
}
/// <summary>
/// Takes all the necessary steps to create a blog and set up the HTTP Context
/// with the blog.
/// </summary>
/// <returns>
/// Returns a reference to a string builder.
/// The stringbuilder will end up containing the Response of any simulated
/// requests.
/// </returns>
internal static SimulatedRequestContext SetupBlog()
{
return SetupBlog(string.Empty);
}
/// <summary>
/// Takes all the necessary steps to create a blog and set up the HTTP Context
/// with the blog.
/// </summary>
/// <returns>
/// Returns a reference to a string builder.
/// The stringbuilder will end up containing the Response of any simulated
/// requests.
/// </returns>
/// <param name="subfolder">The 'virtualized' subfolder the blog lives in.</param>
internal static SimulatedRequestContext SetupBlog(string subfolder)
{
return SetupBlog(subfolder, string.Empty);
}
/// <summary>
/// Takes all the necessary steps to create a blog and set up the HTTP Context
/// with the blog.
/// </summary>
/// <returns>
/// Returns a reference to a string builder.
/// The stringbuilder will end up containing the Response of any simulated
/// requests.
/// </returns>
/// <param name="subfolder">The 'virtualized' subfolder the blog lives in.</param>
/// <param name="applicationPath">The name of the IIS virtual directory the blog lives in.</param>
internal static SimulatedRequestContext SetupBlog(string subfolder, string applicationPath)
{
return SetupBlog(subfolder, applicationPath, 80);
}
/// <summary>
/// Takes all the necessary steps to create a blog and set up the HTTP Context
/// with the blog.
/// </summary>
/// <returns>
/// Returns a reference to a string builder.
/// The stringbuilder will end up containing the Response of any simulated
/// requests.
/// </returns>
/// <param name="subfolder">The 'virtualized' subfolder the blog lives in.</param>
/// <param name="applicationPath">The name of the IIS virtual directory the blog lives in.</param>
/// <param name="port">The port for this blog.</param>
internal static SimulatedRequestContext SetupBlog(string subfolder, string applicationPath, int port)
{
return SetupBlog(subfolder, applicationPath, port, string.Empty);
}
/// <summary>
/// Takes all the necessary steps to create a blog and set up the HTTP Context
/// with the blog.
/// </summary>
/// <param name="subfolder">The 'virtualized' subfolder the blog lives in.</param>
/// <param name="applicationPath">The name of the IIS virtual directory the blog lives in.</param>
/// <param name="page">The page to request.</param>
/// <returns>
/// Returns a reference to a string builder.
/// The stringbuilder will end up containing the Response of any simulated
/// requests.
/// </returns>
internal static SimulatedRequestContext SetupBlog(string subfolder, string applicationPath, string page)
{
return SetupBlog(subfolder, applicationPath, 80, page);
}
/// <summary>
/// Takes all the necessary steps to create a blog and set up the HTTP Context
/// with the blog.
/// </summary>
/// <param name="subfolder">The 'virtualized' subfolder the blog lives in.</param>
/// <param name="applicationPath">The name of the IIS virtual directory the blog lives in.</param>
/// <param name="port">The port for this blog.</param>
/// <param name="page">The page to request.</param>
/// <returns>
/// Returns a reference to a string builder.
/// The stringbuilder will end up containing the Response of any simulated
/// requests.
/// </returns>
internal static SimulatedRequestContext SetupBlog(string subfolder, string applicationPath, int port,
string page)
{
return SetupBlog(subfolder, applicationPath, port, page, "username", "password");
}
/// <summary>
/// Takes all the necessary steps to create a blog and set up the HTTP Context
/// with the blog.
/// </summary>
/// <param name="subfolder">The 'virtualized' subfolder the blog lives in.</param>
/// <param name="applicationPath">The name of the IIS virtual directory the blog lives in.</param>
/// <param name="port">The port for this blog.</param>
/// <param name="page">The page to request.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="password">The password.</param>
/// <returns>
/// Returns a reference to a string builder.
/// The stringbuilder will end up containing the Response of any simulated
/// requests.
/// </returns>
internal static SimulatedRequestContext SetupBlog(string subfolder, string applicationPath, int port,
string page, string userName, string password)
{
var repository = new DatabaseObjectProvider();
string host = GenerateUniqueString();
HttpContext.Current = null;
//I wish this returned the blog it created.
repository.CreateBlog("Unit Test Blog", userName, password, host, subfolder);
Blog blog = repository.GetBlog(host, subfolder);
var sb = new StringBuilder();
TextWriter output = new StringWriter(sb);
SimulatedHttpRequest request = SetHttpContextWithBlogRequest(host, port, subfolder, applicationPath, page,
output, "GET");
BlogRequest.Current.Blog = blog;
if (Config.CurrentBlog != null)
{
Config.CurrentBlog.AutoFriendlyUrlEnabled = true;
}
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(userName), new[] { "Administrators" });
return new SimulatedRequestContext(request, sb, output, host);
}
public static int Create(Entry entry)
{
var requestContext = new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData());
var serviceLocator = new Mock<IDependencyResolver>().Object;
var searchEngineService = new Mock<IIndexingService>().Object;
DependencyResolver.SetResolver(serviceLocator);
var routes = new RouteCollection();
var subtextRoutes = new SubtextRouteMapper(routes, serviceLocator);
Routes.RegisterRoutes(subtextRoutes);
var urlHelper = new BlogUrlHelper(requestContext, routes);
var subtextContext = new SubtextContext(Config.CurrentBlog, requestContext, urlHelper,
new DatabaseObjectProvider(), requestContext.HttpContext.User,
new SubtextCache(requestContext.HttpContext.Cache), serviceLocator);
IEntryPublisher entryPublisher = CreateEntryPublisher(subtextContext, searchEngineService);
int id = entryPublisher.Publish(entry);
entry.Id = id;
return id;
}
public static IEntryPublisher CreateEntryPublisher(ISubtextContext subtextContext, IIndexingService searchEngineService)
{
var slugGenerator = new SlugGenerator(FriendlyUrlSettings.Settings, subtextContext.Repository);
var transformations = new CompositeTextTransformation
{
new XhtmlConverter(),
new EmoticonsTransformation(subtextContext)
};
return new EntryPublisher(subtextContext, transformations, slugGenerator, searchEngineService);
}
public static Stream ToStream(this string text)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(text);
writer.Flush();
stream.Position = 0;
return stream;
}
public static IKernel MockKernel(Func<IEnumerable<object>> returnFunc)
{
var request = new Mock<IRequest>();
var kernel = new Mock<IKernel>();
kernel.Setup(
k =>
k.CreateRequest(It.IsAny<Type>(), It.IsAny<Func<IBindingMetadata, bool>>(),
It.IsAny<IEnumerable<IParameter>>(), It.IsAny<bool>(), It.IsAny<bool>())).Returns(request.Object);
kernel.Setup(k => k.Resolve(It.IsAny<IRequest>())).Returns(returnFunc);
return kernel.Object;
}
public static BlogUrlHelper SetupUrlHelper(string appPath)
{
return SetupUrlHelper(appPath, new RouteData());
}
public static BlogUrlHelper SetupUrlHelper(string appPath, RouteData routeData)
{
var routes = new RouteCollection();
var subtextRoutes = new SubtextRouteMapper(routes, new Mock<IDependencyResolver>().Object);
Routes.RegisterRoutes(subtextRoutes);
var httpContext = new Mock<HttpContextBase>();
httpContext.Setup(c => c.Request.ApplicationPath).Returns(appPath);
httpContext.Setup(c => c.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(s => s);
var requestContext = new RequestContext(httpContext.Object, routeData);
var helper = new BlogUrlHelper(requestContext, routes);
return helper;
}
/// <summary>
/// Updates the specified entry in the data provider.
/// </summary>
/// <param name="entry">Entry.</param>
/// <param name="context"></param>
/// <returns></returns>
public static void Update(Entry entry, ISubtextContext context)
{
if (entry == null)
{
throw new ArgumentNullException("entry");
}
ObjectRepository repository = new DatabaseObjectProvider();
var transform = new CompositeTextTransformation
{
new XhtmlConverter(),
new EmoticonsTransformation(context),
new KeywordExpander(repository)
};
var searchEngineService = new Mock<IIndexingService>().Object;
var publisher = new EntryPublisher(context, transform, new SlugGenerator(FriendlyUrlSettings.Settings), searchEngineService);
publisher.Publish(entry);
}
public static Entry GetEntry(int entryId, PostConfig postConfig, bool includeCategories)
{
bool isActive = ((postConfig & PostConfig.IsActive) == PostConfig.IsActive);
return new DatabaseObjectProvider().GetEntry(entryId, isActive, includeCategories);
}
public static ArgumentNullException AssertThrowsArgumentNullException(this Action action)
{
return action.AssertThrows<ArgumentNullException>();
}
public static TException AssertThrows<TException>(this Action action) where TException : Exception
{
try
{
action();
}
catch (TException exception)
{
return exception;
}
return null;
}
/// <summary>
/// Makes sure we can read app settings
/// </summary>
public static void AssertAppSettings()
{
Assert.AreEqual("UnitTestValue", ConfigurationManager.AppSettings["UnitTestKey"], "Cannot read app settings");
}
public static void WriteTableToOutput(string tableName)
{
string sql = String.Format("SELECT * FROM {0}", tableName);
Console.WriteLine("Table: " + tableName);
using (var dataset = SqlHelper.ExecuteDataset(Config.ConnectionString, CommandType.Text, sql))
{
foreach (DataColumn column in dataset.Tables[0].Columns)
{
Console.Write(column.ColumnName + "\t");
}
Console.WriteLine();
foreach (DataRow row in dataset.Tables[0].Rows)
{
foreach (DataColumn column in dataset.Tables[0].Columns)
{
Console.Write(row[column] + "\t");
}
Console.WriteLine();
}
}
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using AopAlliance.Intercept;
using Common.Logging;
using Spring.Util;
namespace Spring.Aspects.Exceptions
{
/// <summary>
/// Exception advice to perform exception translation, conversion of exceptions to default return values, and
/// exception swallowing. Configuration is via a DSL like string for ease of use in common cases as well as
/// allowing for custom translation logic by leveraging the Spring expression language.
/// </summary>
/// <remarks>
/// <para>
/// The exception handler collection can be filled with either instances of objects that implement the interface
/// <see cref="IExceptionHandler"/> or a string that follows a simple syntax for most common exception management
/// needs. The source exceptions to perform processing on are listed immediately after the keyword 'on' and can
/// be comma delmited. Following that is the action to perform, either log, translate, wrap, replace, return, or
/// swallow. Following the action is a Spring expression language (SpEL) fragment that is used to either create the
/// translated/wrapped/replaced exception or specify an alternative return value. The variables available to be
/// used in the expression language fragment are, #method, #args, #target, and #e which are 1) the method that
/// threw the exception, the arguments to the method, the target object itself, and the exception that was thrown.
/// Using SpEL gives you great flexibility in creating a translation of an exception that has access to the calling context.
/// </para>
/// <para>Common translation cases, wrap and rethrow, are supported with a shorter syntax where you can specify only
/// the exception text for the new translated exception. If you ommit the exception text a default value will be
/// used.</para>
/// <para>The exceptionsHandlers are compared to the thrown exception in the order they are listed. logging
/// an exception will continue the evaluation process, in all other cases exceution stops at that point and the
/// appropriate exceptions handler is executed.</para>
/// <code escaped="true">
/// <property name="exceptionHandlers">
/// <list>
/// <value>on FooException1 log 'My Message, Method Name ' + #method.Name</value>
/// <value>on FooException1 translate new BarException('My Message, Method Called = ' + #method.Name", #e)</value>
/// <value>on FooException2,Foo3Exception wrap BarException 'My Bar Message'</value>
/// <value>on FooException4 replace BarException 'My Bar Message'</value>
/// <value>on FooException5 return 32</value>
/// <value>on FooException6 swallow</value>
/// <ref object="exceptionExpression"/>
/// </list>
/// </property>
/// </code>
///
/// </remarks>
/// <author>Mark Pollack</author>
[Serializable]
public class ExceptionHandlerAdvice : AbstractExceptionHandlerAdvice
{
#region Fields
/// <summary>
/// Log instance available to subclasses
/// </summary>
protected static ILog log = LogManager.GetLogger(typeof(ExceptionHandlerAdvice));
private IList exceptionHandlers = new ArrayList();
/// <summary>
/// Holds shared handler definition templates
/// </summary>
private ExceptionHandlerTable exceptionHandlerTable = new ExceptionHandlerTable();
private string onExceptionNameRegex = @"^(on\s+exception\s+name)\s+(.*?)\s+(log|translate|wrap|replace|return|swallow|execute)\s*(.*?)$";
private string onExceptionRegex = @"^(on\s+exception\s+)(\(.*?\))\s+(log|translate|wrap|replace|return|swallow|execute)\s*(.*?)$";
#endregion
#region Properties
/// <summary>
/// Gets or sets the Regex string used to parse advice expressions starting with 'on exception name' and exception handling actions.
/// </summary>
/// <value>The regex string to parse advice expressions starting with 'on exception name' and exception handling actions.</value>
public override string OnExceptionNameRegex
{
get { return onExceptionNameRegex; }
set { onExceptionNameRegex = value; }
}
/// <summary>
/// Gets or sets the Regex string used to parse advice expressions starting with 'on exception (constraint)' and exception handling actions.
/// </summary>
/// <value>The regex string to parse advice expressions starting with 'on exception (constraint)' and exception handling actions.</value>
public override string OnExceptionRegex
{
get { return onExceptionRegex; }
set { onExceptionRegex = value; }
}
/// <summary>
/// Gets or sets the exception handler.
/// </summary>
/// <value>The exception handler.</value>
public IList ExceptionHandlers
{
get { return exceptionHandlers; }
set { exceptionHandlers = value; }
}
/// <summary>
/// Gets the exception handler dictionary. Allows for registration of a specific handler where the key
/// is the action type. This makes configuration of a custom exception handler easier, for example
/// LogExceptionHandler, in that only 'user friendly' properties such as LogName, etc., need to be configured
/// and not 'user unfriendly' properties such as ConstraintExpressionText and ActionExpressionText.
/// </summary>
/// <value>The exception handler dictionary.</value>
public ExceptionHandlerTable ExceptionHandlerDictionary
{
get { return exceptionHandlerTable; }
}
#endregion
#region IMethodInterceptor implementation
/// <summary>
/// Implement this method to perform extra treatments before and after
/// the call to the supplied <paramref name="invocation"/>.
/// </summary>
/// <remarks>
/// <p>
/// Polite implementations would certainly like to invoke
/// <see cref="AopAlliance.Intercept.IJoinpoint.Proceed"/>.
/// </p>
/// </remarks>
/// <param name="invocation">
/// The method invocation that is being intercepted.
/// </param>
/// <returns>
/// The result of the call to the
/// <see cref="AopAlliance.Intercept.IJoinpoint.Proceed"/> method of
/// the supplied <paramref name="invocation"/>; this return value may
/// well have been intercepted by the interceptor.
/// </returns>
/// <exception cref="System.Exception">
/// If any of the interceptors in the chain or the target object itself
/// throws an exception.
/// </exception>
public override object Invoke(IMethodInvocation invocation)
{
try
{
return invocation.Proceed();
}
catch (TargetInvocationException ex)
{
Exception realException = ex.InnerException;
InvokeHandlers(realException, invocation);
throw realException;
}
catch (Exception ex)
{
object returnVal = InvokeHandlers(ex, invocation);
if (returnVal == null)
{
return null;
}
// if only logged
if (returnVal.Equals("logged"))
{
throw;
}
//only here if we only are swallowing, returning alternative value, no matching handler was found.
// no matching handler.
if (returnVal.Equals("nomatch"))
{
throw;
}
else
{
//TODO make spring specific value.
if (!returnVal.Equals("swallow"))
{
return returnVal;
}
else
{
Type returnType = invocation.Method.ReturnType;
return returnType.IsValueType && !returnType.Equals(typeof(void))? Activator.CreateInstance(returnType) : null;
}
}
}
}
#endregion
#region IInitializingObject implementation
/// <summary>
/// Invoked by an <see cref="Spring.Objects.Factory.IObjectFactory"/>
/// after it has injected all of an object's dependencies.
/// </summary>
/// <remarks>
/// <p>
/// This method allows the object instance to perform the kind of
/// initialization only possible when all of it's dependencies have
/// been injected (set), and to throw an appropriate exception in the
/// event of misconfiguration.
/// </p>
/// <p>
/// Please do consult the class level documentation for the
/// <see cref="Spring.Objects.Factory.IObjectFactory"/> interface for a
/// description of exactly <i>when</i> this method is invoked. In
/// particular, it is worth noting that the
/// <see cref="Spring.Objects.Factory.IObjectFactoryAware"/>
/// and <see cref="Spring.Context.IApplicationContextAware"/>
/// callbacks will have been invoked <i>prior</i> to this method being
/// called.
/// </p>
/// </remarks>
/// <exception cref="System.Exception">
/// In the event of misconfiguration (such as the failure to set a
/// required property) or if initialization fails.
/// </exception>
public override void AfterPropertiesSet()
{
if (exceptionHandlers.Count == 0)
{
throw new ArgumentException("At least one handler is required");
}
IList newExceptionHandlers = new ArrayList();
foreach (object o in exceptionHandlers)
{
string handlerString = o as string;
if (handlerString != null)
{
IExceptionHandler handler = Parse(handlerString);
if (handler == null)
{
throw new ArgumentException("Was not able to parse exception handler string [" + handlerString +
"]");
}
newExceptionHandlers.Add(handler);
}
//explicitly configured advice, must also configure ConstraintExpressionText and ActionExpressionText!
IExceptionHandler handlerObject = o as IExceptionHandler;
if (handlerObject != null)
{
newExceptionHandlers.Add(handlerObject);
}
}
//TODO sync.
exceptionHandlers = newExceptionHandlers;
}
#endregion
#region Methods
/// <summary>
/// Invokes handlers registered for the passed exception and <see cref="IMethodInvocation"/>
/// </summary>
/// <param name="ex">The exception to be handled</param>
/// <param name="invocation">The <see cref="IMethodInvocation"/> that raised this exception.</param>
/// <returns>The output of <see cref="IExceptionHandler.HandleException"/> </returns>
protected virtual object InvokeHandlers(Exception ex, IMethodInvocation invocation)
{
Dictionary<string, object> callContextDictionary = new Dictionary<string, object>();
callContextDictionary.Add("method", invocation.Method);
callContextDictionary.Add("args", invocation.Arguments);
callContextDictionary.Add("target", invocation.Target);
callContextDictionary.Add("e", ex);
object retValue = "nomatch";
foreach (IExceptionHandler handler in exceptionHandlers)
{
if (handler != null)
{
if (handler.CanHandleException(ex, callContextDictionary))
{
retValue = handler.HandleException(callContextDictionary);
if (!handler.ContinueProcessing)
{
return retValue;
}
}
}
}
return retValue;
}
/// <summary>
/// Parses the specified handler string, creating an instance of IExceptionHander.
/// </summary>
/// <param name="handlerString">The handler string.</param>
/// <returns>an instance of an exception handler or null if was not able to correctly parse
/// handler string.</returns>
protected virtual IExceptionHandler Parse(string handlerString)
{
ParsedAdviceExpression parsedAdviceExpression = ParseAdviceExpression(handlerString);
if (!parsedAdviceExpression.Success)
{
log.Warn("Could not parse exception hander statement " + handlerString);
return null;
}
return CreateExceptionHandler(parsedAdviceExpression);
}
/// <summary>
/// Creates the exception handler.
/// </summary>
/// <param name="parsedAdviceExpression">The parsed advice expression.</param>
/// <returns>The exception handler instance</returns>
protected virtual IExceptionHandler CreateExceptionHandler(ParsedAdviceExpression parsedAdviceExpression)
{
if (parsedAdviceExpression.ActionText.IndexOf("log") >= 0)
{
IExceptionHandler handler;
if (exceptionHandlerTable.ContainsKey("log"))
{
handler = exceptionHandlerTable["log"];
AddExceptionNames(parsedAdviceExpression, handler);
} else
{
handler = CreateLogExceptionHandler(parsedAdviceExpression.ExceptionNames);
}
handler.ConstraintExpressionText = parsedAdviceExpression.ConstraintExpression;
handler.ActionExpressionText = parsedAdviceExpression.ActionExpressionText;
return handler;
}
else if (parsedAdviceExpression.ActionText.IndexOf("translate") >= 0)
{
IExceptionHandler handler;
if (exceptionHandlerTable.Contains("translate"))
{
handler = exceptionHandlerTable["translate"];
AddExceptionNames(parsedAdviceExpression, handler);
}
else
{
handler = CreateTranslationExceptionHandler(parsedAdviceExpression.ExceptionNames);
}
handler.ConstraintExpressionText = parsedAdviceExpression.ConstraintExpression;
handler.ActionExpressionText = parsedAdviceExpression.ActionExpressionText;
return handler;
}
else if (parsedAdviceExpression.ActionText.IndexOf("wrap") >= 0)
{
IExceptionHandler handler;
if (exceptionHandlerTable.Contains("wrap"))
{
handler = exceptionHandlerTable["wrap"];
AddExceptionNames(parsedAdviceExpression, handler);
}
else
{
handler = CreateTranslationExceptionHandler(parsedAdviceExpression.ExceptionNames);
}
handler.ConstraintExpressionText = parsedAdviceExpression.ConstraintExpression;
handler.ActionExpressionText = ParseWrappedExceptionExpression("wrap", parsedAdviceExpression.AdviceExpression);
return handler;
}
else if (parsedAdviceExpression.ActionText.IndexOf("replace") >= 0)
{
IExceptionHandler handler;
if (exceptionHandlerTable.Contains("replace"))
{
handler = exceptionHandlerTable["replace"];
AddExceptionNames(parsedAdviceExpression, handler);
} else
{
handler = CreateTranslationExceptionHandler(parsedAdviceExpression.ExceptionNames);
}
handler.ConstraintExpressionText = parsedAdviceExpression.ConstraintExpression;
handler.ActionExpressionText = ParseWrappedExceptionExpression("replace", parsedAdviceExpression.AdviceExpression);
return handler;
}
else if (parsedAdviceExpression.ActionText.IndexOf("swallow") >= 0)
{
IExceptionHandler handler;
if (exceptionHandlerTable.Contains("swallow"))
{
handler = exceptionHandlerTable["swallow"];
AddExceptionNames(parsedAdviceExpression, handler);
}
else
{
handler = CreateSwallowExceptionHander(parsedAdviceExpression);
}
handler.ConstraintExpressionText = parsedAdviceExpression.ConstraintExpression;
return handler;
}
else if (parsedAdviceExpression.ActionText.IndexOf("return") >= 0)
{
IExceptionHandler handler;
if (exceptionHandlerTable.Contains("return"))
{
handler = exceptionHandlerTable["return"];
AddExceptionNames(parsedAdviceExpression, handler);
}
else
{
handler = CreateReturnValueExceptionHandler(parsedAdviceExpression);
}
handler.ConstraintExpressionText = parsedAdviceExpression.ConstraintExpression;
handler.ActionExpressionText = parsedAdviceExpression.ActionExpressionText;
return handler;
}
else if (parsedAdviceExpression.ActionText.IndexOf("execute") >= 0)
{
IExceptionHandler handler;
if (exceptionHandlerTable.Contains("execute"))
{
handler = exceptionHandlerTable["execute"];
AddExceptionNames(parsedAdviceExpression, handler);
}
else
{
handler = CreateExecuteSpelExceptionHandler(parsedAdviceExpression);
}
handler.ConstraintExpressionText = parsedAdviceExpression.ConstraintExpression;
handler.ActionExpressionText = parsedAdviceExpression.ActionExpressionText;
return handler;
}
else
{
log.Warn("Could not parse exception hander statement " + parsedAdviceExpression.AdviceExpression);
}
return null;
}
/// <summary>
/// Creates the execute spel exception handler.
/// </summary>
/// <param name="parsedAdviceExpression">The parsed advice expression.</param>
/// <returns></returns>
protected virtual IExceptionHandler CreateExecuteSpelExceptionHandler(ParsedAdviceExpression parsedAdviceExpression)
{
IExceptionHandler handler;
handler = new ExecuteSpelExceptionHandler(parsedAdviceExpression.ExceptionNames);
return handler;
}
/// <summary>
/// Creates the return value exception handler.
/// </summary>
/// <param name="parsedAdviceExpression">The parsed advice expression.</param>
/// <returns></returns>
protected virtual IExceptionHandler CreateReturnValueExceptionHandler(ParsedAdviceExpression parsedAdviceExpression)
{
IExceptionHandler handler;
handler = new ReturnValueExceptionHandler(parsedAdviceExpression.ExceptionNames);
return handler;
}
/// <summary>
/// Creates the swallow exception hander.
/// </summary>
/// <param name="parsedAdviceExpression">The parsed advice expression.</param>
/// <returns></returns>
protected virtual IExceptionHandler CreateSwallowExceptionHander(ParsedAdviceExpression parsedAdviceExpression)
{
IExceptionHandler handler;
handler = new SwallowExceptionHandler(parsedAdviceExpression.ExceptionNames);
return handler;
}
/// <summary>
/// Creates the translation exception handler.
/// </summary>
/// <param name="exceptionNames">The exception names.</param>
/// <returns></returns>
protected virtual IExceptionHandler CreateTranslationExceptionHandler(string[] exceptionNames)
{
return new TranslationExceptionHandler(exceptionNames);
}
/// <summary>
/// Creates the log exception handler.
/// </summary>
/// <param name="exceptionNames">The exception names.</param>
/// <returns>Log exception</returns>
protected virtual LogExceptionHandler CreateLogExceptionHandler(string[] exceptionNames)
{
return new LogExceptionHandler(exceptionNames);
}
/// <summary>
/// Parses the wrapped exception expression.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="handlerString">The handler string.</param>
/// <returns></returns>
protected string ParseWrappedExceptionExpression(string action, string handlerString)
{
int endOfActionIndex = handlerString.IndexOf(action) + action.Length;
string exceptionAndMessage = handlerString.Substring(endOfActionIndex).Trim();
int endOfExceptionTypeIndex = exceptionAndMessage.IndexOf(" ");
string rawExpressionTextPart;
string exception;
//Has two pieces.
if (endOfExceptionTypeIndex > 0)
{
exception = exceptionAndMessage.Substring(0, endOfExceptionTypeIndex).Trim();
rawExpressionTextPart = exceptionAndMessage.Substring(endOfExceptionTypeIndex).Trim();
}
else
{
exception = exceptionAndMessage;
if (action.Equals("wrap"))
{
rawExpressionTextPart = "'Wrapped ' + #e.GetType().Name";
} else
{
rawExpressionTextPart = "'Replaced ' + #e.GetType().Name";
}
}
if (action.Equals("wrap"))
{
return string.Format("new {0}({1}, #e)", exception, rawExpressionTextPart);
} else
{
return string.Format("new {0}({1})", exception, rawExpressionTextPart);
}
}
private void AddExceptionNames(ParsedAdviceExpression parsedAdviceExpression, IExceptionHandler handler)
{
foreach (string exceptionName in parsedAdviceExpression.ExceptionNames)
{
handler.SourceExceptionNames.Add(exceptionName);
}
}
#endregion
#region ExceptionHandlerTable class
/// <summary>
/// A specialized dictionary for key value pairs of (string, IExceptionHandler)
/// </summary>
public class ExceptionHandlerTable : Hashtable
{
/// <summary>
/// Adds the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public void Add(string key, IExceptionHandler value)
{
lock (SyncRoot)
{
base[key] = value;
}
}
/// <summary>
/// Gets the <see cref="Spring.Aspects.IExceptionHandler"/> with the specified key.
/// </summary>
/// <value></value>
public IExceptionHandler this[string key]
{
get
{
lock (SyncRoot)
{
return (IExceptionHandler)base[key];
}
}
}
/// <summary>
/// Adds an element with the specified key and value into the <see cref="T:System.Collections.Hashtable"/>.
/// </summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="value">The value of the element to add. The value can be null.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null. </exception>
/// <exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.Hashtable"/>.
/// or key is not a string or value is not an IExceptionHandler.</exception>
/// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Hashtable"/> is read-only.-or- The <see cref="T:System.Collections.Hashtable"/> has a fixed size. </exception>
public override void Add(object key, object value)
{
AssertUtils.AssertArgumentType(key, "key", typeof(string), "Key must be a string");
AssertUtils.AssertArgumentType(value, "value", typeof(IExceptionHandler), "Key must be a IExceptionHandler");
this.Add((string)key, (IExceptionHandler)value);
}
/// <summary>
/// Gets the <see cref="System.Object"/> with the specified key.
/// </summary>
/// <value></value>
public override object this[object key]
{
get
{
return this[(string)key];
}
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Semantics;
namespace Microsoft.NetCore.Analyzers.Runtime
{
/// <summary>
/// CA1816: Dispose methods should call SuppressFinalize
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class CallGCSuppressFinalizeCorrectlyAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA1816";
private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.CallGCSuppressFinalizeCorrectlyTitle), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableMessageNotCalledWithFinalizer = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.CallGCSuppressFinalizeCorrectlyMessageNotCalledWithFinalizer), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableMessageNotCalled = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.CallGCSuppressFinalizeCorrectlyMessageNotCalled), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableMessageNotPassedThis = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.CallGCSuppressFinalizeCorrectlyMessageNotPassedThis), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableMessageOutsideDispose = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.CallGCSuppressFinalizeCorrectlyMessageOutsideDispose), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(SystemRuntimeAnalyzersResources.CallGCSuppressFinalizeCorrectlyDescription), SystemRuntimeAnalyzersResources.ResourceManager, typeof(SystemRuntimeAnalyzersResources));
internal static DiagnosticDescriptor NotCalledWithFinalizerRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageNotCalledWithFinalizer,
DiagnosticCategory.Usage,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
description: s_localizableDescription,
helpLinkUri: "https://msdn.microsoft.com/en-US/library/ms182269.aspx",
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor NotCalledRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageNotCalled,
DiagnosticCategory.Usage,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
description: s_localizableDescription,
helpLinkUri: "https://msdn.microsoft.com/en-US/library/ms182269.aspx",
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor NotPassedThisRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageNotPassedThis,
DiagnosticCategory.Usage,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
description: s_localizableDescription,
helpLinkUri: "https://msdn.microsoft.com/en-US/library/ms182269.aspx",
customTags: WellKnownDiagnosticTags.Telemetry);
internal static DiagnosticDescriptor OutsideDisposeRule = new DiagnosticDescriptor(RuleId,
s_localizableTitle,
s_localizableMessageOutsideDispose,
DiagnosticCategory.Usage,
DiagnosticHelpers.DefaultDiagnosticSeverity,
isEnabledByDefault: DiagnosticHelpers.EnabledByDefaultIfNotBuildingVSIX,
description: s_localizableDescription,
helpLinkUri: "https://msdn.microsoft.com/en-US/library/ms182269.aspx",
customTags: WellKnownDiagnosticTags.Telemetry);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(NotCalledWithFinalizerRule, NotCalledRule, NotPassedThisRule, OutsideDisposeRule);
public override void Initialize(AnalysisContext analysisContext)
{
// TODO: Make analyzer thread safe.
//analysisContext.EnableConcurrentExecution();
analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
analysisContext.RegisterCompilationStartAction(compilationContext =>
{
var gcSuppressFinalizeMethodSymbol = compilationContext.Compilation
.GetTypeByMetadataName("System.GC")
?.GetMembers("SuppressFinalize")
.OfType<IMethodSymbol>()
.SingleOrDefault();
if (gcSuppressFinalizeMethodSymbol == null)
{
return;
}
compilationContext.RegisterOperationBlockStartActionInternal(operationBlockContext =>
{
if (operationBlockContext.OwningSymbol.Kind != SymbolKind.Method)
{
return;
}
var methodSymbol = (IMethodSymbol)operationBlockContext.OwningSymbol;
if (methodSymbol.IsExtern || methodSymbol.IsAbstract)
{
return;
}
var analyzer = new SuppressFinalizeAnalyzer(methodSymbol, gcSuppressFinalizeMethodSymbol, compilationContext.Compilation);
operationBlockContext.RegisterOperationActionInternal(analyzer.Analyze, OperationKind.InvocationExpression);
operationBlockContext.RegisterOperationBlockEndAction(analyzer.OperationBlockEndAction);
});
});
}
private class SuppressFinalizeAnalyzer
{
private enum SuppressFinalizeUsage
{
CanCall,
MustCall,
MustNotCall
}
private readonly Compilation _compilation;
private readonly IMethodSymbol _containingMethodSymbol;
private readonly IMethodSymbol _gcSuppressFinalizeMethodSymbol;
private readonly SuppressFinalizeUsage _expectedUsage;
private bool _suppressFinalizeCalled;
private SemanticModel _semanticModel;
public SuppressFinalizeAnalyzer(IMethodSymbol methodSymbol, IMethodSymbol gcSuppressFinalizeMethodSymbol, Compilation compilation)
{
this._compilation = compilation;
this._containingMethodSymbol = methodSymbol;
this._gcSuppressFinalizeMethodSymbol = gcSuppressFinalizeMethodSymbol;
this._expectedUsage = GetAllowedSuppressFinalizeUsage(_containingMethodSymbol);
}
public void Analyze(OperationAnalysisContext analysisContext)
{
var invocationExpression = (IInvocationExpression)analysisContext.Operation;
if (invocationExpression.TargetMethod.OriginalDefinition.Equals(_gcSuppressFinalizeMethodSymbol))
{
_suppressFinalizeCalled = true;
if (_semanticModel == null)
{
_semanticModel = analysisContext.Compilation.GetSemanticModel(analysisContext.Operation.Syntax.SyntaxTree);
}
// Check for GC.SuppressFinalize outside of IDisposable.Dispose()
if (_expectedUsage == SuppressFinalizeUsage.MustNotCall)
{
analysisContext.ReportDiagnostic(invocationExpression.Syntax.CreateDiagnostic(
OutsideDisposeRule,
_containingMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
_gcSuppressFinalizeMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
}
// Checks for GC.SuppressFinalize(this)
if (invocationExpression.ArgumentsInEvaluationOrder.Count() != 1)
{
return;
}
var parameterSymbol = _semanticModel.GetSymbolInfo(invocationExpression.ArgumentsInEvaluationOrder.Single().Syntax).Symbol as IParameterSymbol;
if (parameterSymbol == null || !parameterSymbol.IsThis)
{
analysisContext.ReportDiagnostic(invocationExpression.Syntax.CreateDiagnostic(
NotPassedThisRule,
_containingMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
_gcSuppressFinalizeMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
}
}
}
public void OperationBlockEndAction(OperationBlockAnalysisContext context)
{
// Check for absence of GC.SuppressFinalize
if (!_suppressFinalizeCalled && _expectedUsage == SuppressFinalizeUsage.MustCall)
{
var descriptor = _containingMethodSymbol.ContainingType.HasFinalizer() ? NotCalledWithFinalizerRule : NotCalledRule;
context.ReportDiagnostic(_containingMethodSymbol.CreateDiagnostic(
descriptor,
_containingMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat),
_gcSuppressFinalizeMethodSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat)));
}
}
private SuppressFinalizeUsage GetAllowedSuppressFinalizeUsage(IMethodSymbol method)
{
// We allow constructors in sealed types to call GC.SuppressFinalize.
// This allows types that derive from Component (such SqlConnection)
// to prevent the finalizer they inherit from Component from ever
// being called.
if (method.ContainingType.IsSealed && method.IsConstructor() && !method.IsStatic)
{
return SuppressFinalizeUsage.CanCall;
}
if (!method.IsDisposeImplementation(_compilation))
{
return SuppressFinalizeUsage.MustNotCall;
}
// If the Dispose method is declared in a sealed type, we do
// not require that the method calls GC.SuppressFinalize
var hasFinalizer = method.ContainingType.HasFinalizer();
if (method.ContainingType.IsSealed && !hasFinalizer)
{
return SuppressFinalizeUsage.CanCall;
}
// We don't require that non-public types call GC.SuppressFinalize
// if they don't have a finalizer as the owner of the assembly can
// control whether any finalizable types derive from them.
if (method.ContainingType.DeclaredAccessibility != Accessibility.Public && !hasFinalizer)
{
return SuppressFinalizeUsage.CanCall;
}
// Even if the Dispose method is declared on a type without a
// finalizer, we still require it to call GC.SuppressFinalize to
// prevent derived finalizable types from having to reimplement
// IDisposable.Dispose just to call it.
return SuppressFinalizeUsage.MustCall;
}
}
}
}
| |
/*
###
# # ######### _______ _ _ ______ _ _
## ######## @ ## |______ | | | ____ | |
################## | |_____| |_____| |_____|
## ############# f r a m e w o r k
# # #########
###
(c) 2015 - 2017 FUGU framework project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using Microsoft.EntityFrameworkCore.Storage;
using System.Collections.Generic;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
namespace Fugu.EntityFrameworkCore.Sql
{
public static class DataContextExtensions
{
public static int ExecuteSqlCommand<TDbContext>(this DataContextBase<TDbContext> context, ISqlCommand sql, params object[] parameters)
where TDbContext : DbContextBase
{
Contract.NotNull(context, nameof(context));
Contract.NotNull(sql, nameof(sql));
return context.DbContext.ExecuteSqlCommand(sql, parameters);
}
public static int ExecuteSqlCommand<TDbContext, TArgument>(this DataContextBase<TDbContext> context, ISqlCommand<TArgument> sql, TArgument argument)
where TDbContext : DbContextBase
{
Contract.NotNull(context, nameof(context));
Contract.NotNull(sql, nameof(sql));
return context.DbContext.ExecuteSqlCommand(sql, argument);
}
public static Task<int> ExecuteSqlCommandAsync<TDbContext>(this DataContextBase<TDbContext> context, ISqlCommand sql, CancellationToken cancellationToken = default(CancellationToken), params object[] parameters)
where TDbContext : DbContextBase
{
Contract.NotNull(context, nameof(context));
Contract.NotNull(sql, nameof(sql));
return context.DbContext.ExecuteSqlCommandAsync(sql, cancellationToken, parameters);
}
public static Task<int> ExecuteSqlCommandAsync<TDbContext, TArgument>(this DataContextBase<TDbContext> context, ISqlCommand<TArgument> sql, TArgument argument, CancellationToken cancellationToken = default(CancellationToken))
where TDbContext : DbContextBase
{
Contract.NotNull(context, nameof(context));
Contract.NotNull(sql, nameof(sql));
return context.DbContext.ExecuteSqlCommandAsync(sql, cancellationToken, sql.GetParameters(argument));
}
public static object ExecuteSqlScalar<TDbContext>(this DataContextBase<TDbContext> context, ISqlCommand sql, params object[] parameters)
where TDbContext : DbContextBase
{
Contract.NotNull(context, nameof(context));
Contract.NotNull(sql, nameof(sql));
return context.DbContext.ExecuteSqlScalar(sql, parameters);
}
public static object ExecuteSqlScalar<TDbContext, TArgument>(this DataContextBase<TDbContext> context, ISqlCommand<TArgument> sql, TArgument argument)
where TDbContext : DbContextBase
{
Contract.NotNull(context, nameof(context));
Contract.NotNull(sql, nameof(sql));
return context.DbContext.ExecuteSqlScalar(sql, argument);
}
public static Task<object> ExecuteSqlScalarAsync<TDbContext>(this DataContextBase<TDbContext> context, ISqlCommand sql, CancellationToken cancellationToken = default(CancellationToken), params object[] parameters)
where TDbContext : DbContextBase
{
Contract.NotNull(context, nameof(context));
Contract.NotNull(sql, nameof(sql));
return context.DbContext.ExecuteSqlScalarAsync(sql, cancellationToken, parameters);
}
public static Task<object> ExecuteSqlScalarAsync<TDbContext, TArgument>(this DataContextBase<TDbContext> context, ISqlCommand<TArgument> sql, TArgument argument, CancellationToken cancellationToken = default(CancellationToken))
where TDbContext : DbContextBase
{
Contract.NotNull(context, nameof(context));
Contract.NotNull(sql, nameof(sql));
return context.DbContext.ExecuteSqlScalarAsync(sql, cancellationToken, sql.GetParameters(argument));
}
public static IEnumerable<TClass> ExecuteSqlReader<TDbContext, TClass>(this DataContextBase<TDbContext> context, string sql, params object[] parameters)
where TDbContext : DbContextBase
where TClass : new()
{
Contract.NotNull(context, nameof(context));
Contract.NotNull(sql, nameof(sql));
return context.DbContext.ExecuteSqlReader<TClass>(sql, parameters);
}
public static IEnumerable<TClass> ExecuteSqlReader<TDbContext, TClass>(this DataContextBase<TDbContext> context, ISqlCommand sql, params object[] parameters)
where TDbContext : DbContextBase
where TClass : new()
{
Contract.NotNull(context, nameof(context));
Contract.NotNull(sql, nameof(sql));
return context.DbContext.ExecuteSqlReader<TClass>(sql, parameters);
}
public static IEnumerable<TArgument> ExecuteSqlReader<TDbContext, TArgument>(this DataContextBase<TDbContext> context, ISqlCommand<TArgument> sql, TArgument argument)
where TDbContext : DbContextBase
where TArgument : new()
{
Contract.NotNull(context, nameof(context));
Contract.NotNull(sql, nameof(sql));
return context.DbContext.ExecuteSqlReader(sql, argument);
}
public static Task<IEnumerable<TClass>> ExecuteSqlReaderAsync<TDbContext, TClass>(this DataContextBase<TDbContext> context, string sql, CancellationToken cancellationToken = default(CancellationToken), params object[] parameters)
where TDbContext : DbContextBase
where TClass : new()
{
Contract.NotNull(context, nameof(context));
Contract.NotNull(sql, nameof(sql));
return context.DbContext.ExecuteSqlReaderAsync<TClass>(sql, cancellationToken, parameters);
}
public static Task<IEnumerable<TClass>> ExecuteSqlReaderAsync<TDbContext, TClass>(this DataContextBase<TDbContext> context, ISqlCommand sql, CancellationToken cancellationToken = default(CancellationToken), params object[] parameters)
where TDbContext : DbContextBase
where TClass : new()
{
Contract.NotNull(context, nameof(context));
Contract.NotNull(sql, nameof(sql));
return context.DbContext.ExecuteSqlReaderAsync<TClass>(sql, cancellationToken, parameters);
}
public static Task<IEnumerable<TArgument>> ExecuteSqlReaderAsync<TDbContext, TArgument>(this DataContextBase<TDbContext> context, ISqlCommand<TArgument> sql, TArgument argument, CancellationToken cancellationToken = default(CancellationToken))
where TDbContext : DbContextBase
where TArgument : new()
{
Contract.NotNull(context, nameof(context));
Contract.NotNull(sql, nameof(sql));
return context.DbContext.ExecuteSqlReaderAsync(sql, argument, cancellationToken);
}
public static IDbContextTransaction BeginDbTransaction<TDbContext>(this DataContextBase<TDbContext> context)
where TDbContext : DbContextBase
{
Contract.NotNull(context, nameof(context));
return context.DbContext.BeginDbTransaction();
}
public static IDbContextTransaction BeginDbTransaction<TDbContext>(this DataContextBase<TDbContext> context, IsolationLevel isolationLevel)
where TDbContext : DbContextBase
{
Contract.NotNull(context, nameof(context));
return context.DbContext.BeginDbTransaction(isolationLevel);
}
public static Task<IDbContextTransaction> BeginDbTransactionAsync<TDbContext>(this DataContextBase<TDbContext> context, CancellationToken cancellationToken = default(CancellationToken))
where TDbContext : DbContextBase
{
Contract.NotNull(context, nameof(context));
return context.DbContext.BeginDbTransactionAsync(cancellationToken);
}
public static Task<IDbContextTransaction> BeginDbTransactionAsync<TDbContext>(this DataContextBase<TDbContext> context, IsolationLevel isolationLevel, CancellationToken cancellationToken = default(CancellationToken))
where TDbContext : DbContextBase
{
Contract.NotNull(context, nameof(context));
return context.DbContext.BeginDbTransactionAsync(isolationLevel, cancellationToken);
}
public static void CommitDbTransaction<TDbContext>(this DataContextBase<TDbContext> context)
where TDbContext : DbContextBase
{
Contract.NotNull(context, nameof(context));
context.DbContext.CommitDbTransaction();
}
public static void RollbackDbTransaction<TDbContext>(this DataContextBase<TDbContext> context)
where TDbContext : DbContextBase
{
Contract.NotNull(context, nameof(context));
context.DbContext.RollbackDbTransaction();
}
}
}
| |
// <copyright file="RiakCluster.cs" company="Basho Technologies, Inc.">
// Copyright 2011 - OJ Reeves & Jeremiah Peschka
// Copyright 2014 - Basho Technologies, Inc.
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// </copyright>
namespace RiakClient
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Comms;
using Comms.LoadBalancing;
using Config;
using Messages;
/// <summary>
/// Represents a collection of <see cref="RiakEndPoint"/>s.
/// Allows operations to be performed using an endpoint's connection.
/// Also supported rudimentary load balancing between multiple nodes.
/// </summary>
public class RiakCluster : RiakEndPoint
{
private readonly RoundRobinStrategy loadBalancer;
private readonly List<IRiakNode> nodes;
private readonly ConcurrentQueue<IRiakNode> offlineNodes;
private readonly TimeSpan nodePollTime;
private readonly int defaultRetryCount;
private bool disposing = false;
/// <summary>
/// Initializes a new instance of the <see cref="RiakCluster"/> class.
/// </summary>
/// <param name="clusterConfig">The <see cref="IRiakClusterConfiguration"/> to use for this RiakCluster.</param>
/// <param name="connectionFactory">The <see cref="IRiakConnectionFactory"/> instance to use for this RiakCluster.</param>
/// <exception cref="ArgumentNullException">If <paramref name="clusterConfig" /> contains no node information.</exception>
public RiakCluster(IRiakClusterConfiguration clusterConfig, IRiakConnectionFactory connectionFactory)
{
nodePollTime = clusterConfig.NodePollTime;
nodes = clusterConfig.RiakNodes.Select(rn =>
new RiakNode(rn, clusterConfig.Authentication, connectionFactory)).Cast<IRiakNode>().ToList();
loadBalancer = new RoundRobinStrategy();
loadBalancer.Initialise(nodes);
offlineNodes = new ConcurrentQueue<IRiakNode>();
defaultRetryCount = clusterConfig.DefaultRetryCount;
RetryWaitTime = clusterConfig.DefaultRetryWaitTime;
Task.Factory.StartNew(NodeMonitor);
}
/// <summary>
/// Initializes a new instance of the <see cref="RiakCluster"/> class using the default connection factory.
/// </summary>
/// <param name="clusterConfig">The <see cref="IRiakClusterConfiguration"/> to use for this RiakCluster.</param>
/// <exception cref="ArgumentNullException">If <paramref name="clusterConfig" /> contains no node information.</exception>
public RiakCluster(IRiakClusterConfiguration clusterConfig)
: this(clusterConfig, new RiakConnectionFactory())
{
}
/// <inheritdoc/>
protected override int DefaultRetryCount
{
get { return defaultRetryCount; }
}
/// <summary>
/// Creates an instance of <see cref="IRiakClient"/> populated from from the configuration section
/// specified by <paramref name="configSectionName"/>.
/// </summary>
/// <param name="configSectionName">The name of the configuration section to load the settings from.</param>
/// <returns>A fully configured <see cref="IRiakEndPoint"/></returns>
public static IRiakEndPoint FromConfig(string configSectionName)
{
return new RiakCluster(RiakClusterConfiguration.LoadFromConfig(configSectionName), new RiakConnectionFactory());
}
/// <summary>
/// Creates an instance of <see cref="IRiakClient"/> populated from from the configuration section
/// specified by <paramref name="configSectionName"/>.
/// </summary>
/// <param name="configSectionName">The name of the configuration section to load the settings from.</param>
/// <param name="configFileName">The full path and name of the config file to load the configuration from.</param>
/// <returns>A fully configured <see cref="IRiakEndPoint"/></returns>
public static IRiakEndPoint FromConfig(string configSectionName, string configFileName)
{
return new RiakCluster(RiakClusterConfiguration.LoadFromConfig(configSectionName, configFileName), new RiakConnectionFactory());
}
/// <summary>
/// Executes a delegate function using a <see cref="IRiakConnection"/>, and returns the results.
/// Can retry up to "<paramref name="retryAttempts"/>" times for <see cref="ResultCode.NoRetries"/> and <see cref="ResultCode.ShuttingDown"/> error states.
/// This method is used over <see cref="RiakEndPoint.UseConnection"/> to keep a connection open to receive streaming results.
/// </summary>
/// <typeparam name="TResult">The type of the result from the <paramref name="useFun"/> parameter.</typeparam>
/// <param name="useFun">
/// The delegate function to execute. Takes an <see cref="IRiakConnection"/> and an <see cref="Action"/> continuation as input, and returns a
/// <see cref="RiakResult{T}"/> containing an <see cref="IEnumerable{TResult}"/> as the results of the operation.
/// </param>
/// <param name="retryAttempts">The number of times to retry an operation.</param>
/// <returns>The results of the <paramref name="useFun"/> delegate.</returns>
public override RiakResult<IEnumerable<TResult>> UseDelayedConnection<TResult>(Func<IRiakConnection, Action, RiakResult<IEnumerable<TResult>>> useFun, int retryAttempts)
{
if (retryAttempts < 0)
{
return RiakResult<IEnumerable<TResult>>.FromError(ResultCode.NoRetries, "Unable to access a connection on the cluster.", false);
}
if (disposing)
{
return RiakResult<IEnumerable<TResult>>.FromError(ResultCode.ShuttingDown, "System currently shutting down", true);
}
var node = loadBalancer.SelectNode();
if (node != null)
{
var result = node.UseDelayedConnection(useFun);
if (!result.IsSuccess)
{
if (result.ResultCode == ResultCode.NoConnections)
{
Thread.Sleep(RetryWaitTime);
return UseDelayedConnection(useFun, retryAttempts - 1);
}
if (result.ResultCode == ResultCode.CommunicationError)
{
if (result.NodeOffline)
{
DeactivateNode(node);
}
Thread.Sleep(RetryWaitTime);
return UseDelayedConnection(useFun, retryAttempts - 1);
}
}
return result;
}
return RiakResult<IEnumerable<TResult>>.FromError(ResultCode.ClusterOffline, "Unable to access functioning Riak node", true);
}
protected override void Dispose(bool disposing)
{
this.disposing = disposing;
if (disposing)
{
nodes.ForEach(n => n.Dispose());
}
}
protected override TRiakResult UseConnection<TRiakResult>(
Func<IRiakConnection, TRiakResult> useFun,
Func<ResultCode, string, bool, TRiakResult> onError,
int retryAttempts)
{
if (retryAttempts < 0)
{
return onError(ResultCode.NoRetries, "Unable to access a connection on the cluster.", false);
}
if (disposing)
{
return onError(ResultCode.ShuttingDown, "System currently shutting down", true);
}
var node = loadBalancer.SelectNode();
if (node != null)
{
var result = node.UseConnection(useFun);
if (!result.IsSuccess)
{
TRiakResult nextResult = null;
if (result.ResultCode == ResultCode.NoConnections)
{
Thread.Sleep(RetryWaitTime);
nextResult = UseConnection(useFun, onError, retryAttempts - 1);
}
else if (result.ResultCode == ResultCode.CommunicationError)
{
if (result.NodeOffline)
{
DeactivateNode(node);
}
Thread.Sleep(RetryWaitTime);
nextResult = UseConnection(useFun, onError, retryAttempts - 1);
}
// if the next result is successful then return that
if (nextResult != null && nextResult.IsSuccess)
{
return nextResult;
}
// otherwise we'll return the result that we had at this call to make sure that
// the correct/initial error is shown
return onError(result.ResultCode, result.ErrorMessage, result.NodeOffline);
}
return (TRiakResult)result;
}
return onError(ResultCode.ClusterOffline, "Unable to access functioning Riak node", true);
}
private void DeactivateNode(IRiakNode node)
{
lock (node)
{
if (!offlineNodes.Contains(node))
{
loadBalancer.RemoveNode(node);
offlineNodes.Enqueue(node);
}
}
}
// TODO: move to own class
private void NodeMonitor()
{
while (!disposing)
{
var deadNodes = new List<IRiakNode>();
IRiakNode node = null;
while (offlineNodes.TryDequeue(out node) && !disposing)
{
var result = node.UseConnection(c => c.PbcWriteRead(MessageCode.RpbPingReq, MessageCode.RpbPingResp));
if (result.IsSuccess)
{
loadBalancer.AddNode(node);
}
else
{
deadNodes.Add(node);
}
}
if (!disposing)
{
foreach (var deadNode in deadNodes)
{
offlineNodes.Enqueue(deadNode);
}
Thread.Sleep(nodePollTime);
}
}
}
}
}
| |
using System;
using System.Linq;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Data;
using ServiceStack.Common.Utils;
using ServiceStack.DataAnnotations;
using ServiceStack.Common.Extensions;
using System.Reflection;
using ServiceStack.OrmLite;
using ServiceStack.OrmLite.Oracle;
namespace TestExpressions
{
public class Author{
public Author(){}
[AutoIncrement]
[Alias("AuthorID")]
public Int32 Id { get; set;}
[Index(Unique = true)]
[StringLength(40)]
public string Name { get; set;}
public DateTime Birthday { get; set;}
public DateTime ? LastActivity { get; set;}
public Decimal? Earnings { get; set;}
public bool Active { get; set; }
[StringLength(80)]
[Alias("JobCity")]
public string City { get; set;}
[StringLength(80)]
[Alias("Comment")]
public string Comments { get; set;}
public Int16 Rate{ get; set;}
}
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine ("Hello World!");
OrmLiteConfig.DialectProvider = new OracleOrmLiteDialectProvider();
SqlExpressionVisitor<Author> ev = OrmLiteConfig.DialectProvider.ExpressionVisitor<Author>();
using (IDbConnection db =
"Data Source=x;User Id=x;Password=x;".OpenDbConnection())
using ( IDbCommand dbCmd = db.CreateCommand())
{
dbCmd.DropTable<Author>();
dbCmd.CreateTable<Author>();
dbCmd.DeleteAll<Author>();
List<Author> authors = new List<Author>();
authors.Add(new Author(){Name="Demis Bellot",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 99.9m,Comments="CSharp books", Rate=10, City="London"});
authors.Add(new Author(){Name="Angel Colmenares",Birthday= DateTime.Today.AddYears(-25),Active=true,Earnings= 50.0m,Comments="CSharp books", Rate=5, City="Bogota"});
authors.Add(new Author(){Name="Adam Witco",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 80.0m,Comments="Math Books", Rate=9, City="London"});
authors.Add(new Author(){Name="Claudia Espinel",Birthday= DateTime.Today.AddYears(-23),Active=true,Earnings= 60.0m,Comments="Cooking books", Rate=10, City="Bogota"});
authors.Add(new Author(){Name="Libardo Pajaro",Birthday= DateTime.Today.AddYears(-25),Active=true,Earnings= 80.0m,Comments="CSharp books", Rate=9, City="Bogota"});
authors.Add(new Author(){Name="Jorge Garzon",Birthday= DateTime.Today.AddYears(-28),Active=true,Earnings= 70.0m,Comments="CSharp books", Rate=9, City="Bogota"});
authors.Add(new Author(){Name="Alejandro Isaza",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 70.0m,Comments="Java books", Rate=0, City="Bogota"});
authors.Add(new Author(){Name="Wilmer Agamez",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 30.0m,Comments="Java books", Rate=0, City="Cartagena"});
authors.Add(new Author(){Name="Rodger Contreras",Birthday= DateTime.Today.AddYears(-25),Active=true,Earnings= 90.0m,Comments="CSharp books", Rate=8, City="Cartagena"});
authors.Add(new Author(){Name="Chuck Benedict",Birthday= DateTime.Today.AddYears(-22),Active=true,Earnings= 85.5m,Comments="CSharp books", Rate=8, City="London"});
authors.Add(new Author(){Name="James Benedict II",Birthday= DateTime.Today.AddYears(-22),Active=true,Earnings= 85.5m,Comments="Java books", Rate=5, City="Berlin"});
authors.Add(new Author(){Name="Ethan Brown",Birthday= DateTime.Today.AddYears(-20),Active=true,Earnings= 45.0m,Comments="CSharp books", Rate=5, City="Madrid"});
authors.Add(new Author(){Name="Xavi Garzon",Birthday= DateTime.Today.AddYears(-22),Active=true,Earnings= 75.0m,Comments="CSharp books", Rate=9, City="Madrid"});
authors.Add(new Author(){Name="Luis garzon",Birthday= DateTime.Today.AddYears(-22),Active=true,Earnings= 85.0m,Comments="CSharp books", Rate=10, City="Mexico"});
dbCmd.InsertAll(authors);
// lets start !
// select authors born 20 year ago
int year = DateTime.Today.AddYears(-20).Year;
int expected=5;
ev.Where(rn=> rn.Birthday>=new DateTime(year, 1,1) && rn.Birthday<=new DateTime(year, 12,31));
List<Author> result=dbCmd.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
result = dbCmd.Select<Author>(qry => qry.Where(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= new DateTime(year, 12, 31)));
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count);
result = dbCmd.Select<Author>(rn => rn.Birthday >= new DateTime(year, 1, 1) && rn.Birthday <= new DateTime(year, 12, 31));
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected == result.Count);
// select authors from London, Berlin and Madrid : 6
expected=6;
//Sql.In can take params object[]
ev.Where(rn=> Sql.In( rn.City, new object[]{"London", "Madrid", "Berlin"}) );
result=dbCmd.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors from Bogota and Cartagena : 7
expected=7;
//... or Sql.In can take IList<Object>
List<Object> cities= new List<Object>();
cities.Add("Bogota");
cities.Add("Cartagena");
ev.Where(rn => Sql.In(rn.City, cities ));
result=dbCmd.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors which name starts with A
expected=3;
ev.Where(rn=> rn.Name.StartsWith("A") );
result=dbCmd.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors which name ends with Garzon o GARZON o garzon ( no case sensitive )
expected=3;
ev.Where(rn=> rn.Name.ToUpper().EndsWith("GARZON") );
result=dbCmd.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors which name ends with garzon ( no case sensitive )
expected=3;
ev.Where(rn=> rn.Name.EndsWith("garzon") );
result=dbCmd.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors which name contains Benedict
expected=2;
ev.Where(rn=> rn.Name.Contains("Benedict") );
result=dbCmd.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors with Earnings <= 50
expected=3;
ev.Where(rn=> rn.Earnings<=50 );
result=dbCmd.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// select authors with Rate = 10 and city=Mexio
expected=1;
ev.Where(rn=> rn.Rate==10 && rn.City=="Mexico");
result=dbCmd.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// enough selecting, lets update;
// set Active=false where rate =0
expected=2;
ev.Where(rn=> rn.Rate==0 ).Update(rn=> rn.Active);
var rows = dbCmd.UpdateOnly( new Author(){ Active=false }, ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, rows, expected==rows);
// insert values only in Id, Name, Birthday, Rate and Active fields
expected=4;
ev.Insert(rn =>new { rn.Id, rn.Name, rn.Birthday, rn.Active, rn.Rate} );
dbCmd.InsertOnly( new Author(){Active=false, Rate=0, Name="Victor Grozny", Birthday=DateTime.Today.AddYears(-18) }, ev);
dbCmd.InsertOnly( new Author(){Active=false, Rate=0, Name="Ivan Chorny", Birthday=DateTime.Today.AddYears(-19) }, ev);
ev.Where(rn=> !rn.Active);
result=dbCmd.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
//update comment for City == null
expected=2;
ev.Where( rn => rn.City==null ).Update(rn=> rn.Comments);
rows=dbCmd.UpdateOnly(new Author(){Comments="No comments"}, ev);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, rows, expected==rows);
// delete where City is null
expected=2;
rows = dbCmd.Delete( ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, rows, expected==rows);
// lets select all records ordered by Rate Descending and Name Ascending
expected=14;
ev.Where().OrderBy(rn=> new{ at=Sql.Desc(rn.Rate), rn.Name }); // clear where condition
result=dbCmd.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
Console.WriteLine(ev.OrderByExpression);
var author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Claudia Espinel", author.Name, "Claudia Espinel"==author.Name);
// select only first 5 rows ....
expected=5;
ev.Limit(5); // note: order is the same as in the last sentence
result=dbCmd.Select(ev);
Console.WriteLine(ev.WhereExpression);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
// lets select only Name and City (name will be "UPPERCASED" )
ev.Select(rn=> new { at= Sql.As( rn.Name.ToUpper(), "Name" ), rn.City} );
Console.WriteLine(ev.SelectExpression);
result=dbCmd.Select(ev);
author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper()==author.Name);
//paging :
ev.Limit(0,4);// first page, page size=4;
result=dbCmd.Select(ev);
author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Claudia Espinel".ToUpper(), author.Name, "Claudia Espinel".ToUpper()==author.Name);
ev.Limit(4,4);// second page
result=dbCmd.Select(ev);
author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Jorge Garzon".ToUpper(), author.Name, "Jorge Garzon".ToUpper()==author.Name);
ev.Limit(8,4);// third page
result=dbCmd.Select(ev);
author = result.FirstOrDefault();
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", "Rodger Contreras".ToUpper(), author.Name, "Rodger Contreras".ToUpper()==author.Name);
// select distinct..
ev.Limit(); // clear limit
ev.SelectDistinct(r=>r.City).OrderBy();
expected=6;
result=dbCmd.Select(ev);
Console.WriteLine("Expected:{0} ; Selected:{1}, OK? {2}", expected, result.Count, expected==result.Count);
Console.ReadLine();
Console.WriteLine("Press Enter to continue");
}
Console.WriteLine ("This is The End my friend!");
}
}
}
| |
using System;
using Htc.Vita.Core.Log;
using Xunit;
namespace Htc.Vita.Core.Tests
{
public static class LoggerTest
{
[Fact]
public static void Default_0_GetInstance()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
}
[Fact]
public static void Default_0_GetInstance_WithName()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance("Alt");
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Default_0_GetInstance_WithType()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Default_1_Debug()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
logger.Debug("Default test debug message");
Assert.NotNull(logger);
}
[Fact]
public static void Default_1_Debug_WithName()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance("Alt");
Assert.NotNull(loggerAlt);
logger.Debug("Default test debug message");
loggerAlt.Debug("Default test debug message in Alt", new DummyException("Alt"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Default_1_Debug_WithType()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Debug("Default test debug message");
loggerAlt.Debug("Default test debug message in TestCase", new DummyException("TestCase"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Default_2_Error()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
logger.Error("Default test error message");
Assert.NotNull(logger);
}
[Fact]
public static void Default_2_Error_WithName()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance("Alt");
Assert.NotNull(loggerAlt);
logger.Error("Default test error message");
loggerAlt.Error("Default test error message in Alt", new DummyException("Alt"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Default_2_Error_WithType()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Error("Default test error message");
loggerAlt.Error("Default test error message in TestCase", new DummyException("TestCase"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Default_3_Fatal()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
logger.Fatal("Default test fatal message");
Assert.NotNull(logger);
}
[Fact]
public static void Default_3_Fatal_WithName()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance("Alt");
Assert.NotNull(loggerAlt);
logger.Fatal("Default test fatal message");
loggerAlt.Fatal("Default test fatal message in Alt", new DummyException("Alt"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Default_3_Fatal_WithType()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Fatal("Default test fatal message");
loggerAlt.Fatal("Default test fatal message in TestCase", new DummyException("TestCase"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Default_4_Info()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
logger.Info("Default test info message");
Assert.NotNull(logger);
}
[Fact]
public static void Default_4_Info_WithName()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance("Alt");
Assert.NotNull(loggerAlt);
logger.Info("Default test info message");
loggerAlt.Info("Default test info message in Alt", new DummyException("Alt"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Default_4_Info_WithType()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Info("Default test info message");
loggerAlt.Info("Default test info message in TestCase", new DummyException("TestCase"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Default_5_Trace()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
logger.Trace("Default test trace message");
Assert.NotNull(logger);
}
[Fact]
public static void Default_5_Trace_WithName()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance("Alt");
Assert.NotNull(loggerAlt);
logger.Trace("Default test trace message");
loggerAlt.Trace("Default test trace message in Alt", new DummyException("Alt"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Default_5_Trace_WithType()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Trace("Default test trace message");
loggerAlt.Trace("Default test trace message in TestCase", new DummyException("TestCase"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Default_6_Warn()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
logger.Warn("Default test warn message");
Assert.NotNull(logger);
}
[Fact]
public static void Default_6_Warn_WithName()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance("Alt");
Assert.NotNull(loggerAlt);
logger.Warn("Default test warn message");
loggerAlt.Warn("Default test warn message in Alt", new DummyException("Alt"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Default_6_Warn_WithType()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Warn("Default test warn message");
loggerAlt.Warn("Default test warn message in TestCase", new DummyException("TestCase"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Default_7_Shutdown()
{
var logger = Logger.GetInstance();
Assert.NotNull(logger);
logger.Shutdown();
}
[Fact]
public static void Console_0_GetInstance()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
}
[Fact]
public static void Console_0_GetInstance_WithName()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<ConsoleLogger>("Alt");
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Console_0_GetInstance_WithType()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<ConsoleLogger>(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Console_1_Debug()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
logger.Debug("Console test debug message");
Assert.NotNull(logger);
}
[Fact]
public static void Console_1_Debug_WithName()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<ConsoleLogger>("Alt");
Assert.NotNull(loggerAlt);
logger.Debug("Console test debug message");
loggerAlt.Debug("Console test debug message in Alt", new DummyException("Alt"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Console_1_Debug_WithType()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<ConsoleLogger>(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Debug("Console test debug message");
loggerAlt.Debug("Console test debug message in TestCase", new DummyException("TestCase"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Console_2_Error()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
logger.Error("Console test error message");
Assert.NotNull(logger);
}
[Fact]
public static void Console_2_Error_WithName()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<ConsoleLogger>("Alt");
Assert.NotNull(loggerAlt);
logger.Error("Console test error message");
loggerAlt.Error("Console test error message in Alt", new DummyException("Alt"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Console_2_Error_WithType()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<ConsoleLogger>(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Error("Console test error message");
loggerAlt.Error("Console test error message in TestCase", new DummyException("TestCase"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Console_3_Fatal()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
logger.Fatal("Console test fatal message");
Assert.NotNull(logger);
}
[Fact]
public static void Console_3_Fatal_WithName()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<ConsoleLogger>("Alt");
Assert.NotNull(loggerAlt);
logger.Fatal("Console test fatal message");
loggerAlt.Fatal("Console test fatal message in Alt", new DummyException("Alt"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Console_3_Fatal_WithType()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<ConsoleLogger>(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Fatal("Console test fatal message");
loggerAlt.Fatal("Console test fatal message in TestCase", new DummyException("TestCase"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Console_4_Info()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
logger.Info("Console test info message");
Assert.NotNull(logger);
}
[Fact]
public static void Console_4_Info_WithName()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<ConsoleLogger>("Alt");
Assert.NotNull(loggerAlt);
logger.Info("Console test info message");
loggerAlt.Info("Console test info message in Alt", new DummyException("Alt"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Console_4_Info_WithType()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<ConsoleLogger>(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Info("Console test info message");
loggerAlt.Info("Console test info message in TestCase", new DummyException("TestCase"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Console_5_Trace()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
logger.Trace("Console test trace message");
Assert.NotNull(logger);
}
[Fact]
public static void Console_5_Trace_WithName()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<ConsoleLogger>("Alt");
Assert.NotNull(loggerAlt);
logger.Trace("Console test trace message");
loggerAlt.Trace("Console test trace message in Alt", new DummyException("Alt"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Console_5_Trace_WithType()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<ConsoleLogger>(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Trace("Console test trace message");
loggerAlt.Trace("Console test trace message in TestCase", new DummyException("TestCase"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Console_6_Warn()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
logger.Warn("Console test warn message");
Assert.NotNull(logger);
}
[Fact]
public static void Console_6_Warn_WithName()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<ConsoleLogger>("Alt");
Assert.NotNull(loggerAlt);
logger.Warn("Console test warn message");
loggerAlt.Warn("Console test warn message in Alt", new DummyException("Alt"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Console_6_Warn_WithType()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<ConsoleLogger>(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Warn("Console test warn message");
loggerAlt.Warn("Console test warn message in TestCase", new DummyException("TestCase"));
Assert.NotNull(logger);
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Console_7_Shutdown()
{
var logger = Logger.GetInstance<ConsoleLogger>();
Assert.NotNull(logger);
logger.Shutdown();
}
[Fact]
public static void Dummy_0_GetInstance()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
}
[Fact]
public static void Dummy_0_GetInstance_WithName()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<DummyLogger>("Alt");
Assert.NotNull(loggerAlt);
Assert.NotSame(logger, loggerAlt);
}
[Fact]
public static void Dummy_1_Debug()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
logger.Debug("Dummy test debug message");
Assert.True(logger is DummyLogger);
var dummyLogger = (DummyLogger)logger;
Assert.EndsWith("Dummy test debug message", dummyLogger.GetBuffer());
}
[Fact]
public static void Dummy_1_Debug_WithName()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<DummyLogger>("Alt");
Assert.NotNull(loggerAlt);
logger.Debug("Dummy test debug message");
loggerAlt.Debug("Dummy test debug message in Alt", new DummyException("Alt"));
var dummyLogger = (DummyLogger)logger;
var dummyLoggerAlt = (DummyLogger)loggerAlt;
Assert.NotNull(dummyLogger);
Assert.NotNull(dummyLoggerAlt);
Assert.NotSame(dummyLogger, dummyLoggerAlt);
Assert.EndsWith("Dummy test debug message", dummyLogger.GetBuffer());
Assert.EndsWith("Dummy test debug message in Alt" + new DummyException("Alt"), dummyLoggerAlt.GetBuffer());
}
[Fact]
public static void Dummy_1_Debug_WithType()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<DummyLogger>(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Debug("Dummy test debug message");
loggerAlt.Debug("Dummy test debug message in TestCase", new DummyException("TestCase"));
var dummyLogger = (DummyLogger)logger;
var dummyLoggerAlt = (DummyLogger)loggerAlt;
Assert.NotNull(dummyLogger);
Assert.NotNull(dummyLoggerAlt);
Assert.NotSame(dummyLogger, dummyLoggerAlt);
Assert.EndsWith("Dummy test debug message", dummyLogger.GetBuffer());
Assert.EndsWith("Dummy test debug message in TestCase" + new DummyException("TestCase"), dummyLoggerAlt.GetBuffer());
}
[Fact]
public static void Dummy_2_Error()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
logger.Error("Dummy test error message");
Assert.True(logger is DummyLogger);
var dummyLogger = (DummyLogger)logger;
Assert.EndsWith("Dummy test error message", dummyLogger.GetBuffer());
}
[Fact]
public static void Dummy_2_Error_WithName()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<DummyLogger>("Alt");
Assert.NotNull(loggerAlt);
logger.Error("Dummy test error message");
loggerAlt.Error("Dummy test error message in Alt", new DummyException("Alt"));
var dummyLogger = (DummyLogger)logger;
var dummyLoggerAlt = (DummyLogger)loggerAlt;
Assert.NotNull(dummyLogger);
Assert.NotNull(dummyLoggerAlt);
Assert.NotSame(dummyLogger, dummyLoggerAlt);
Assert.EndsWith("Dummy test error message", dummyLogger.GetBuffer());
Assert.EndsWith("Dummy test error message in Alt" + new DummyException("Alt"), dummyLoggerAlt.GetBuffer());
}
[Fact]
public static void Dummy_2_Error_WithType()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<DummyLogger>(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Error("Dummy test error message");
loggerAlt.Error("Dummy test error message in TestCase", new DummyException("TestCase"));
var dummyLogger = (DummyLogger)logger;
var dummyLoggerAlt = (DummyLogger)loggerAlt;
Assert.NotNull(dummyLogger);
Assert.NotNull(dummyLoggerAlt);
Assert.NotSame(dummyLogger, dummyLoggerAlt);
Assert.EndsWith("Dummy test error message", dummyLogger.GetBuffer());
Assert.EndsWith("Dummy test error message in TestCase" + new DummyException("TestCase"), dummyLoggerAlt.GetBuffer());
}
[Fact]
public static void Dummy_3_Fatal()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
logger.Fatal("Dummy test fatal message");
Assert.True(logger is DummyLogger);
var dummyLogger = (DummyLogger)logger;
Assert.EndsWith("Dummy test fatal message", dummyLogger.GetBuffer());
}
[Fact]
public static void Dummy_3_Fatal_WithName()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<DummyLogger>("Alt");
Assert.NotNull(loggerAlt);
logger.Fatal("Dummy test fatal message");
loggerAlt.Fatal("Dummy test fatal message in Alt", new DummyException("Alt"));
var dummyLogger = (DummyLogger)logger;
var dummyLoggerAlt = (DummyLogger)loggerAlt;
Assert.NotNull(dummyLogger);
Assert.NotNull(dummyLoggerAlt);
Assert.NotSame(dummyLogger, dummyLoggerAlt);
Assert.EndsWith("Dummy test fatal message", dummyLogger.GetBuffer());
Assert.EndsWith("Dummy test fatal message in Alt" + new DummyException("Alt"), dummyLoggerAlt.GetBuffer());
}
[Fact]
public static void Dummy_3_Fatal_WithType()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<DummyLogger>(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Fatal("Dummy test fatal message");
loggerAlt.Fatal("Dummy test fatal message in TestCase", new DummyException("TestCase"));
var dummyLogger = (DummyLogger)logger;
var dummyLoggerAlt = (DummyLogger)loggerAlt;
Assert.NotNull(dummyLogger);
Assert.NotNull(dummyLoggerAlt);
Assert.NotSame(dummyLogger, dummyLoggerAlt);
Assert.EndsWith("Dummy test fatal message", dummyLogger.GetBuffer());
Assert.EndsWith("Dummy test fatal message in TestCase" + new DummyException("TestCase"), dummyLoggerAlt.GetBuffer());
}
[Fact]
public static void Dummy_4_Info()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
logger.Info("Dummy test info message");
Assert.True(logger is DummyLogger);
var dummyLogger = (DummyLogger)logger;
Assert.EndsWith("Dummy test info message", dummyLogger.GetBuffer());
}
[Fact]
public static void Dummy_4_Info_WithName()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<DummyLogger>("Alt");
Assert.NotNull(loggerAlt);
logger.Info("Dummy test info message");
loggerAlt.Info("Dummy test info message in Alt", new DummyException("Alt"));
var dummyLogger = (DummyLogger)logger;
var dummyLoggerAlt = (DummyLogger)loggerAlt;
Assert.NotNull(dummyLogger);
Assert.NotNull(dummyLoggerAlt);
Assert.NotSame(dummyLogger, dummyLoggerAlt);
Assert.EndsWith("Dummy test info message", dummyLogger.GetBuffer());
Assert.EndsWith("Dummy test info message in Alt" + new DummyException("Alt"), dummyLoggerAlt.GetBuffer());
}
[Fact]
public static void Dummy_4_Info_WithType()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<DummyLogger>(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Info("Dummy test info message");
loggerAlt.Info("Dummy test info message in TestCase", new DummyException("TestCase"));
var dummyLogger = (DummyLogger)logger;
var dummyLoggerAlt = (DummyLogger)loggerAlt;
Assert.NotNull(dummyLogger);
Assert.NotNull(dummyLoggerAlt);
Assert.NotSame(dummyLogger, dummyLoggerAlt);
Assert.EndsWith("Dummy test info message", dummyLogger.GetBuffer());
Assert.EndsWith("Dummy test info message in TestCase" + new DummyException("TestCase"), dummyLoggerAlt.GetBuffer());
}
[Fact]
public static void Dummy_5_Trace()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
logger.Trace("Dummy test trace message");
Assert.True(logger is DummyLogger);
var dummyLogger = (DummyLogger)logger;
Assert.EndsWith("Dummy test trace message", dummyLogger.GetBuffer());
}
[Fact]
public static void Dummy_5_Trace_WithName()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<DummyLogger>("Alt");
Assert.NotNull(loggerAlt);
logger.Trace("Dummy test trace message");
loggerAlt.Trace("Dummy test trace message in Alt", new DummyException("Alt"));
var dummyLogger = (DummyLogger)logger;
var dummyLoggerAlt = (DummyLogger)loggerAlt;
Assert.NotNull(dummyLogger);
Assert.NotNull(dummyLoggerAlt);
Assert.NotSame(dummyLogger, dummyLoggerAlt);
Assert.EndsWith("Dummy test trace message", dummyLogger.GetBuffer());
Assert.EndsWith("Dummy test trace message in Alt" + new DummyException("Alt"), dummyLoggerAlt.GetBuffer());
}
[Fact]
public static void Dummy_5_Trace_WithType()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<DummyLogger>(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Trace("Dummy test trace message");
loggerAlt.Trace("Dummy test trace message in TestCase", new DummyException("TestCase"));
var dummyLogger = (DummyLogger)logger;
var dummyLoggerAlt = (DummyLogger)loggerAlt;
Assert.NotNull(dummyLogger);
Assert.NotNull(dummyLoggerAlt);
Assert.NotSame(dummyLogger, dummyLoggerAlt);
Assert.EndsWith("Dummy test trace message", dummyLogger.GetBuffer());
Assert.EndsWith("Dummy test trace message in TestCase" + new DummyException("TestCase"), dummyLoggerAlt.GetBuffer());
}
[Fact]
public static void Dummy_6_Warn()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
logger.Warn("Dummy test warn message");
Assert.True(logger is DummyLogger);
var dummyLogger = (DummyLogger)logger;
Assert.EndsWith("Dummy test warn message", dummyLogger.GetBuffer());
}
[Fact]
public static void Dummy_6_Warn_WithName()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<DummyLogger>("Alt");
Assert.NotNull(loggerAlt);
logger.Warn("Dummy test warn message");
loggerAlt.Warn("Dummy test warn message in Alt", new DummyException("Alt"));
var dummyLogger = (DummyLogger)logger;
var dummyLoggerAlt = (DummyLogger)loggerAlt;
Assert.NotNull(dummyLogger);
Assert.NotNull(dummyLoggerAlt);
Assert.NotSame(dummyLogger, dummyLoggerAlt);
Assert.EndsWith("Dummy test warn message", dummyLogger.GetBuffer());
Assert.EndsWith("Dummy test warn message in Alt" + new DummyException("Alt"), dummyLoggerAlt.GetBuffer());
}
[Fact]
public static void Dummy_6_Warn_WithType()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
var loggerAlt = Logger.GetInstance<DummyLogger>(typeof(LoggerTest));
Assert.NotNull(loggerAlt);
logger.Warn("Dummy test warn message");
loggerAlt.Warn("Dummy test warn message in TestCase", new DummyException("TestCase"));
var dummyLogger = (DummyLogger)logger;
var dummyLoggerAlt = (DummyLogger)loggerAlt;
Assert.NotNull(dummyLogger);
Assert.NotNull(dummyLoggerAlt);
Assert.NotSame(dummyLogger, dummyLoggerAlt);
Assert.EndsWith("Dummy test warn message", dummyLogger.GetBuffer());
Assert.EndsWith("Dummy test warn message in TestCase" + new DummyException("TestCase"), dummyLoggerAlt.GetBuffer());
}
[Fact]
public static void Dummy_7_Shutdown()
{
var logger = Logger.GetInstance<DummyLogger>();
Assert.NotNull(logger);
logger.Shutdown();
}
public class DummyException : Exception
{
public DummyException(string message) : base(message)
{
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
////////////////////////////////////////////////////////////////////////////
//
// Class: TextInfo
//
// 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.
//
// Date: March 31, 1999
//
////////////////////////////////////////////////////////////////////////////
using System.Security;
using System;
using System.Text;
using System.Threading;
using System.Runtime;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace System.Globalization
{
public partial class TextInfo
{
////--------------------------------------------------------------------//
//// Internal Information //
////--------------------------------------------------------------------//
////
//// Variables.
////
private String m_listSeparator;
private bool m_isReadOnly = false;
////
//// In Whidbey we had several names:
//// m_win32LangID is the name of the culture, but only used for (de)serialization.
//// customCultureName is the name of the creating custom culture (if custom) In combination with m_win32LangID
//// this is authoratative, ie when deserializing.
//// m_cultureTableRecord was the data record of the creating culture. (could have different name if custom)
//// m_textInfoID is the LCID of the textinfo itself (no longer used)
//// m_name is the culture name (from cultureinfo.name)
////
//// In Silverlight/Arrowhead this is slightly different:
//// m_cultureName is the name of the creating culture. Note that we consider this authoratative,
//// if the culture's textinfo changes when deserializing, then behavior may change.
//// (ala Whidbey behavior). This is the only string Arrowhead needs to serialize.
//// m_cultureData is the data that backs this class.
//// m_textInfoName is the actual name of the textInfo (from cultureData.STEXTINFO)
//// this can be the same as m_cultureName on Silverlight since the OS knows
//// how to do the sorting. However in the desktop, when we call the sorting dll, it doesn't
//// know how to resolve custom locle names to sort ids so we have to have alredy resolved this.
////
private readonly String m_cultureName; // Name of the culture that created this text info
private readonly CultureData m_cultureData; // Data record for the culture that made us, not for this textinfo
private readonly String m_textInfoName; // Name of the text info we're using (ie: m_cultureData.STEXTINFO)
private bool? m_IsAsciiCasingSameAsInvariant;
// Invariant text info
internal static TextInfo Invariant
{
get
{
if (s_Invariant == null)
s_Invariant = new TextInfo(CultureData.Invariant);
return s_Invariant;
}
}
internal volatile static TextInfo s_Invariant;
//
// Internal ordinal comparison functions
//
internal static int GetHashCodeOrdinalIgnoreCase(String s)
{
// This is the same as an case insensitive hash for Invariant
// (not necessarily true for sorting, but OK for casing & then we apply normal hash code rules)
return (Invariant.GetCaseInsensitiveHashCode(s));
}
// Currently we don't have native functions to do this, so we do it the hard way
internal static int IndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
if (count > source.Length || count < 0 || startIndex < 0 || startIndex >= source.Length || startIndex + count > source.Length)
{
return -1;
}
return CompareInfo.IndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
// Currently we don't have native functions to do this, so we do it the hard way
internal static int LastIndexOfStringOrdinalIgnoreCase(String source, String value, int startIndex, int count)
{
if (count > source.Length || count < 0 || startIndex < 0 || startIndex > source.Length - 1 || (startIndex - count + 1 < 0))
{
return -1;
}
return CompareInfo.LastIndexOfOrdinal(source, value, startIndex, count, ignoreCase: true);
}
//////////////////////////////////////////////////////////////////////////
////
//// CultureName
////
//// The name of the culture associated with the current TextInfo.
////
//////////////////////////////////////////////////////////////////////////
public string CultureName
{
get
{
return m_textInfoName;
}
}
////////////////////////////////////////////////////////////////////////
//
// IsReadOnly
//
// Detect if the object is readonly.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
public bool IsReadOnly
{
get { return (m_isReadOnly); }
}
//////////////////////////////////////////////////////////////////////////
////
//// Clone
////
//// Is the implementation of IColnable.
////
//////////////////////////////////////////////////////////////////////////
internal virtual Object Clone()
{
object o = MemberwiseClone();
((TextInfo)o).SetReadOnlyState(false);
return (o);
}
////////////////////////////////////////////////////////////////////////
//
// ReadOnly
//
// Create a cloned readonly instance or return the input one if it is
// readonly.
//
////////////////////////////////////////////////////////////////////////
[System.Runtime.InteropServices.ComVisible(false)]
internal static TextInfo ReadOnly(TextInfo textInfo)
{
if (textInfo == null) { throw new ArgumentNullException("textInfo"); }
Contract.EndContractBlock();
if (textInfo.IsReadOnly) { return (textInfo); }
TextInfo clonedTextInfo = (TextInfo)(textInfo.MemberwiseClone());
clonedTextInfo.SetReadOnlyState(true);
return (clonedTextInfo);
}
private void VerifyWritable()
{
if (m_isReadOnly)
{
throw new InvalidOperationException(SR.InvalidOperation_ReadOnly);
}
}
internal void SetReadOnlyState(bool readOnly)
{
m_isReadOnly = readOnly;
}
////////////////////////////////////////////////////////////////////////
//
// ListSeparator
//
// Returns the string used to separate items in a list.
//
////////////////////////////////////////////////////////////////////////
public virtual String ListSeparator
{
get
{
if (m_listSeparator == null)
{
m_listSeparator = this.m_cultureData.SLIST;
}
return (m_listSeparator);
}
set
{
if (value == null)
{
throw new ArgumentNullException("value", SR.ArgumentNull_String);
}
VerifyWritable();
m_listSeparator = value;
}
}
////////////////////////////////////////////////////////////////////////
//
// ToLower
//
// Converts the character or string to lower case. Certain locales
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual char ToLower(char c)
{
if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
{
return ToLowerAsciiInvariant(c);
}
return (ChangeCase(c, toUpper: false));
}
public unsafe virtual String ToLower(String str)
{
if (str == null) { throw new ArgumentNullException("str"); }
return ChangeCase(str, toUpper: false);
}
static private Char ToLowerAsciiInvariant(Char c)
{
if ('A' <= c && c <= 'Z')
{
c = (Char)(c | 0x20);
}
return c;
}
////////////////////////////////////////////////////////////////////////
//
// ToUpper
//
// Converts the character or string to upper case. Certain locales
// have different casing semantics from the file systems in Win32.
//
////////////////////////////////////////////////////////////////////////
public unsafe virtual char ToUpper(char c)
{
if (IsAscii(c) && IsAsciiCasingSameAsInvariant)
{
return ToUpperAsciiInvariant(c);
}
return (ChangeCase(c, toUpper: true));
}
public unsafe virtual String ToUpper(String str)
{
if (str == null) { throw new ArgumentNullException("str"); }
return ChangeCase(str, toUpper: true);
}
static private Char ToUpperAsciiInvariant(Char c)
{
if ('a' <= c && c <= 'z')
{
c = (Char)(c & ~0x20);
}
return c;
}
static private bool IsAscii(Char c)
{
return c < 0x80;
}
private bool IsAsciiCasingSameAsInvariant
{
get
{
if (m_IsAsciiCasingSameAsInvariant == null)
{
m_IsAsciiCasingSameAsInvariant = CultureInfo.GetCultureInfo(m_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
CompareOptions.IgnoreCase) == 0;
}
return (bool)m_IsAsciiCasingSameAsInvariant;
}
}
// IsRightToLeft
//
// Returns true if the dominant direction of text and UI such as the relative position of buttons and scroll bars
//
public bool IsRightToLeft
{
get
{
return this.m_cultureData.IsRightToLeft;
}
}
////////////////////////////////////////////////////////////////////////
//
// Equals
//
// Implements Object.Equals(). Returns a boolean indicating whether
// or not object refers to the same CultureInfo as the current instance.
//
////////////////////////////////////////////////////////////////////////
public override bool Equals(Object obj)
{
TextInfo that = obj as TextInfo;
if (that != null)
{
return this.CultureName.Equals(that.CultureName);
}
return (false);
}
////////////////////////////////////////////////////////////////////////
//
// GetHashCode
//
// Implements Object.GetHashCode(). Returns the hash code for the
// CultureInfo. The hash code is guaranteed to be the same for CultureInfo A
// and B where A.Equals(B) is true.
//
////////////////////////////////////////////////////////////////////////
public override int GetHashCode()
{
return (this.CultureName.GetHashCode());
}
////////////////////////////////////////////////////////////////////////
//
// ToString
//
// Implements Object.ToString(). Returns a string describing the
// TextInfo.
//
////////////////////////////////////////////////////////////////////////
public override String ToString()
{
return ("TextInfo - " + this.m_cultureData.CultureName);
}
//
// Get case-insensitive hash code for the specified string.
//
internal unsafe int GetCaseInsensitiveHashCode(String str)
{
// Validate inputs
if (str == null)
{
throw new ArgumentNullException("str");
}
// This code assumes that ASCII casing is safe for whatever context is passed in.
// this is true today, because we only ever call these methods on Invariant. It would be ideal to refactor
// these methods so they were correct by construction and we could only ever use Invariant.
uint hash = 5381;
uint c;
// Note: We assume that str contains only ASCII characters until
// we hit a non-ASCII character to optimize the common case.
for (int i = 0; i < str.Length; i++)
{
c = str[i];
if (c >= 0x80)
{
return GetCaseInsensitiveHashCodeSlow(str);
}
// If we have a lowercase character, ANDing off 0x20
// will make it an uppercase character.
if ((c - 'a') <= ('z' - 'a'))
{
c = (uint)((int)c & ~0x20);
}
hash = ((hash << 5) + hash) ^ c;
}
return (int)hash;
}
private unsafe int GetCaseInsensitiveHashCodeSlow(String str)
{
Contract.Assert(str != null);
string upper = ToUpper(str);
uint hash = 5381;
uint c;
for (int i = 0; i < upper.Length; i++)
{
c = upper[i];
hash = ((hash << 5) + hash) ^ c;
}
return (int)hash;
}
}
}
| |
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewEngines;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.Logging;
using Moq;
using Postal.AspNetCore;
using Shouldly;
using System;
using System.Threading.Tasks;
using Xunit;
namespace Postal
{
public class EmailViewRenderTests
{
[Fact]
public async Task Render_returns_email_string_created_by_view()
{
var viewEngine = new Mock<IRazorViewEngine>();
var view = new FakeView();
viewEngine.Setup(e => e.FindView(It.IsAny<ActionContext>(), "Test", It.IsAny<bool>()))
.Returns(ViewEngineResult.Found("Test", view)).Verifiable();
var logger = new Mock<ILogger<TemplateService>>();
var serviceProvider = new Mock<IServiceProvider>();
var tempDataProvider = new Mock<ITempDataProvider>();
var hostingEnvironment = new Mock<IWebHostEnvironment>();
ITemplateService templateService = new TemplateService(logger.Object, viewEngine.Object, serviceProvider.Object, tempDataProvider.Object, hostingEnvironment.Object);
var renderer = new EmailViewRender(templateService);
var actualEmailString = await renderer.RenderAsync(new Email("Test"));
actualEmailString.ShouldBe("Fake");
viewEngine.Verify();
}
[Fact]
public async Task Render_returns_email_string_created_by_view_retrievepath()
{
var viewEngine = new Mock<IRazorViewEngine>();
var view = new FakeView();
viewEngine.Setup(e => e.FindView(It.IsAny<ActionContext>(), "~/Views/TestFolder/Test", It.IsAny<bool>()))
.Returns(ViewEngineResult.NotFound("Test", new string[0]));
viewEngine.Setup(e => e.GetView(It.IsAny<string>(), "~/Views/TestFolder/Test", It.IsAny<bool>()))
.Returns(ViewEngineResult.Found("~/Views/TestFolder/Test", view)).Verifiable();
var logger = new Mock<ILogger<TemplateService>>();
var serviceProvider = new Mock<IServiceProvider>();
var tempDataProvider = new Mock<ITempDataProvider>();
var hostingEnvironment = new Mock<IWebHostEnvironment>();
ITemplateService templateService = new TemplateService(logger.Object, viewEngine.Object, serviceProvider.Object, tempDataProvider.Object, hostingEnvironment.Object);
var renderer = new EmailViewRender(templateService);
var actualEmailString = await renderer.RenderAsync(new Email("~/Views/TestFolder/Test"));
actualEmailString.ShouldBe("Fake");
viewEngine.Verify();
}
class FakeView : IView
{
public FakeView()
{
TemplateString = _ => "Fake";
}
public FakeView(Func<ViewContext, string> templateString)
{
TemplateString = templateString;
}
public string Path => throw new NotImplementedException();
public Func<ViewContext, string> TemplateString { get; private set; }
public Task RenderAsync(ViewContext context)
{
return context.Writer.WriteAsync(TemplateString(context));
}
}
[Fact]
public async Task Render_throws_exception_when_email_view_not_found()
{
var viewEngine = new Mock<IRazorViewEngine>();
viewEngine.Setup(e => e.FindView(It.IsAny<ActionContext>(), "Test", It.IsAny<bool>()))
.Returns(ViewEngineResult.NotFound("Test", new[] { "Test" })).Verifiable();
var logger = new Mock<ILogger<TemplateService>>();
var serviceProvider = new Mock<IServiceProvider>();
var tempDataProvider = new Mock<ITempDataProvider>();
var hostingEnvironment = new Mock<IWebHostEnvironment>();
ITemplateService templateService = new TemplateService(logger.Object, viewEngine.Object, serviceProvider.Object, tempDataProvider.Object, hostingEnvironment.Object);
var renderer = new EmailViewRender(templateService);
await Assert.ThrowsAsync<TemplateServiceException>(() => renderer.RenderAsync(new Email("Test")));
viewEngine.Verify();
}
[Fact]
public async Task Render_throws_exception_when_email_view_retrievepath_not_found()
{
var viewEngine = new Mock<IRazorViewEngine>();
viewEngine.Setup(e => e.GetView(It.IsAny<string>(), "~/Views/TestFolder/Test", It.IsAny<bool>()))
.Returns(ViewEngineResult.NotFound("~/Views/TestFolder/Test", new[] { "Test" })).Verifiable();
var logger = new Mock<ILogger<TemplateService>>();
var serviceProvider = new Mock<IServiceProvider>();
var tempDataProvider = new Mock<ITempDataProvider>();
var hostingEnvironment = new Mock<IWebHostEnvironment>();
ITemplateService templateService = new TemplateService(logger.Object, viewEngine.Object, serviceProvider.Object, tempDataProvider.Object, hostingEnvironment.Object);
var renderer = new EmailViewRender(templateService);
await Assert.ThrowsAsync<TemplateServiceException>(() => renderer.RenderAsync(new Email("~/Views/TestFolder/Test")));
viewEngine.Verify();
}
[Fact]
public async Task Render_returns_email_string_with_img_created_by_view()
{
var email = new Email("Test");
var cid = email.ImageEmbedder.ReferenceImage("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png");
var mvcViewOptions = new Mock<Microsoft.Extensions.Options.IOptions<MvcViewOptions>>();
//var tmp = controller.Resolver.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
//ICompositeViewEngine engine = new CompositeViewEngine(mvcViewOptions.Object);
var viewEngine = new Mock<IRazorViewEngine>();
var view = new FakeView(_ => _.ViewData[ImageEmbedder.ViewDataKey] != null ? "True" : "False");
viewEngine.Setup(e => e.FindView(It.IsAny<ActionContext>(), "Test", It.IsAny<bool>()))
.Returns(ViewEngineResult.Found("Test", view)).Verifiable();
var logger = new Mock<ILogger<TemplateService>>();
var serviceProvider = new Mock<IServiceProvider>();
var tempDataProvider = new Mock<ITempDataProvider>();
var hostingEnvironment = new Mock<IWebHostEnvironment>();
ITemplateService templateService = new TemplateService(logger.Object, viewEngine.Object, serviceProvider.Object, tempDataProvider.Object, hostingEnvironment.Object);
var renderer = new EmailViewRender(templateService);
var actualEmailString = await renderer.RenderAsync(email);
actualEmailString.ShouldBe("True");
viewEngine.Verify();
}
[Fact]
public async Task Render_returns_email_string_with_img_created_by_view_retrievepath()
{
var email = new Email("~/Views/TestFolder/Test");
var cid = email.ImageEmbedder.ReferenceImage("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png");
var mvcViewOptions = new Mock<Microsoft.Extensions.Options.IOptions<MvcViewOptions>>();
//var tmp = controller.Resolver.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine;
//ICompositeViewEngine engine = new CompositeViewEngine(mvcViewOptions.Object);
var viewEngine = new Mock<IRazorViewEngine>();
var view = new FakeView(_ => _.ViewData[ImageEmbedder.ViewDataKey] != null ? "True" : "False");
viewEngine.Setup(e => e.GetView(It.IsAny<string>(), "~/Views/TestFolder/Test", It.IsAny<bool>()))
.Returns(ViewEngineResult.Found("~/Views/TestFolder/Test", view)).Verifiable();
var logger = new Mock<ILogger<TemplateService>>();
var serviceProvider = new Mock<IServiceProvider>();
var tempDataProvider = new Mock<ITempDataProvider>();
var hostingEnvironment = new Mock<IWebHostEnvironment>();
ITemplateService templateService = new TemplateService(logger.Object, viewEngine.Object, serviceProvider.Object, tempDataProvider.Object, hostingEnvironment.Object);
var renderer = new EmailViewRender(templateService);
var actualEmailString = await renderer.RenderAsync(email);
actualEmailString.ShouldBe("True");
viewEngine.Verify();
}
[Fact]
public async Task Render_returns_email_string_created_by_view_generic_host()
{
var viewEngine = new Mock<IRazorViewEngine>();
var view = new FakeView();
viewEngine.Setup(e => e.FindView(It.IsAny<ActionContext>(), "Test", It.IsAny<bool>()))
.Returns(ViewEngineResult.Found("Test", view)).Verifiable();
var logger = new Mock<ILogger<TemplateService>>();
var serviceProvider = new Mock<IServiceProvider>();
var tempDataProvider = new Mock<ITempDataProvider>();
var hostingEnvironment = new Mock<Microsoft.Extensions.Hosting.IHostEnvironment>();
ITemplateService templateService = new TemplateService(logger.Object, viewEngine.Object, serviceProvider.Object, tempDataProvider.Object, hostingEnvironment.Object);
var renderer = new EmailViewRender(templateService);
var actualEmailString = await renderer.RenderAsync(new Email("Test"));
actualEmailString.ShouldBe("Fake");
viewEngine.Verify();
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading.Tasks;
using E2ETests.Common;
using Microsoft.AspNetCore.Server.IntegrationTesting;
using Microsoft.AspNetCore.Testing.xunit;
using Microsoft.Extensions.Logging;
using Xunit;
using Xunit.Abstractions;
namespace E2ETests
{
// Uses ports ranging 5001 - 5025.
// TODO: temporarily disabling these tests as dotnet xunit runner does not support 32-bit yet.
// public
class SmokeTests_X86 : IDisposable
{
private readonly XunitLogger _logger;
public SmokeTests_X86(ITestOutputHelper output)
{
_logger = new XunitLogger(output, LogLevel.Information);
}
[ConditionalTheory, Trait("E2Etests", "Smoke")]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(ServerType.WebListener, RuntimeFlavor.Clr, RuntimeArchitecture.x86, ApplicationType.Portable, "http://localhost:5001/")]
[InlineData(ServerType.WebListener, RuntimeFlavor.CoreClr, RuntimeArchitecture.x86, ApplicationType.Portable, "http://localhost:5002/")]
[InlineData(ServerType.WebListener, RuntimeFlavor.CoreClr, RuntimeArchitecture.x86, ApplicationType.Standalone, "http://localhost:5003/")]
[InlineData(ServerType.Kestrel, RuntimeFlavor.Clr, RuntimeArchitecture.x86, ApplicationType.Portable, "http://localhost:5004/")]
[InlineData(ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x86, ApplicationType.Portable, "http://localhost:5005/")]
[InlineData(ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x86, ApplicationType.Standalone, "http://localhost:5006/")]
[InlineData(ServerType.IISExpress, RuntimeFlavor.Clr, RuntimeArchitecture.x86, ApplicationType.Portable, "http://localhost:5007/")]
[InlineData(ServerType.IISExpress, RuntimeFlavor.CoreClr, RuntimeArchitecture.x86, ApplicationType.Portable, "http://localhost:5008/")]
[InlineData(ServerType.IISExpress, RuntimeFlavor.CoreClr, RuntimeArchitecture.x86, ApplicationType.Standalone, "http://localhost:5009/")]
public async Task WindowsOS(
ServerType serverType,
RuntimeFlavor runtimeFlavor,
RuntimeArchitecture architecture,
ApplicationType applicationType,
string applicationBaseUrl)
{
var smokeTestRunner = new SmokeTests(_logger);
await smokeTestRunner.SmokeTestSuite(serverType, runtimeFlavor, architecture, applicationType, applicationBaseUrl);
}
[ConditionalTheory(Skip = "Temporarily disabling test"), Trait("E2Etests", "Smoke")]
[OSSkipCondition(OperatingSystems.Windows)]
[InlineData(ServerType.Kestrel, RuntimeFlavor.Clr, RuntimeArchitecture.x86, ApplicationType.Portable, "http://localhost:5010/")]
public async Task NonWindowsOS(
ServerType serverType,
RuntimeFlavor runtimeFlavor,
RuntimeArchitecture architecture,
ApplicationType applicationType,
string applicationBaseUrl)
{
var smokeTestRunner = new SmokeTests(_logger);
await smokeTestRunner.SmokeTestSuite(serverType, runtimeFlavor, architecture, applicationType, applicationBaseUrl);
}
public void Dispose()
{
_logger.Dispose();
}
}
public class SmokeTests_X64 : IDisposable
{
private readonly XunitLogger _logger;
public SmokeTests_X64(ITestOutputHelper output)
{
_logger = new XunitLogger(output, LogLevel.Information);
}
[ConditionalTheory, Trait("E2Etests", "Smoke")]
[OSSkipCondition(OperatingSystems.Linux)]
[OSSkipCondition(OperatingSystems.MacOSX)]
[InlineData(ServerType.WebListener, RuntimeFlavor.Clr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5011/")]
[InlineData(ServerType.WebListener, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5012/")]
[InlineData(ServerType.WebListener, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Standalone, "http://localhost:5013/")]
[InlineData(ServerType.Kestrel, RuntimeFlavor.Clr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5014/")]
[InlineData(ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5015/")]
[InlineData(ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Standalone, "http://localhost:5016/")]
[InlineData(ServerType.IISExpress, RuntimeFlavor.Clr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5017/")]
[InlineData(ServerType.IISExpress, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5018/")]
[InlineData(ServerType.IISExpress, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Standalone, "http://localhost:5019/")]
public async Task WindowsOS(
ServerType serverType,
RuntimeFlavor runtimeFlavor,
RuntimeArchitecture architecture,
ApplicationType applicationType,
string applicationBaseUrl)
{
var smokeTestRunner = new SmokeTests(_logger);
await smokeTestRunner.SmokeTestSuite(serverType, runtimeFlavor, architecture, applicationType, applicationBaseUrl);
}
[ConditionalTheory, Trait("E2Etests", "Smoke")]
[OSSkipCondition(OperatingSystems.Windows)]
[InlineData(ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5020/")]
[InlineData(ServerType.Kestrel, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Standalone, "http://localhost:5021/")]
public async Task NonWindowsOS(
ServerType serverType,
RuntimeFlavor runtimeFlavor,
RuntimeArchitecture architecture,
ApplicationType applicationType,
string applicationBaseUrl)
{
var smokeTestRunner = new SmokeTests(_logger);
await smokeTestRunner.SmokeTestSuite(serverType, runtimeFlavor, architecture, applicationType, applicationBaseUrl);
}
public void Dispose()
{
_logger.Dispose();
}
}
class SmokeTests_OnIIS : IDisposable
{
private readonly XunitLogger _logger;
public SmokeTests_OnIIS(ITestOutputHelper output)
{
_logger = new XunitLogger(output, LogLevel.Information);
}
[ConditionalTheory, Trait("E2Etests", "Smoke")]
[OSSkipCondition(OperatingSystems.MacOSX)]
[OSSkipCondition(OperatingSystems.Linux)]
[SkipIfCurrentRuntimeIsCoreClr]
[SkipIfEnvironmentVariableNotEnabled("IIS_VARIATIONS_ENABLED")]
//[InlineData(ServerType.IIS, RuntimeFlavor.Clr, RuntimeArchitecture.x86, ApplicationType.Portable, "http://localhost:5022/")]
[InlineData(ServerType.IIS, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Portable, "http://localhost:5023/")]
[InlineData(ServerType.IIS, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, ApplicationType.Standalone, "http://localhost:5024/")]
public async Task SmokeTestSuite_On_IIS_X86(
ServerType serverType,
RuntimeFlavor runtimeFlavor,
RuntimeArchitecture architecture,
ApplicationType applicationType,
string applicationBaseUrl)
{
var smokeTestRunner = new SmokeTests(_logger);
await smokeTestRunner.SmokeTestSuite(
serverType, runtimeFlavor, architecture, applicationType, applicationBaseUrl, noSource: true);
}
public void Dispose()
{
_logger.Dispose();
}
}
public class SmokeTests
{
private ILogger _logger;
public SmokeTests(ILogger logger)
{
_logger = logger;
}
public async Task SmokeTestSuite(
ServerType serverType,
RuntimeFlavor runtimeFlavor,
RuntimeArchitecture architecture,
ApplicationType applicationType,
string applicationBaseUrl,
bool noSource = false)
{
using (_logger.BeginScope("SmokeTestSuite"))
{
var musicStoreDbName = DbUtils.GetUniqueName();
var deploymentParameters = new DeploymentParameters(
Helpers.GetApplicationPath(applicationType), serverType, runtimeFlavor, architecture)
{
ApplicationBaseUriHint = applicationBaseUrl,
EnvironmentName = "SocialTesting",
ServerConfigTemplateContent = (serverType == ServerType.IISExpress) ? File.ReadAllText("Http.config") : null,
SiteName = "MusicStoreTestSite",
PublishApplicationBeforeDeployment = true,
PreservePublishedApplicationForDebugging = Helpers.PreservePublishedApplicationForDebugging,
TargetFramework = runtimeFlavor == RuntimeFlavor.Clr ? "net451" : "netcoreapp1.0",
Configuration = Helpers.GetCurrentBuildConfiguration(),
ApplicationType = applicationType,
UserAdditionalCleanup = parameters =>
{
DbUtils.DropDatabase(musicStoreDbName, _logger);
}
};
// Override the connection strings using environment based configuration
deploymentParameters.EnvironmentVariables
.Add(new KeyValuePair<string, string>(
MusicStoreConfig.ConnectionStringKey,
DbUtils.CreateConnectionString(musicStoreDbName)));
using (var deployer = ApplicationDeployerFactory.Create(deploymentParameters, _logger))
{
var deploymentResult = deployer.Deploy();
Helpers.SetInMemoryStoreForIIS(deploymentParameters, _logger);
await SmokeTestHelper.RunTestsAsync(deploymentResult, _logger);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;
namespace LinqToDB.DataProvider.DB2
{
using Data;
using Mapping;
using SchemaProvider;
using SqlProvider;
public class DB2DataProvider : DynamicDataProviderBase
{
public DB2DataProvider(string name, DB2Version version)
: base(name, null)
{
Version = version;
SqlProviderFlags.AcceptsTakeAsParameter = false;
SqlProviderFlags.AcceptsTakeAsParameterIfSkip = true;
SqlProviderFlags.IsDistinctOrderBySupported = version != DB2Version.zOS;
SetCharField("CHAR", (r,i) => r.GetString(i).TrimEnd());
_sqlOptimizer = new DB2SqlOptimizer(SqlProviderFlags);
}
protected override void OnConnectionTypeCreated(Type connectionType)
{
DB2Types.ConnectionType = connectionType;
DB2Types.DB2Int64. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Int64", true);
DB2Types.DB2Int32. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Int32", true);
DB2Types.DB2Int16. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Int16", true);
DB2Types.DB2Decimal. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Decimal", true);
DB2Types.DB2DecimalFloat.Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2DecimalFloat", true);
DB2Types.DB2Real. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Real", true);
DB2Types.DB2Real370. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Real370", true);
DB2Types.DB2Double. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Double", true);
DB2Types.DB2String. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2String", true);
DB2Types.DB2Clob. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Clob", true);
DB2Types.DB2Binary. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Binary", true);
DB2Types.DB2Blob. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Blob", true);
DB2Types.DB2Date. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Date", true);
DB2Types.DB2Time. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Time", true);
DB2Types.DB2TimeStamp. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2TimeStamp", true);
DB2Types.DB2Xml = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2Xml", true);
DB2Types.DB2RowId. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2RowId", true);
DB2Types.DB2DateTime. Type = connectionType.Assembly.GetType("IBM.Data.DB2Types.DB2DateTime", false);
SetProviderField(DB2Types.DB2Int64, typeof(Int64), "GetDB2Int64");
SetProviderField(DB2Types.DB2Int32, typeof(Int32), "GetDB2Int32");
SetProviderField(DB2Types.DB2Int16, typeof(Int16), "GetDB2Int16");
SetProviderField(DB2Types.DB2Decimal, typeof(Decimal), "GetDB2Decimal");
SetProviderField(DB2Types.DB2DecimalFloat, typeof(Decimal), "GetDB2DecimalFloat");
SetProviderField(DB2Types.DB2Real, typeof(Single), "GetDB2Real");
SetProviderField(DB2Types.DB2Real370, typeof(Single), "GetDB2Real370");
SetProviderField(DB2Types.DB2Double, typeof(Double), "GetDB2Double");
SetProviderField(DB2Types.DB2String, typeof(String), "GetDB2String");
SetProviderField(DB2Types.DB2Clob, typeof(String), "GetDB2Clob");
SetProviderField(DB2Types.DB2Binary, typeof(byte[]), "GetDB2Binary");
SetProviderField(DB2Types.DB2Blob, typeof(byte[]), "GetDB2Blob");
SetProviderField(DB2Types.DB2Date, typeof(DateTime), "GetDB2Date");
SetProviderField(DB2Types.DB2Time, typeof(TimeSpan), "GetDB2Time");
SetProviderField(DB2Types.DB2TimeStamp, typeof(DateTime), "GetDB2TimeStamp");
SetProviderField(DB2Types.DB2Xml, typeof(string), "GetDB2Xml");
SetProviderField(DB2Types.DB2RowId, typeof(byte[]), "GetDB2RowId");
MappingSchema.AddScalarType(DB2Types.DB2Int64, GetNullValue(DB2Types.DB2Int64), true, DataType.Int64);
MappingSchema.AddScalarType(DB2Types.DB2Int32, GetNullValue(DB2Types.DB2Int32), true, DataType.Int32);
MappingSchema.AddScalarType(DB2Types.DB2Int16, GetNullValue(DB2Types.DB2Int16), true, DataType.Int16);
MappingSchema.AddScalarType(DB2Types.DB2Decimal, GetNullValue(DB2Types.DB2Decimal), true, DataType.Decimal);
MappingSchema.AddScalarType(DB2Types.DB2DecimalFloat, GetNullValue(DB2Types.DB2DecimalFloat), true, DataType.Decimal);
MappingSchema.AddScalarType(DB2Types.DB2Real, GetNullValue(DB2Types.DB2Real), true, DataType.Single);
MappingSchema.AddScalarType(DB2Types.DB2Real370, GetNullValue(DB2Types.DB2Real370), true, DataType.Single);
MappingSchema.AddScalarType(DB2Types.DB2Double, GetNullValue(DB2Types.DB2Double), true, DataType.Double);
MappingSchema.AddScalarType(DB2Types.DB2String, GetNullValue(DB2Types.DB2String), true, DataType.NVarChar);
MappingSchema.AddScalarType(DB2Types.DB2Clob, GetNullValue(DB2Types.DB2Clob), true, DataType.NText);
MappingSchema.AddScalarType(DB2Types.DB2Binary, GetNullValue(DB2Types.DB2Binary), true, DataType.VarBinary);
MappingSchema.AddScalarType(DB2Types.DB2Blob, GetNullValue(DB2Types.DB2Blob), true, DataType.Blob);
MappingSchema.AddScalarType(DB2Types.DB2Date, GetNullValue(DB2Types.DB2Date), true, DataType.Date);
MappingSchema.AddScalarType(DB2Types.DB2Time, GetNullValue(DB2Types.DB2Time), true, DataType.Time);
MappingSchema.AddScalarType(DB2Types.DB2TimeStamp, GetNullValue(DB2Types.DB2TimeStamp), true, DataType.DateTime2);
MappingSchema.AddScalarType(DB2Types.DB2Xml, GetNullValue(DB2Types.DB2Xml), true, DataType.Xml);
MappingSchema.AddScalarType(DB2Types.DB2RowId, GetNullValue(DB2Types.DB2RowId), true, DataType.VarBinary);
_setBlob = GetSetParameter(connectionType, "DB2Parameter", "DB2Type", "DB2Type", "Blob");
if (DB2Types.DB2DateTime.IsSupported)
{
SetProviderField(DB2Types.DB2DateTime, typeof(DateTime), "GetDB2DateTime");
MappingSchema.AddScalarType(DB2Types.DB2DateTime, GetNullValue(DB2Types.DB2DateTime), true, DataType.DateTime);
}
if (DataConnection.TraceSwitch.TraceInfo)
{
DataConnection.WriteTraceLine(
DataReaderType.Assembly.FullName,
DataConnection.TraceSwitch.DisplayName);
DataConnection.WriteTraceLine(
DB2Types.DB2DateTime.IsSupported ? "DB2DateTime is supported." : "DB2DateTime is not supported.",
DataConnection.TraceSwitch.DisplayName);
}
DB2Tools.Initialized();
}
static object GetNullValue(Type type)
{
var getValue = Expression.Lambda<Func<object>>(Expression.Convert(Expression.Field(null, type, "Null"), typeof(object)));
return getValue.Compile()();
}
public override string ConnectionNamespace { get { return "IBM.Data.DB2"; } }
protected override string ConnectionTypeName { get { return "IBM.Data.DB2.DB2Connection, IBM.Data.DB2"; } }
protected override string DataReaderTypeName { get { return "IBM.Data.DB2.DB2DataReader, IBM.Data.DB2"; } }
public DB2Version Version { get; private set; }
static class MappingSchemaInstance
{
public static readonly DB2LUWMappingSchema DB2LUWMappingSchema = new DB2LUWMappingSchema();
public static readonly DB2zOSMappingSchema DB2zOSMappingSchema = new DB2zOSMappingSchema();
}
public override MappingSchema MappingSchema
{
get
{
switch (Version)
{
case DB2Version.LUW : return MappingSchemaInstance.DB2LUWMappingSchema;
case DB2Version.zOS : return MappingSchemaInstance.DB2zOSMappingSchema;
}
return base.MappingSchema;
}
}
public override ISchemaProvider GetSchemaProvider()
{
return Version == DB2Version.zOS ?
new DB2zOSSchemaProvider() :
new DB2LUWSchemaProvider();
}
public override ISqlBuilder CreateSqlBuilder()
{
return Version == DB2Version.zOS ?
new DB2zOSSqlBuilder(GetSqlOptimizer(), SqlProviderFlags, MappingSchema.ValueToSqlConverter) as ISqlBuilder:
new DB2LUWSqlBuilder(GetSqlOptimizer(), SqlProviderFlags, MappingSchema.ValueToSqlConverter);
}
readonly DB2SqlOptimizer _sqlOptimizer;
public override ISqlOptimizer GetSqlOptimizer()
{
return _sqlOptimizer;
}
public override void InitCommand(DataConnection dataConnection, CommandType commandType, string commandText, DataParameter[] parameters)
{
dataConnection.DisposeCommand();
base.InitCommand(dataConnection, commandType, commandText, parameters);
}
static Action<IDbDataParameter> _setBlob;
public override void SetParameter(IDbDataParameter parameter, string name, DataType dataType, object value)
{
if (value is sbyte)
{
value = (short)(sbyte)value;
dataType = DataType.Int16;
}
else if (value is byte)
{
value = (short)(byte)value;
dataType = DataType.Int16;
}
switch (dataType)
{
case DataType.UInt16 : dataType = DataType.Int32; break;
case DataType.UInt32 : dataType = DataType.Int64; break;
case DataType.UInt64 : dataType = DataType.Decimal; break;
case DataType.VarNumeric : dataType = DataType.Decimal; break;
case DataType.DateTime2 : dataType = DataType.DateTime; break;
case DataType.Char :
case DataType.VarChar :
case DataType.NChar :
case DataType.NVarChar :
if (value is Guid) value = ((Guid)value).ToString();
else if (value is bool)
value = Common.ConvertTo<char>.From((bool)value);
break;
case DataType.Boolean :
case DataType.Int16 :
if (value is bool)
{
value = (bool)value ? 1 : 0;
dataType = DataType.Int16;
}
break;
case DataType.Guid :
if (value is Guid)
{
value = ((Guid)value).ToByteArray();
dataType = DataType.VarBinary;
}
break;
case DataType.Binary :
case DataType.VarBinary :
if (value is Guid) value = ((Guid)value).ToByteArray();
break;
case DataType.Blob :
base.SetParameter(parameter, "@" + name, dataType, value);
_setBlob(parameter);
return;
}
base.SetParameter(parameter, "@" + name, dataType, value);
}
#region BulkCopy
DB2BulkCopy _bulkCopy;
public override BulkCopyRowsCopied BulkCopy<T>(DataConnection dataConnection, BulkCopyOptions options, IEnumerable<T> source)
{
if (_bulkCopy == null)
_bulkCopy = new DB2BulkCopy(GetConnectionType());
return _bulkCopy.BulkCopy(
options.BulkCopyType == BulkCopyType.Default ? DB2Tools.DefaultBulkCopyType : options.BulkCopyType,
dataConnection,
options,
source);
}
#endregion
#region Merge
public override int Merge<T>(DataConnection dataConnection, Expression<Func<T,bool>> deletePredicate, bool delete, IEnumerable<T> source)
{
if (delete)
throw new LinqToDBException("DB2 MERGE statement does not support DELETE by source.");
return new DB2Merge().Merge(dataConnection, deletePredicate, delete, source);
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="WindowPattern" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: Client-side wrapper for Window Pattern
//
// History:
// 06/23/2003 : BrendanM Ported to WCP
//
//---------------------------------------------------------------------------
using System;
using System.Windows.Automation.Provider;
using MS.Internal.Automation;
using System.Runtime.InteropServices;
namespace System.Windows.Automation
{
// Disable warning for obsolete types. These are scheduled to be removed in M8.2 so
// only need the warning to come out for components outside of APT.
#pragma warning disable 0618
///<summary>wrapper class for Window pattern </summary>
#if (INTERNAL_COMPILE)
internal class WindowPattern: BasePattern
#else
public class WindowPattern: BasePattern
#endif
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
private WindowPattern(AutomationElement el, SafePatternHandle hPattern, bool cached)
: base(el, hPattern)
{
_hPattern = hPattern;
_cached = cached;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Constants / Readonly Fields
//
//------------------------------------------------------
#region Public Constants and Readonly Fields
/// <summary>Returns the Window pattern identifier</summary>
public static readonly AutomationPattern Pattern = WindowPatternIdentifiers.Pattern;
/// <summary>Property ID: CanMaximize - </summary>
public static readonly AutomationProperty CanMaximizeProperty = WindowPatternIdentifiers.CanMaximizeProperty;
/// <summary>Property ID: CanMinimize - </summary>
public static readonly AutomationProperty CanMinimizeProperty = WindowPatternIdentifiers.CanMinimizeProperty;
/// <summary>Property ID: IsModal - Is this is a modal window</summary>
public static readonly AutomationProperty IsModalProperty = WindowPatternIdentifiers.IsModalProperty;
/// <summary>Property ID: WindowVisualState - Is the Window Maximized, Minimized, or Normal (aka restored)</summary>
public static readonly AutomationProperty WindowVisualStateProperty = WindowPatternIdentifiers.WindowVisualStateProperty;
/// <summary>Property ID: WindowInteractionState - Is the Window Closing, ReadyForUserInteraction, BlockedByModalWindow or NotResponding.</summary>
public static readonly AutomationProperty WindowInteractionStateProperty = WindowPatternIdentifiers.WindowInteractionStateProperty;
/// <summary>Property ID: - This window is always on top</summary>
public static readonly AutomationProperty IsTopmostProperty = WindowPatternIdentifiers.IsTopmostProperty;
/// <summary>Event ID: WindowOpened - Immediately after opening the window - ApplicationWindows or Window Status is not guarantee to be: ReadyForUserInteraction</summary>
public static readonly AutomationEvent WindowOpenedEvent = WindowPatternIdentifiers.WindowOpenedEvent;
/// <summary>Event ID: WindowClosed - Immediately after closing the window</summary>
public static readonly AutomationEvent WindowClosedEvent = WindowPatternIdentifiers.WindowClosedEvent;
#endregion Public Constants and Readonly Fields
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Changes the State of the window based on the passed enum.
/// </summary>
/// <param name="state">The requested state of the window.</param>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public void SetWindowVisualState( WindowVisualState state )
{
UiaCoreApi.WindowPattern_SetWindowVisualState(_hPattern, state);
}
/// <summary>
/// Non-blocking call to close this non-application window.
/// When called on a split pane, it will close the pane (thereby removing a
/// split), it may or may not also close all other panes related to the
/// document/content/etc. This behavior is application dependent.
/// </summary>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public void Close()
{
UiaCoreApi.WindowPattern_Close(_hPattern);
}
/// <summary>
/// Causes the calling code to block, waiting the specified number of milliseconds, for the
/// associated window to enter an idle state.
/// </summary>
/// <remarks>
/// The implementation is dependent on the underlying application framework therefore this
/// call may return sometime after the window is ready for user input. The calling code
/// should not rely on this call to understand exactly when the window has become idle.
///
/// For now this method works reliably for both WinFx and Win32 Windows that are starting
/// up. However, if called at other times on WinFx Windows (e.g. during a long layout)
/// WaitForInputIdle may return true before the Window is actually idle. Additional work
/// needs to be done to detect when WinFx Windows are idle.
/// </remarks>
/// <param name="milliseconds">The amount of time, in milliseconds, to wait for the
/// associated process to become idle. The maximum is the largest possible value of a
/// 32-bit integer, which represents infinity to the operating system
/// </param>
/// <returns>
/// returns true if the window has reached the idle state and false if the timeout occurred.
/// </returns>
public bool WaitForInputIdle( int milliseconds )
{
return UiaCoreApi.WindowPattern_WaitForInputIdle(_hPattern, milliseconds);
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// This member allows access to previously requested
/// cached properties for this element. The returned object
/// has accessors for each property defined for this pattern.
/// </summary>
/// <remarks>
/// Cached property values must have been previously requested
/// using a CacheRequest. If you try to access a cached
/// property that was not previously requested, an InvalidOperation
/// Exception will be thrown.
///
/// To get the value of a property at the current point in time,
/// access the property via the Current accessor instead of
/// Cached.
/// </remarks>
public WindowPatternInformation Cached
{
get
{
Misc.ValidateCached(_cached);
return new WindowPatternInformation(_el, true);
}
}
/// <summary>
/// This member allows access to current property values
/// for this element. The returned object has accessors for
/// each property defined for this pattern.
/// </summary>
/// <remarks>
/// This pattern must be from an AutomationElement with a
/// Full reference in order to get current values. If the
/// AutomationElement was obtained using AutomationElementMode.None,
/// then it contains only cached data, and attempting to get
/// the current value of any property will throw an InvalidOperationException.
///
/// To get the cached value of a property that was previously
/// specified using a CacheRequest, access the property via the
/// Cached accessor instead of Current.
/// </remarks>
public WindowPatternInformation Current
{
get
{
Misc.ValidateCurrent(_hPattern);
return new WindowPatternInformation(_el, false);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
internal static object Wrap(AutomationElement el, SafePatternHandle hPattern, bool cached)
{
return new WindowPattern(el, hPattern, cached);
}
#endregion Internal Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private SafePatternHandle _hPattern;
private bool _cached;
#endregion Private Fields
//------------------------------------------------------
//
// Nested Classes
//
//------------------------------------------------------
#region Nested Classes
/// <summary>
/// This class provides access to either Cached or Current
/// properties on a pattern via the pattern's .Cached or
/// .Current accessors.
/// </summary>
public struct WindowPatternInformation
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
internal WindowPatternInformation(AutomationElement el, bool useCache)
{
_el = el;
_useCache = useCache;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>Is this window Maximizable</summary>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public bool CanMaximize
{
get
{
return (bool)_el.GetPatternPropertyValue(CanMaximizeProperty, _useCache);
}
}
/// <summary>Is this window Minimizable</summary>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public bool CanMinimize
{
get
{
return (bool)_el.GetPatternPropertyValue(CanMinimizeProperty, _useCache);
}
}
/// <summary>Is this is a modal window.</summary>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public bool IsModal
{
get
{
return (bool)_el.GetPatternPropertyValue(IsModalProperty, _useCache);
}
}
/// <summary>Is the Window Maximized, Minimized, or Normal (aka restored)</summary>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public WindowVisualState WindowVisualState
{
get
{
return (WindowVisualState)_el.GetPatternPropertyValue(WindowVisualStateProperty, _useCache);
}
}
/// <summary>Is the Window Closing, ReadyForUserInteraction, BlockedByModalWindow or NotResponding.</summary>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public WindowInteractionState WindowInteractionState
{
get
{
return (WindowInteractionState)_el.GetPatternPropertyValue(WindowInteractionStateProperty, _useCache);
}
}
/// <summary>Is this window is always on top</summary>
///
/// <outside_see conditional="false">
/// This API does not work inside the secure execution environment.
/// <exception cref="System.Security.Permissions.SecurityPermission"/>
/// </outside_see>
public bool IsTopmost
{
get
{
return (bool)_el.GetPatternPropertyValue(IsTopmostProperty, _useCache);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
private AutomationElement _el; // AutomationElement that contains the cache or live reference
private bool _useCache; // true to use cache, false to use live reference to get current values
#endregion Private Fields
}
#endregion Nested Classes
}
}
| |
using System;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Coinbase.Models;
using Flurl;
using Flurl.Http;
using Flurl.Http.Configuration;
namespace Coinbase
{
public interface ICoinbaseClient : IFlurlClient
{
IAccountsEndpoint Accounts { get; }
IAddressesEndpoint Addresses { get; }
IBuysEndpoint Buys { get; }
IDataEndpoint Data { get; }
IDepositsEndpoint Deposits { get; }
INotificationsEndpoint Notifications { get; }
IPaymentMethodsEndpoint PaymentMethods { get; }
ISellsEndpoint Sells { get; }
ITransactionsEndpoint Transactions { get; }
IUsersEndpoint Users { get; }
IWithdrawalsEndpoint Withdrawals { get; }
}
public partial class CoinbaseClient : FlurlClient, ICoinbaseClient
{
public const string ApiVersionDate = "2017-08-07";
public Config Config { get; }
public const string Endpoint = "https://api.coinbase.com/v2/";
protected internal Url AccountsEndpoint => this.Config.ApiUrl.AppendPathSegment("accounts");
protected internal Url PaymentMethodsEndpoint => this.Config.ApiUrl.AppendPathSegment("payment-methods");
protected internal Url CurrenciesEndpoint => this.Config.ApiUrl.AppendPathSegment("currencies");
protected internal Url ExchangeRatesEndpoint => this.Config.ApiUrl.AppendPathSegment("exchange-rates");
protected internal Url PricesEndpoint => this.Config.ApiUrl.AppendPathSegment("prices");
protected internal Url TimeEndpoint => this.Config.ApiUrl.AppendPathSegment("time");
protected internal Url NotificationsEndpoint => this.Config.ApiUrl.AppendPathSegment("notifications");
/// <summary>
/// The main class for making Coinbase API calls.
/// </summary>
public CoinbaseClient(Config config = null)
{
this.Config = config ?? new Config();
this.Config.EnsureValid();
this.ConfigureClient();
}
internal static readonly string UserAgent =
$"{AssemblyVersionInformation.AssemblyProduct}/{AssemblyVersionInformation.AssemblyVersion} ({AssemblyVersionInformation.AssemblyTitle}; {AssemblyVersionInformation.AssemblyDescription})";
protected internal virtual void ConfigureClient()
{
this.WithHeader(HeaderNames.Version, ApiVersionDate)
.WithHeader("User-Agent", UserAgent);
this.Config.Configure(this);
}
public interface ICoinbaseApiClient : ICoinbaseClient
{
}
public class CoinbaseApiClient : CoinbaseClient, ICoinbaseApiClient
{
public CoinbaseApiClient(ApiKeyConfig config) : base(config)
{
}
}
public interface ICoinbaseOAuthClient : ICoinbaseClient
{
}
public class CoinbaseOAuthClient : CoinbaseClient, ICoinbaseOAuthClient
{
public CoinbaseOAuthClient(OAuthConfig config) : base(config)
{
}
}
/// <summary>
/// Enable HTTP debugging via Fiddler. Ensure Tools > Fiddler Options... > Connections is enabled and has a port configured.
/// Then, call this method with the following URL format: http://localhost.:PORT where PORT is the port number Fiddler proxy
/// is listening on. (Be sure to include the period after the localhost).
/// </summary>
/// <param name="proxyUrl">The full proxy URL Fiddler proxy is listening on. IE: http://localhost.:8888 - The period after localhost is important to include.</param>
public void EnableFiddlerDebugProxy(string proxyUrl)
{
var webProxy = new WebProxy(proxyUrl, BypassOnLocal: false);
this.Configure(settings =>
{
settings.HttpClientFactory = new DebugProxyFactory(webProxy);
});
}
private class DebugProxyFactory : DefaultHttpClientFactory
{
private readonly WebProxy proxy;
public DebugProxyFactory(WebProxy proxy)
{
this.proxy = proxy;
}
public override HttpMessageHandler CreateMessageHandler()
{
return new HttpClientHandler
{
Proxy = this.proxy,
UseProxy = true
};
}
}
/// <summary>
/// Get the next page of data given the current paginated response.
/// </summary>
/// <param name="currentPage">The current paged response.</param>
/// <returns>The next page of data.</returns>
public Task<PagedResponse<T>> GetNextPageAsync<T>(PagedResponse<T> currentPage, CancellationToken cancellationToken = default)
{
if( !currentPage.HasNextPage() ) throw new NullReferenceException("No next page.");
return GetPageAsync<T>(currentPage.Pagination.NextUri, cancellationToken);
}
///// <summary>
///// Get the previous page of data given the current pagination response.
///// </summary>
///// <param name="currentPage">The current paged response.</param>
///// <returns>The previous page of data.</returns>
//public Task<PagedResponse<T>> PreviousPageAsync<T>(PagedResponse<T> currentPage, CancellationToken cancellationToken = default)
//{
// if( !currentPage.HasPrevPage() ) throw new NullReferenceException("No previous page.");
// return GetPageAsync<T>(currentPage.Pagination.PreviousUri, cancellationToken);
//}
/// <summary>
/// Internally used for getting a next or previous page.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="pageUrl"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
protected internal Task<PagedResponse<T>> GetPageAsync<T>(string pageUrl, CancellationToken cancellationToken = default)
{
pageUrl = pageUrl.Remove(0, 4);
return (this.Config.ApiUrl + pageUrl)
.WithClient(this)
.GetJsonAsync<PagedResponse<T>>(cancellationToken);
}
/// <summary>
/// Captures the low-level <seealso cref="HttpResponseMessage" /> from a
/// underlying request. Useful in advanced scenarios where you
/// want to check HTTP headers, HTTP status code or
/// inspect the response body manually.
/// </summary>
/// <param name="responseGetter">A function that must be called to
/// retrieve the <seealso cref="HttpResponseMessage"/>
/// </param>
/// <returns>Returns the <seealso cref="HttpResponseMessage"/> of the
/// underlying HTTP request.</returns>
public CoinbaseClient HoistResponse(out Func<IFlurlResponse> responseGetter)
{
IFlurlResponse msg = null;
void CaptureResponse(FlurlCall http)
{
msg = http.Response;
this.Configure(cf =>
{
// Remove Action<HttpCall> from Invocation list
// to avoid memory leak from further calls to the same
// client object.
cf.AfterCall -= CaptureResponse;
});
}
this.Configure(cf =>
{
cf.AfterCall += CaptureResponse;
});
responseGetter = () => msg;
return this;
}
}
}
| |
using Microsoft.Xna.Framework.Graphics;
using xgc3.GameComponents;
using System; using System.Collections.Generic; using System.Text; using xgc3.Core; using xgc3.Resources; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace xgc3.Generated {public class GameInfo : xgc3.RuntimeEnv.BaseRuntimeEnvInstance {
public String Title;
public GameInfo() {
}
}
public class Sprite : xgc3.GameObjects.View {
public String AssetName;
public Texture2D Texture;
private void On_Create( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Sprite self = selfInstance as xgc3.Generated.Sprite;
Console.WriteLine( "Spite - Create");
string resource = self.Resource;
if (resource != null)
{
Texture2D texturePointer = self.GameMgr.Game.Content.Load<Texture2D>(resource);
self.Texture = texturePointer;
}
}
private void On_Destroy( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Sprite self = selfInstance as xgc3.Generated.Sprite;
Console.WriteLine( "Spite - Destroy");
// TODO: Test Leak cleanup
if (self.Texture != null)
{
self.Texture.Dispose();
self.Texture = null;
}
}
private void On_Draw( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Sprite self = selfInstance as xgc3.Generated.Sprite;
//Console.WriteLine( "Sprite - Draw");
string resource = self.Resource;
if (resource != null)
{
Vector2 p = new Vector2(self.X, self.Y);
self.GameMgr.Game.GameComponent.SpriteB.Draw(self.Texture, p, Color.White);
}
else
{
// When no sprite? Just draw name.
Vector2 p = new Vector2(self.X, self.Y);
self.GameMgr.Game.GameComponent.SpriteB.DrawString(self.GameMgr.Game.FontMgr.Courier, self.Name, p, Color.Red);
}
}
public Sprite() {
this.Create += On_Create;
this.Destroy += On_Destroy;
this.Draw += On_Draw;
}
}
public class Label : xgc3.GameObjects.View {
public String Text;
public Microsoft.Xna.Framework.Graphics.Color Color = Microsoft.Xna.Framework.Graphics.Color.Black;
private void On_Create( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Label self = selfInstance as xgc3.Generated.Label; Console.WriteLine( "Hello world!" + self.Name); }
private void On_Draw( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Label self = selfInstance as xgc3.Generated.Label;
Vector2 p = new Vector2(self.X, self.Y);
string text = self.Text;
if( text == null)
{
text = self.Name;
}
self.GameMgr.Game.GameComponent.SpriteB.DrawString(self.GameMgr.Game.FontMgr.Courier, text, p, self.Color);
}
public Label() {
this.Create += On_Create;
this.Draw += On_Draw;
}
}
public class FPS : xgc3.Generated.Label {
public string Format = "FPS: {0}";
private void On_Step( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.FPS self = selfInstance as xgc3.Generated.FPS;
xgc3.GameObjects.GameTimer gameTimer = other as xgc3.GameObjects.GameTimer;
this.Text = string.Format( this.Format, Math.Round( gameTimer.FPS, 2));
}
public FPS() {
this.Step += On_Step;
}
}
public class TextBox : xgc3.GameObjects.View {
public String Text;
public Microsoft.Xna.Framework.Graphics.Color Color = Microsoft.Xna.Framework.Graphics.Color.Pink;
public xgc3.GameComponents.ExtendedMouseButtonState MouseState;
private void On_Create( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.TextBox self = selfInstance as xgc3.Generated.TextBox; Console.WriteLine( "Hello world!" + self.Name); }
private void On_Draw( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.TextBox self = selfInstance as xgc3.Generated.TextBox;
Vector2 p = new Vector2(self.X, self.Y);
self.GameMgr.Game.GameComponent.SpriteB.DrawString(self.GameMgr.Game.FontMgr.Courier, self.Text, p, self.Color);
}
public TextBox() {
this.Create += On_Create;
this.Draw += On_Draw;
}
}
public class BaseComponent : xgc3.GameObjects.View {
protected Boolean _enabled = true;
public Boolean Clickable = true;
public BaseComponent() {
}
}
public class Button : xgc3.Generated.BaseComponent {
public xgc3.Resources.SpriteResource Resource;
public Boolean Focusable = false;
public Boolean _msdown = false;
public Boolean _msin = false;
public String Text;
public Microsoft.Xna.Framework.Graphics.Color Color;
static public xgc3.Resources.SpriteResource normal = new xgc3.Resources.SpriteResource( "normal", "button_normal");static public xgc3.Resources.SpriteResource down = new xgc3.Resources.SpriteResource( "down", "button_down");static public xgc3.Resources.SpriteResource over = new xgc3.Resources.SpriteResource( "over", "button_over");static public xgc3.Resources.SpriteResource disabled = new xgc3.Resources.SpriteResource( "disabled", "button_disabled");public void On_Click( xgc3.Core.Instance self, xgc3.Core.Instance other, String extra)
{}
public event EventDelegate Click;
public void Raise_Click(Instance self, Instance other, string extra)
{ if (Click != null) { Click(self, other, extra); }}
public void _callShow()
{
if ( this._msdown && this._msin ) this.ShowDown();
else if ( this._msin ) this.ShowOver();
else this.ShowUp();
}
public void DoSpaceDown()
{
if ( this._enabled) {
this.ShowDown();
}
}
public void DoSpaceUp()
{
if ( this._enabled) {
this.Raise_Click( this, null, null);
this.ShowUp();
}
}
public void DoEnterDown()
{
if ( this._enabled ){
this.ShowDown( );
}
}
public void DoEnterUp()
{
if ( this._enabled ){
this.Raise_Click( this, null, null);
this.ShowUp( );
}
}
public void _showEnabled()
{
this.Clickable = _enabled;
ShowUp();
}
public void ShowDown()
{
this.Resource = down;
}
public void ShowUp()
{
if (!_enabled )
{
this.Resource = disabled;
}
else
{
this.Resource = normal;
}
}
public void ShowOver()
{
this.Resource = over;
}
private void On_MouseOver( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Button self = selfInstance as xgc3.Generated.Button;
this._msin = true;
this._callShow();
}
private void On_MouseOut( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Button self = selfInstance as xgc3.Generated.Button;
this._msin = false;
this._callShow();
}
private void On_LeftMouseDown( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Button self = selfInstance as xgc3.Generated.Button;
this._msdown = true;
this._callShow();
}
private void On_LeftMouseUp( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Button self = selfInstance as xgc3.Generated.Button;
this._msdown = false;
this._callShow();
this.Raise_Click( this, null, null);
}
private void On_Create( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Button self = selfInstance as xgc3.Generated.Button;
Console.WriteLine( "Sprite - Create");
this.Resource = normal;
}
private void On_Destroy( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Button self = selfInstance as xgc3.Generated.Button;
Console.WriteLine( "Sprite - Destroy");
// TODO - Free up resources?
}
private void On_Draw( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Button self = selfInstance as xgc3.Generated.Button;
//Console.WriteLine( "Sprite - Draw");
if (self.Resource != null)
{
Vector2 p = new Vector2(self.X, self.Y);
// Scale button graphic...
DrawTiledTexture( self.GameMgr.Game.GameComponent.SpriteB, self.Resource.GetTexture( self.GameMgr), self.X, self.Y, self.Width, self.Height, Color.White, 5);
// Now, draw the text inside the button.
Rectangle textBounds;
Rectangle r = new Rectangle( self.X, self.Y, self.Width, self.Height);
DrawString( self.GameMgr.Game.GameComponent.SpriteB, self.GameMgr.Game.FontMgr.Courier, self.Text, r,
Color.Black, TextAlignment.Middle, true, new Vector2(0,0), out textBounds);
}
else
{
// When no resource, Just draw name.
Vector2 p = new Vector2(self.X, self.Y);
self.GameMgr.Game.GameComponent.SpriteB.DrawString(self.GameMgr.Game.FontMgr.Courier, self.Name, p, Color.Red);
}
}
public Button() {
this.Click += On_Click;
this.MouseOver += On_MouseOver;
this.MouseOut += On_MouseOut;
this.LeftMouseDown += On_LeftMouseDown;
this.LeftMouseUp += On_LeftMouseUp;
this.Create += On_Create;
this.Destroy += On_Destroy;
this.Draw += On_Draw;
}
}
public class Test : xgc3.Core.Instance {
private void On_Create( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Test self = selfInstance as xgc3.Generated.Test; Console.WriteLine( "Hello world!"); }
public Test() {
this.Create += On_Create;
}
}
public class Application_GameObjects : xgc3.RuntimeEnv.Application {
public Application_GameObjects() {}
public class StyleSheet_Sheet1 : xgc3.RuntimeEnv.StyleSheet {
public StyleSheet_Sheet1() {}
public class Selector_D8F7907EFEA57020C16E3E1698D4F3D4 : xgc3.RuntimeEnv.Selector {
public Selector_D8F7907EFEA57020C16E3E1698D4F3D4() {}
}
public class Selector_9AE55BF7AD6697C903DBA5F7C073B10E : xgc3.RuntimeEnv.Selector {
public Selector_9AE55BF7AD6697C903DBA5F7C073B10E() {}
public class StyleAttribute_DE918806BBFCC9A84171C1243B06A0DA : xgc3.RuntimeEnv.StyleAttribute {
public StyleAttribute_DE918806BBFCC9A84171C1243B06A0DA() {}
}
}
public class Selector_68E92007D6A6BDC06086AA9AAFDE9DAD : xgc3.RuntimeEnv.Selector {
public Selector_68E92007D6A6BDC06086AA9AAFDE9DAD() {}
public class StyleAttribute_804C3F4AACC5696633A0DC41019F2C96 : xgc3.RuntimeEnv.StyleAttribute {
public StyleAttribute_804C3F4AACC5696633A0DC41019F2C96() {}
}
public class StyleAttribute_0D69810C013E61C837891296A4B752C7 : xgc3.RuntimeEnv.StyleAttribute {
public StyleAttribute_0D69810C013E61C837891296A4B752C7() {}
}
}
}
public class GameInfo_GameInfo : xgc3.Generated.GameInfo {
public GameInfo_GameInfo() {}
private new void On_Create( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Application_GameObjects.GameInfo_GameInfo self = selfInstance as xgc3.Generated.Application_GameObjects.GameInfo_GameInfo; Console.WriteLine( "Hello world!"); }
}
public class SpriteResource_flower : xgc3.Resources.SpriteResource {
public SpriteResource_flower() {}
}
public class Room_Editor : xgc3.GameObjects.Room {
public Room_Editor() {}
private new void On_Create( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Application_GameObjects.Room_Editor self = selfInstance as xgc3.Generated.Application_GameObjects.Room_Editor; Console.WriteLine( "Hello world!"); }
public String Test;
public void Foo( )
{ { Console.WriteLine( "dog"); return;} }
private void On_BarEvent( xgc3.Core.Instance self, xgc3.Core.Instance other, String extra)
{ Console.WriteLine( "Hello world!"); }
public event EventDelegate BarEvent;
public void Raise_BarEvent(Instance self, Instance other, string extra)
{ if (BarEvent != null) { BarEvent(self, other, extra); }}
public class Sprite_flower3 : xgc3.Generated.Sprite {
public Sprite_flower3() {}
private new void On_Create( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Application_GameObjects.Room_Editor.Sprite_flower3 self = selfInstance as xgc3.Generated.Application_GameObjects.Room_Editor.Sprite_flower3; Console.WriteLine( "Hello world!" + self.Name); }
private new void On_Step( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Application_GameObjects.Room_Editor.Sprite_flower3 self = selfInstance as xgc3.Generated.Application_GameObjects.Room_Editor.Sprite_flower3; self.X = self.X+1; if( self.X > 200) { self.X = 0;} }
}
public class TextBox_flower4 : xgc3.Generated.TextBox {
public TextBox_flower4() {}
private new void On_Create( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Application_GameObjects.Room_Editor.TextBox_flower4 self = selfInstance as xgc3.Generated.Application_GameObjects.Room_Editor.TextBox_flower4; Console.WriteLine( "Hello world!" + self.Name); }
private new void On_Step( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Application_GameObjects.Room_Editor.TextBox_flower4 self = selfInstance as xgc3.Generated.Application_GameObjects.Room_Editor.TextBox_flower4; self.Y = self.Y+1; if( self.Y > 200) { self.Y = 0;} }
}
public class Button_Button1 : xgc3.Generated.Button {
public Button_Button1() {}
private new void On_Click( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Application_GameObjects.Room_Editor.Button_Button1 self = selfInstance as xgc3.Generated.Application_GameObjects.Room_Editor.Button_Button1; Console.WriteLine("Button click!"); }
}
public class Label_Label1 : xgc3.Generated.Label {
public Label_Label1() {}
}
public class FPS_FramesPerSecond : xgc3.Generated.FPS {
public FPS_FramesPerSecond() {}
}
public class TextBox_TextBox1 : xgc3.Generated.TextBox {
public TextBox_TextBox1() {}
private new void On_Draw( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Application_GameObjects.Room_Editor.TextBox_TextBox1 self = selfInstance as xgc3.Generated.Application_GameObjects.Room_Editor.TextBox_TextBox1;
Vector2 p = new Vector2(self.X, self.Y);
self.GameMgr.Game.GameComponent.SpriteB.DrawString(self.GameMgr.Game.FontMgr.Courier, self.Text, p, self.Color);
}
}
}
public class Room_Editor2 : xgc3.Generated.Application_GameObjects.Room_Editor {
public Room_Editor2() {}
private new void On_Create( xgc3.Core.Instance selfInstance, xgc3.Core.Instance other, String extra)
{ xgc3.Generated.Application_GameObjects.Room_Editor2 self = selfInstance as xgc3.Generated.Application_GameObjects.Room_Editor2; Console.WriteLine( "Hello world!"); }
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using Azure.Core.TestFramework;
using Azure.Media.VideoAnalyzer.Edge.Models;
using Microsoft.Azure.Devices;
using NUnit.Framework;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using System.IO;
using System.Text;
using Azure.Core;
using System.Linq;
namespace Azure.Media.VideoAnalyzer.Edge.Samples
{
public class LiveVideoAnalyzerSample
{
private ServiceClient _serviceClient;
private RegistryManager _registryManager;
private string _deviceId = System.Environment.GetEnvironmentVariable("iothub_deviceid", EnvironmentVariableTarget.User);
private string _moduleId = System.Environment.GetEnvironmentVariable("iothub_moduleid", EnvironmentVariableTarget.User);
public LiveVideoAnalyzerSample()
{
#region Snippet:Azure_VideoAnalyzerSamples_ConnectionString
string connectionString = System.Environment.GetEnvironmentVariable("iothub_connectionstring", EnvironmentVariableTarget.User);
var serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
#endregion Snippet:Azure_VideoAnalyzerSamples_ConnectionString
_serviceClient = serviceClient;
_registryManager = RegistryManager.CreateFromConnectionString(connectionString);
}
[Test]
public async Task SendRequests()
{
try
{
//create a pipeline topology and live pipeline
var pipelineTopology = BuildPipelineTopology();
var livePipeline = BuildLivePipeline(pipelineTopology.Name);
//set topology without using helper function
#region Snippet:Azure_VideoAnalyzerSamples_InvokeDirectMethod
var setPipelineTopRequest = new PipelineTopologySetRequest(pipelineTopology);
var directMethod = new CloudToDeviceMethod(setPipelineTopRequest.MethodName);
directMethod.SetPayloadJson(setPipelineTopRequest.GetPayloadAsJson());
var setPipelineTopResponse = await _serviceClient.InvokeDeviceMethodAsync(_deviceId, _moduleId, directMethod);
#endregion Snippet:Azure_VideoAnalyzerSamples_InvokeDirectMethod
// get a topology using helper function
var getPipelineTopRequest = await InvokeDirectMethodHelper(new PipelineTopologyGetRequest(pipelineTopology.Name));
var getPipelineTopResponse = PipelineTopology.Deserialize(getPipelineTopRequest.GetPayloadAsJson());
// list all topologies
var listPipelineTopRequest = await InvokeDirectMethodHelper(new PipelineTopologyListRequest());
var listPipelineTopResponse = PipelineTopologyCollection.Deserialize(listPipelineTopRequest.GetPayloadAsJson());
//set live pipeline
var setLivePipelineRequest = await InvokeDirectMethodHelper(new LivePipelineSetRequest(livePipeline));
//activate live pipeline
var activateLivePipelineRequest = await InvokeDirectMethodHelper(new LivePipelineActivateRequest(livePipeline.Name));
//get live pipeline
var getLivePipelineRequest = await InvokeDirectMethodHelper(new LivePipelineGetRequest(livePipeline.Name));
var getLivePipelineResponse = LivePipeline.Deserialize(getLivePipelineRequest.GetPayloadAsJson());
// list all live pipeline
var listLivePipelineRequest = await InvokeDirectMethodHelper(new LivePipelineListRequest());
var listLivePipelineResponse = LivePipelineCollection.Deserialize(listLivePipelineRequest.GetPayloadAsJson());
//getlive pipeline
var deactiveLivePipeline = await InvokeDirectMethodHelper(new LivePipelineDeactivateRequest(livePipeline.Name));
var deleteLivePipeline = await InvokeDirectMethodHelper(new LivePipelineDeleteRequest(livePipeline.Name));
//delete live pipeline
var deletePipelineTopology = await InvokeDirectMethodHelper(new PipelineTopologyDeleteRequest(pipelineTopology.Name));
//get an onvif device
var onvifDeviceGetRequest = await InvokeDirectMethodHelper(new OnvifDeviceGetRequest(new UnsecuredEndpoint("rtsp://camerasimulator:8554")));
var onvifDeviceGetResponse = OnvifDevice.Deserialize(onvifDeviceGetRequest.GetPayloadAsJson());
//get all onvif devices on the network
var onvifDiscoverRequest = await InvokeDirectMethodHelper(new OnvifDeviceDiscoverRequest());
var onvifDiscoverResponse = DiscoveredOnvifDeviceCollection.Deserialize(onvifDiscoverRequest.GetPayloadAsJson());
// create a remote device adapter and send a set request for it
var iotDeviceName = "iotDeviceSample";
var remoteDeviceName = "remoteDeviceSample";
var iotDevice = await GetOrAddIoTDeviceAsync(iotDeviceName);
var remoteDeviceAdapter = CreateRemoteDeviceAdapter(remoteDeviceName, iotDeviceName, iotDevice.Authentication.SymmetricKey.PrimaryKey);
var remoteDeviceAdapterSetRequest = await InvokeDirectMethodHelper(new RemoteDeviceAdapterSetRequest(remoteDeviceAdapter));
var remoteDeviceAdapterSetResponse = RemoteDeviceAdapter.Deserialize(remoteDeviceAdapterSetRequest.GetPayloadAsJson());
//get a remote device adapter
var remoteDeviceAdapterGetRequest = await InvokeDirectMethodHelper(new RemoteDeviceAdapterGetRequest(remoteDeviceName));
var remoteDeviceAdapterGetResponse = RemoteDeviceAdapter.Deserialize(remoteDeviceAdapterGetRequest.GetPayloadAsJson());
//list all remote device adapters
var remoteDeviceAdapterListRequest = await InvokeDirectMethodHelper(new RemoteDeviceAdapterListRequest());
var remoteDeviceAdapterListResponse = RemoteDeviceAdapterCollection.Deserialize(remoteDeviceAdapterListRequest.GetPayloadAsJson());
//delete a remote device adapater
var remoteDeviceAdapterDeleteRequest = await InvokeDirectMethodHelper(new RemoteDeviceAdapterDeleteRequest(remoteDeviceName));
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Assert.Fail();
}
}
private async Task<CloudToDeviceMethodResult> InvokeDirectMethodHelper(MethodRequest bc)
{
var directMethod = new CloudToDeviceMethod(bc.MethodName);
directMethod.SetPayloadJson(bc.GetPayloadAsJson());
return await _serviceClient.InvokeDeviceMethodAsync(_deviceId, _moduleId, directMethod);
}
protected async Task<Device> GetOrAddIoTDeviceAsync(string iotDeviceName)
{
var iotDevice = await _registryManager.GetDeviceAsync(iotDeviceName);
if (iotDevice == null)
{
iotDevice = await _registryManager.AddDeviceAsync(new Device(iotDeviceName));
}
return iotDevice;
}
private RemoteDeviceAdapter CreateRemoteDeviceAdapter(string deviceProxyName, string iotDeviceName, string symmetricKey)
{
var targetHost = new Uri("rtsp://camerasimulator:8554").Host;
return new RemoteDeviceAdapter(deviceProxyName)
{
Properties = new RemoteDeviceAdapterProperties(
new RemoteDeviceAdapterTarget(targetHost),
new IotHubDeviceConnection(iotDeviceName)
{
Credentials = new SymmetricKeyCredentials(symmetricKey),
})
{
Description = "description",
},
};
}
private LivePipeline BuildLivePipeline(string topologyName)
{
#region Snippet:Azure_VideoAnalyzerSamples_BuildLivePipeline
var livePipelineProps = new LivePipelineProperties
{
Description = "Sample description",
TopologyName = topologyName,
};
livePipelineProps.Parameters.Add(new ParameterDefinition("rtspUrl", "rtsp://sample.com"));
return new LivePipeline("livePIpeline")
{
Properties = livePipelineProps
};
#endregion Snippet:Azure_VideoAnalyzerSamples_BuildLivePipeline
}
private PipelineTopology BuildPipelineTopology()
{
#region Snippet:Azure_VideoAnalyzerSamples_BuildPipelineTopology
var pipelineTopologyProps = new PipelineTopologyProperties
{
Description = "Continuous video recording to a Video Analyzer video",
};
SetParameters(pipelineTopologyProps);
SetSources(pipelineTopologyProps);
SetSinks(pipelineTopologyProps);
return new PipelineTopology("ContinuousRecording")
{
Properties = pipelineTopologyProps
};
#endregion Snippet:Azure_VideoAnalyzerSamples_BuildPipelineTopology
}
// Add parameters to Topology
private void SetParameters(PipelineTopologyProperties pipelineTopologyProperties)
{
#region Snippet:Azure_VideoAnalyzerSamples_SetParameters
pipelineTopologyProperties.Parameters.Add(new ParameterDeclaration("rtspUserName", ParameterType.String)
{
Description = "rtsp source user name.",
Default = "exampleUserName"
});
pipelineTopologyProperties.Parameters.Add(new ParameterDeclaration("rtspPassword", ParameterType.SecretString)
{
Description = "rtsp source password.",
Default = "examplePassword"
});
pipelineTopologyProperties.Parameters.Add(new ParameterDeclaration("rtspUrl", ParameterType.String)
{
Description = "rtsp Url"
});
#endregion Snippet:Azure_VideoAnalyzerSamples_SetParameters
}
// Add sources to Topology
private void SetSources(PipelineTopologyProperties pipelineTopologyProps)
{
#region Snippet:Azure_VideoAnalyzerSamples_SetSourcesSinks1
pipelineTopologyProps.Sources.Add(new RtspSource("rtspSource", new UnsecuredEndpoint("${rtspUrl}")
{
Credentials = new UsernamePasswordCredentials("${rtspUserName}", "${rtspPassword}")
})
);
#endregion Snippet:Azure_VideoAnalyzerSamples_SetSourcesSinks1
}
// Add sinks to Topology
private void SetSinks(PipelineTopologyProperties pipelineTopologyProps)
{
#region Snippet:Azure_VideoAnalyzerSamples_SetSourcesSinks2
var nodeInput = new List<NodeInput>
{
new NodeInput("rtspSource")
};
pipelineTopologyProps.Sinks.Add(new VideoSink("videoSink", nodeInput, "video", "/var/lib/videoanalyzer/tmp/", "1024"));
#endregion Snippet:Azure_VideoAnalyzerSamples_SetSourcesSinks2
}
}
}
| |
// 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.
using System.IO;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.Xml;
using System.Security.Cryptography.X509Certificates;
using Xunit;
using Test.Cryptography;
using System.Security.Cryptography.Pkcs.Tests;
namespace System.Security.Cryptography.Pkcs.EnvelopedCmsTests.Tests
{
public static partial class EdgeCasesTests
{
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void ImportEdgeCase()
{
//
// Pfx's imported into a certificate collection propagate their "delete on Dispose" behavior to its cloned instances:
// a subtle difference from Pfx's created using the X509Certificate2 constructor that can lead to premature or
// double key deletion. Since EnvelopeCms.Decrypt() has no legitimate reason to clone the extraStore certs, this shouldn't
// be a problem, but this test will verify that it isn't.
//
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e"
+ "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c"
+ "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4"
+ "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d"
+ "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.LoadPfxUsingCollectionImport())
{
X509Certificate2Collection extraStore = new X509Certificate2Collection(cert);
ecms.Decrypt(extraStore);
byte[] expectedContent = { 1, 2, 3 };
ContentInfo contentInfo = ecms.ContentInfo;
Assert.Equal<byte>(expectedContent, contentInfo.Content);
}
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void ImportEdgeCaseSki()
{
byte[] encodedMessage =
("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158"
+ "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83"
+ "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46"
+ "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba"
+ "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.LoadPfxUsingCollectionImport())
{
X509Certificate2Collection extraStore = new X509Certificate2Collection(cert);
ecms.Decrypt(extraStore);
byte[] expectedContent = { 1, 2, 3 };
ContentInfo contentInfo = ecms.ContentInfo;
Assert.Equal<byte>(new byte[] { 1, 2, 3 }, contentInfo.Content);
Assert.Equal<byte>(expectedContent, contentInfo.Content);
}
}
private static X509Certificate2 LoadPfxUsingCollectionImport(this CertLoader certLoader)
{
byte[] pfxData = certLoader.PfxData;
string password = certLoader.Password;
X509Certificate2Collection collection = new X509Certificate2Collection();
collection.Import(pfxData, password, X509KeyStorageFlags.DefaultKeySet);
Assert.Equal(1, collection.Count);
return collection[0];
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void ZeroLengthContent_RoundTrip()
{
ContentInfo contentInfo = new ContentInfo(Array.Empty<byte>());
EnvelopedCms ecms = new EnvelopedCms(contentInfo);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
CmsRecipient cmsRecipient = new CmsRecipient(cert);
try
{
ecms.Encrypt(cmsRecipient);
}
catch (CryptographicException) when (PlatformDetection.IsFullFramework) // Expected on full FX
{
}
}
byte[] encodedMessage = ecms.Encode();
ValidateZeroLengthContent(encodedMessage);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void ZeroLengthContent_FixedValue()
{
byte[] encodedMessage =
("3082010406092a864886f70d010703a081f63081f30201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d010101050004818009"
+ "c16b674495c2c3d4763189c3274cf7a9142fbeec8902abdc9ce29910d541df910e029a31443dc9a9f3b05f02da1c38478c40"
+ "0261c734d6789c4197c20143c4312ceaa99ecb1849718326d4fc3b7fbb2d1d23281e31584a63e99f2c17132bcd8eddb63296"
+ "7125cd0a4baa1efa8ce4c855f7c093339211bdf990cef5cce6cd74302306092a864886f70d010701301406082a864886f70d"
+ "03070408779b3de045826b188000").HexToByteArray();
ValidateZeroLengthContent(encodedMessage);
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void Rc4AndCngWrappersDontMixTest()
{
//
// Combination of RC4 over a CAPI certificate.
//
// This works as long as the PKCS implementation opens the cert using CAPI. If he creates a CNG wrapper handle (by passing CRYPT_ACQUIRE_PREFER_NCRYPT_KEY_FLAG),
// the test fails with a NOTSUPPORTED crypto exception inside Decrypt(). The same happens if the key is genuinely CNG.
//
byte[] content = { 6, 3, 128, 33, 44 };
AlgorithmIdentifier rc4 = new AlgorithmIdentifier(new Oid(Oids.Rc4));
EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(content), rc4);
CmsRecipientCollection recipients = new CmsRecipientCollection(new CmsRecipient(Certificates.RSAKeyTransferCapi1.GetCertificate()));
ecms.Encrypt(recipients);
byte[] encodedMessage = ecms.Encode();
ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
// In order to actually use the CAPI version of the key, perphemeral loading must be specified.
using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.CloneAsPerphemeralLoader().TryGetCertificateWithPrivateKey())
{
if (cert == null)
return; // Sorry - CertLoader is not configured to load certs with private keys - we've tested as much as we can.
X509Certificate2Collection extraStore = new X509Certificate2Collection();
extraStore.Add(cert);
ecms.Decrypt(extraStore);
}
ContentInfo contentInfo = ecms.ContentInfo;
Assert.Equal<byte>(content, contentInfo.Content);
}
private static void ValidateZeroLengthContent(byte[] encodedMessage)
{
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey())
{
if (cert == null)
return;
X509Certificate2Collection extraStore = new X509Certificate2Collection(cert);
ecms.Decrypt(extraStore);
ContentInfo contentInfo = ecms.ContentInfo;
byte[] content = contentInfo.Content;
int expected = PlatformDetection.IsFullFramework ? 6 : 0; // Desktop bug gives 6
Assert.Equal(expected, content.Length);
}
}
[Fact]
public static void ReuseEnvelopeCmsEncodeThenDecode()
{
// Test ability to encrypt, encode and decode all in one EnvelopedCms instance.
ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 });
EnvelopedCms ecms = new EnvelopedCms(contentInfo);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
CmsRecipient cmsRecipient = new CmsRecipient(cert);
ecms.Encrypt(cmsRecipient);
}
byte[] encodedMessage = ecms.Encode();
ecms.Decode(encodedMessage);
RecipientInfoCollection recipients = ecms.RecipientInfos;
Assert.Equal(1, recipients.Count);
RecipientInfo recipientInfo = recipients[0];
KeyTransRecipientInfo recipient = recipientInfo as KeyTransRecipientInfo;
Assert.NotNull(recipientInfo);
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
object value = subjectIdentifier.Value;
Assert.True(value is X509IssuerSerial);
X509IssuerSerial xis = (X509IssuerSerial)value;
Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName);
Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber);
}
[Fact]
public static void ReuseEnvelopeCmsDecodeThenEncode()
{
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e"
+ "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c"
+ "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4"
+ "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d"
+ "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
CmsRecipient cmsRecipient = new CmsRecipient(cert);
ecms.Encrypt(cmsRecipient);
}
encodedMessage = ecms.Encode();
ecms.Decode(encodedMessage);
RecipientInfoCollection recipients = ecms.RecipientInfos;
Assert.Equal(1, recipients.Count);
RecipientInfo recipientInfo = recipients[0];
KeyTransRecipientInfo recipient = recipientInfo as KeyTransRecipientInfo;
Assert.NotNull(recipientInfo);
SubjectIdentifier subjectIdentifier = recipient.RecipientIdentifier;
object value = subjectIdentifier.Value;
Assert.True(value is X509IssuerSerial);
X509IssuerSerial xis = (X509IssuerSerial)value;
Assert.Equal("CN=RSAKeyTransfer1", xis.IssuerName);
Assert.Equal("31D935FB63E8CFAB48A0BF7B397B67C0", xis.SerialNumber);
}
[Fact]
public static void EnvelopedCmsNullContent()
{
object ignore;
Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(null));
Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(null, new AlgorithmIdentifier(new Oid(Oids.TripleDesCbc))));
}
[Fact]
public static void EnvelopedCmsNullAlgorithm()
{
object ignore;
ContentInfo contentInfo = new ContentInfo(new byte[3]);
Assert.Throws<ArgumentNullException>(() => ignore = new EnvelopedCms(contentInfo, null));
}
[Fact]
public static void EnvelopedCmsEncryptWithNullRecipient()
{
EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3]));
Assert.Throws<ArgumentNullException>(() => ecms.Encrypt((CmsRecipient)null));
}
[Fact]
public static void EnvelopedCmsEncryptWithNullRecipients()
{
EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3]));
Assert.Throws<ArgumentNullException>(() => ecms.Encrypt((CmsRecipientCollection)null));
}
[Fact]
// On the desktop, this throws up a UI for the user to select a recipient. We don't support that.
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public static void EnvelopedCmsEncryptWithZeroRecipients()
{
EnvelopedCms ecms = new EnvelopedCms(new ContentInfo(new byte[3]));
Assert.Throws<PlatformNotSupportedException>(() => ecms.Encrypt(new CmsRecipientCollection()));
}
[Fact]
public static void EnvelopedCmsNullDecode()
{
EnvelopedCms ecms = new EnvelopedCms();
Assert.Throws<ArgumentNullException>(() => ecms.Decode(null));
}
[Fact]
public static void EnvelopedCmsDecryptNullary()
{
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e"
+ "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c"
+ "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4"
+ "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d"
+ "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt());
}
[Fact]
public static void EnvelopedCmsDecryptNullRecipient()
{
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e"
+ "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c"
+ "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4"
+ "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d"
+ "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
RecipientInfo recipientInfo = null;
X509Certificate2Collection extraStore = new X509Certificate2Collection();
Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo));
Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo, extraStore));
}
[Fact]
public static void EnvelopedCmsDecryptNullExtraStore()
{
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e"
+ "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c"
+ "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4"
+ "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d"
+ "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
RecipientInfo recipientInfo = ecms.RecipientInfos[0];
X509Certificate2Collection extraStore = null;
Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(extraStore));
Assert.Throws<ArgumentNullException>(() => ecms.Decrypt(recipientInfo, extraStore));
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void EnvelopedCmsDecryptWithoutMatchingCert()
{
// You don't have the private key? No message for you.
// This is the private key that "we don't have." We want to force it to load anyway, though, to trigger
// the "fail the test due to bad machine config" exception if someone left this cert in the MY store check.
using (X509Certificate2 ignore = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey())
{ }
byte[] encodedMessage =
("3082010c06092a864886f70d010703a081fe3081fb0201003181c83081c5020100302e301a311830160603550403130f5253"
+ "414b65795472616e7366657231021031d935fb63e8cfab48a0bf7b397b67c0300d06092a864886f70d01010105000481805e"
+ "bb2d08773594be9ec5d30c0707cf339f2b982a4f0797b74d520a0c973d668a9a6ad9d28066ef36e5b5620fef67f4d79ee50c"
+ "25eb999f0c656548347d5676ac4b779f8fce2b87e6388fbe483bb0fcf78ab1f1ff29169600401fded7b2803a0bf96cc160c4"
+ "96726216e986869eed578bda652855c85604a056201538ee56b6c4302b06092a864886f70d010701301406082a864886f70d"
+ "030704083adadf63cd297a86800835edc437e31d0b70").HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
RecipientInfo recipientInfo = ecms.RecipientInfos[0];
X509Certificate2Collection extraStore = new X509Certificate2Collection();
Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo));
Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(extraStore));
Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo, extraStore));
}
[Fact]
[OuterLoop(/* Leaks key on disk if interrupted */)]
public static void EnvelopedCmsDecryptWithoutMatchingCertSki()
{
// You don't have the private key? No message for you.
// This is the private key that "we don't have." We want to force it to load anyway, though, to trigger
// the "fail the test due to bad machine config" exception if someone left this cert in the MY store check.
using (X509Certificate2 ignore = Certificates.RSAKeyTransfer1.TryGetCertificateWithPrivateKey())
{ }
byte[] encodedMessage =
("3081f206092a864886f70d010703a081e43081e10201023181ae3081ab0201028014f2008aa9fa3742e8370cb1674ce1d158"
+ "2921dcc3300d06092a864886f70d01010105000481804336e978bc72ba2f5264cd854867fac438f36f2b3df6004528f2df83"
+ "4fb2113d6f7c07667e7296b029756222d6ced396a8fffed32be838eec7f2e54b9467fa80f85d097f7d1f0fbde57e07ab3d46"
+ "a60b31f37ef9844dcab2a8eef4fec5579fac5ec1e7ee82409898e17d30c3ac1a407fca15d23c9df2904a707294d78d4300ba"
+ "302b06092a864886f70d010701301406082a864886f70d03070408355c596e3e8540608008f1f811e862e51bbd").HexToByteArray();
EnvelopedCms ecms = new EnvelopedCms();
ecms.Decode(encodedMessage);
RecipientInfo recipientInfo = ecms.RecipientInfos[0];
X509Certificate2Collection extraStore = new X509Certificate2Collection();
Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo));
Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(extraStore));
Assert.ThrowsAny<CryptographicException>(() => ecms.Decrypt(recipientInfo, extraStore));
}
[Fact]
public static void AlgorithmIdentifierNullaryCtor()
{
AlgorithmIdentifier a = new AlgorithmIdentifier();
Assert.Equal(Oids.TripleDesCbc, a.Oid.Value);
Assert.Equal(0, a.KeyLength);
}
[Fact]
public static void CmsRecipient1AryCtor()
{
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
CmsRecipient r = new CmsRecipient(cert);
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, r.RecipientIdentifierType);
Assert.Same(cert, r.Certificate);
}
}
[Fact]
public static void CmsRecipientPassUnknown()
{
using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate())
{
CmsRecipient r = new CmsRecipient(SubjectIdentifierType.Unknown, cert);
Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, r.RecipientIdentifierType);
Assert.Same(cert, r.Certificate);
}
}
[Fact]
public static void CmsRecipientPassNullCertificate()
{
object ignore;
Assert.Throws<ArgumentNullException>(() => ignore = new CmsRecipient(null));
Assert.Throws<ArgumentNullException>(() => ignore = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, null));
}
[Fact]
public static void ContentInfoNullOid()
{
object ignore;
Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null, new byte[3]));
}
[Fact]
public static void ContentInfoNullContent()
{
object ignore;
Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null));
Assert.Throws<ArgumentNullException>(() => ignore = new ContentInfo(null, null));
}
[Fact]
public static void ContentInfoGetContentTypeNull()
{
Assert.Throws<ArgumentNullException>(() => ContentInfo.GetContentType(null));
}
[Fact]
public static void CryptographicAttributeObjectOidCtor()
{
Oid oid = new Oid(Oids.DocumentDescription);
CryptographicAttributeObject cao = new CryptographicAttributeObject(oid);
Assert.Equal(oid.Value, cao.Oid.Value);
Assert.Equal(0, cao.Values.Count);
}
[Fact]
public static void CryptographicAttributeObjectPassNullValuesToCtor()
{
Oid oid = new Oid(Oids.DocumentDescription);
// This is legal and equivalent to passing a zero-length AsnEncodedDataCollection.
CryptographicAttributeObject cao = new CryptographicAttributeObject(oid, null);
Assert.Equal(oid.Value, cao.Oid.Value);
Assert.Equal(0, cao.Values.Count);
}
[Fact]
public static void CryptographicAttributeObjectMismatch()
{
Oid oid = new Oid(Oids.DocumentDescription);
Oid wrongOid = new Oid(Oids.DocumentName);
AsnEncodedDataCollection col = new AsnEncodedDataCollection();
col.Add(new AsnEncodedData(oid, new byte[3]));
object ignore;
Assert.Throws<InvalidOperationException>(() => ignore = new CryptographicAttributeObject(wrongOid, col));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk.Query;
#if DLAB_UNROOT_COMMON_NAMESPACE
using DLaB.Common;
#else
using Source.DLaB.Common;
#endif
#if DLAB_UNROOT_NAMESPACE || DLAB_XRM
namespace DLaB.Xrm
#else
namespace Source.DLaB.Xrm
#endif
{
public static partial class Extensions
{
#region ConditionExpression
/// <summary>
/// Gets the SQL like statement of the ConditionExpression
/// </summary>
/// <param name="ce">The ConditionExpression</param>
/// <param name="entityName"></param>
/// <returns></returns>
public static string GetStatement(this ConditionExpression ce, string entityName)
{
string op;
string condition;
var entityAttribute = (ce.EntityName ?? entityName) + "." + ce.AttributeName;
switch (ce.Operator)
{
case ConditionOperator.Null:
case ConditionOperator.NotNull:
op = ce.Operator == ConditionOperator.Null ? "IS NULL" : "IS NOT NULL";
condition = $"{entityAttribute} {op} ";
break;
case ConditionOperator.In:
case ConditionOperator.NotIn:
op = ce.Operator == ConditionOperator.In ? "IN" : "NOT IN";
condition = $"{entityAttribute} {op} ({ce.Values.Select(GetDisplayValue).ToCsv()}) ";
break;
case ConditionOperator.Between:
if (ce.Values.Count == 2)
{
condition = $"{ce.AttributeName} {ce.Operator} {GetDisplayValue(GetValue(ce, 0))} AND {GetDisplayValue(GetValue(ce, 1))}";
}
else
{
throw new Exception("Between Operator should have two values to be between");
}
break;
case ConditionOperator.Equal:
condition = $"{entityAttribute} = {GetDisplayValue(GetValue(ce, 0))} ";
break;
case ConditionOperator.GreaterThan:
condition = $"{entityAttribute} > {GetDisplayValue(GetValue(ce, 0))} ";
break;
case ConditionOperator.GreaterEqual:
condition = $"{entityAttribute} >= {GetDisplayValue(GetValue(ce, 0))} ";
break;
case ConditionOperator.LessThan:
condition = $"{entityAttribute} < {GetDisplayValue(GetValue(ce, 0))} ";
break;
case ConditionOperator.LessEqual:
condition = $"{entityAttribute} <= {GetDisplayValue(GetValue(ce, 0))} ";
break;
case ConditionOperator.EqualUserId:
condition = "Is Current User";
break;
case ConditionOperator.EqualBusinessId:
condition = "Is Current Business Unit";
break;
case ConditionOperator.NotEqualUserId:
condition = "Is Not Current User";
break;
case ConditionOperator.NotEqualBusinessId:
condition = "Is Not Current Business Unit";
break;
case ConditionOperator.Last7Days:
case ConditionOperator.LastFiscalPeriod:
case ConditionOperator.LastFiscalYear:
case ConditionOperator.LastMonth:
case ConditionOperator.LastWeek:
case ConditionOperator.LastYear:
case ConditionOperator.Next7Days:
case ConditionOperator.NextFiscalPeriod:
case ConditionOperator.NextFiscalYear:
case ConditionOperator.NextMonth:
case ConditionOperator.NextWeek:
case ConditionOperator.NextYear:
case ConditionOperator.ThisFiscalPeriod:
case ConditionOperator.ThisFiscalYear:
case ConditionOperator.ThisMonth:
case ConditionOperator.ThisWeek:
case ConditionOperator.ThisYear:
case ConditionOperator.Today:
case ConditionOperator.Tomorrow:
case ConditionOperator.Yesterday:
condition = $"{entityAttribute} IS IN {ce.Operator} ";
break;
default:
condition = $"{ce.AttributeName} {ce.Operator} {GetDisplayValue(GetValue(ce, 0))} ";
break;
}
return condition;
}
private static object GetValue(ConditionExpression ce, int index)
{
if (ce.Values.Count <= index)
{
return "Invalid Index! Requested " + index + " but count was " + ce.Values.Count;
}
return ce.Values[index];
}
private static string GetDisplayValue(object value)
{
if (value == null) { return "<null>"; }
var type = value.GetType();
if (typeof(String).IsAssignableFrom(type))
{
if (DateTime.TryParse(value as String, out DateTime localTime))
{
value = localTime.ToUniversalTime().ToString(CultureInfo.InvariantCulture);
}
return "'" + value + "'";
}
if (typeof(Guid).IsAssignableFrom(type))
{
return "'" + value + "'";
}
if (typeof(DateTime).IsAssignableFrom(type))
{
var dateTimeValue = (DateTime)value;
if (dateTimeValue.Kind != DateTimeKind.Utc)
{
dateTimeValue = dateTimeValue.ToUniversalTime();
}
return "'" + dateTimeValue + "'";
}
return value.ToString();
}
#endregion ConditionExpression
#region FilterExpression
/// <summary>
/// Returns a SQL-ish Representation of the filter
/// </summary>
/// <param name="filter"></param>
/// <param name="entityName"></param>
/// <returns></returns>
public static string GetStatement(this FilterExpression filter, string entityName)
{
var conditions = filter.Conditions.Select(condition => GetStatement(condition, entityName)).ToList();
if (filter.Conditions.Count > 0 && filter.Filters.Count > 0)
{
conditions[conditions.Count - 1] += Environment.NewLine;
}
conditions.AddRange(filter.Filters.Select(child => child.GetStatement(entityName) + Environment.NewLine));
var join = filter.FilterOperator.ToString().PadLeft(3, ' ') + " ";
var statement = String.Join(join, conditions.ToArray());
if (String.IsNullOrWhiteSpace(statement)) { return string.Empty; }
return "( " + statement + ") ";
}
#endregion FilterExpression
#region QueryExpression
/// <summary>
/// Returns a SQL-ish representation of the QueryExpression's Criteria
/// </summary>
/// <param name="qe"></param>
/// <returns></returns>
public static string GetSqlStatement(this QueryExpression qe)
{
var sb = new StringBuilder();
string top = string.Empty;
if (qe.PageInfo != null && qe.PageInfo.Count > 0)
{
top = "TOP " + qe.PageInfo.Count + " ";
}
var allLinkedEntities = WalkAllLinkedEntities(qe).ToList();
var cols = new List<string>();
foreach (var link in allLinkedEntities.Where(l => l.Columns.Columns.Any()))
{
string linkName = link.EntityAlias ?? link.LinkToEntityName ?? "unspecified";
linkName += ".";
cols.AddRange(link.Columns.Columns.Select(c => linkName + c));
}
// Select Statement
sb.Append("SELECT " + top);
if (qe.ColumnSet != null)
{
string tableName = qe.EntityName + ".";
if (qe.ColumnSet.AllColumns)
{
sb.Append(cols.Count > 0 ? tableName + "*, " : tableName + "* ");
}
else
{
cols.AddRange(qe.ColumnSet.Columns.Select(c => tableName + c));
}
}
sb.AppendLine(cols.ToCsv());
// From Statement
sb.AppendLine("FROM " + qe.EntityName);
foreach (var link in allLinkedEntities)
{
var aliasName = String.IsNullOrWhiteSpace(link.EntityAlias) ? link.LinkToEntityName : link.EntityAlias;
sb.AppendFormat("{0} JOIN {1} on {2}.{3} = {4}.{5}{6}",
link.JoinOperator.ToString().ToUpper(),
link.LinkToEntityName + (String.IsNullOrWhiteSpace(link.EntityAlias) ? String.Empty : link.LinkToEntityName + " as " + link.EntityAlias),
link.LinkFromEntityName, link.LinkFromAttributeName,
aliasName, link.LinkToAttributeName, Environment.NewLine);
if (link.LinkCriteria != null)
{
var statement = link.LinkCriteria.GetStatement(aliasName);
if (!String.IsNullOrWhiteSpace(statement))
{
sb.AppendLine(" AND " + statement);
}
}
}
sb.AppendLine("WHERE");
sb.AppendLine(qe.Criteria.GetStatement(qe.EntityName));
// Order By Statement
if (qe.Orders.Any())
{
sb.AppendLine("ORDER BY");
var orders = qe.Orders.Select(order => order.AttributeName + " " + order.OrderType);
sb.Append(String.Join("," + Environment.NewLine, orders));
}
return sb.ToString();
}
#endregion QueryExpression
#region Helper Functions
/// <summary>
/// Enumerates over all LinkEntities in the QueryExpression, in a depth-first search
/// </summary>
/// <param name="qe"></param>
/// <returns></returns>
private static IEnumerable<LinkEntity> WalkAllLinkedEntities(QueryExpression qe)
{
foreach (var link in qe.LinkEntities)
{
yield return link;
foreach (var child in WalkAllLinkedEntities(link))
{
yield return child;
}
}
}
/// <summary>
/// Enumerates over all LinkEntities in the LinkEntity, in a depth-first search
/// </summary>
/// <param name="link"></param>
/// <returns></returns>
private static IEnumerable<LinkEntity> WalkAllLinkedEntities(LinkEntity link)
{
foreach (var child in link.LinkEntities)
{
yield return child;
foreach (var grandchild in WalkAllLinkedEntities(child))
{
yield return grandchild;
}
}
}
#endregion Helper Functions
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) Under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for Additional information regarding copyright ownership.
* The ASF licenses this file to You Under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed Under the License is distributed on an "AS Is" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations Under the License.
*/
/*
* Created on May 19, 2005
*
*/
namespace NPOI.SS.Formula.Functions
{
using System;
/**
* @author Amol S. Deshmukh < amolweb at ya hoo dot com >
* This class Is an extension to the standard math library
* provided by java.lang.Math class. It follows the Math class
* in that it has a private constructor and all static methods.
*/
public class MathX
{
private MathX() { }
/**
* Returns a value rounded to p digits after decimal.
* If p Is negative, then the number Is rounded to
* places to the left of the decimal point. eg.
* 10.23 rounded to -1 will give: 10. If p Is zero,
* the returned value Is rounded to the nearest integral
* value.
* If n Is negative, the resulting value Is obtained
* as the round value of absolute value of n multiplied
* by the sign value of n (@see MathX.sign(double d)).
* Thus, -0.6666666 rounded to p=0 will give -1 not 0.
* If n Is NaN, returned value Is NaN.
* @param n
* @param p
*/
public static double Round(double n, int p)
{
double retval;
if (double.IsNaN(n) || double.IsInfinity(n))
{
retval = double.NaN;
}
else if (double.MaxValue == n)
return double.MaxValue;
else if (double.MinValue == n)
return 0;
else
{
if (p >= 0)
{
int temp = (int)Math.Pow(10, p);
double delta = 0.5;
int x = p + 1;
while (x > 0)
{
delta = delta / 10;
x--;
}
retval = (double)(Math.Round((decimal)(n + delta) * temp) / temp);
}
else
{
int temp = (int)Math.Pow(10, Math.Abs(p));
retval = (double)(Math.Round((decimal)(n) / temp) * temp);
}
}
return retval;
}
/**
* Returns a value rounded-up to p digits after decimal.
* If p Is negative, then the number Is rounded to
* places to the left of the decimal point. eg.
* 10.23 rounded to -1 will give: 20. If p Is zero,
* the returned value Is rounded to the nearest integral
* value.
* If n Is negative, the resulting value Is obtained
* as the round-up value of absolute value of n multiplied
* by the sign value of n (@see MathX.sign(double d)).
* Thus, -0.2 rounded-up to p=0 will give -1 not 0.
* If n Is NaN, returned value Is NaN.
* @param n
* @param p
*/
public static double RoundUp(double n, int p)
{
double retval;
if (double.IsNaN(n) || double.IsInfinity(n))
{
retval = double.NaN;
}
else if (double.MaxValue == n)
return double.MaxValue;
else if (double.MinValue == n)
{
double digit = 1;
while (p > 0)
{
digit = digit / 10;
p--;
}
return digit;
}
else
{
if (p != 0)
{
double temp = Math.Pow(10, p);
double nat = Math.Abs(n * temp);
retval = Sign(n) *
((nat == (long)nat)
? nat / temp
: Math.Round(nat + 0.5) / temp);
}
else
{
double na = Math.Abs(n);
retval = Sign(n) *
((na == (long)na)
? na
: (long)na + 1);
}
}
return retval;
}
/**
* Returns a value rounded to p digits after decimal.
* If p Is negative, then the number Is rounded to
* places to the left of the decimal point. eg.
* 10.23 rounded to -1 will give: 10. If p Is zero,
* the returned value Is rounded to the nearest integral
* value.
* If n Is negative, the resulting value Is obtained
* as the round-up value of absolute value of n multiplied
* by the sign value of n (@see MathX.sign(double d)).
* Thus, -0.8 rounded-down to p=0 will give 0 not -1.
* If n Is NaN, returned value Is NaN.
* @param n
* @param p
*/
public static double RoundDown(double n, int p)
{
double retval;
if (double.IsNaN(n) || double.IsInfinity(n))
{
retval = double.NaN;
}
else if (double.MaxValue == n)
return double.MaxValue;
else if (double.MinValue == n)
return 0;
else
{
if (p != 0)
{
double temp = Math.Pow(10, p);
retval = Sign(n) * Math.Round((Math.Abs(n) * temp) - 0.5, MidpointRounding.AwayFromZero) / temp;
}
else
{
retval = (long)n;
}
}
return retval;
}
/*
* If d < 0, returns short -1
* <br/>
* If d > 0, returns short 1
* <br/>
* If d == 0, returns short 0
* If d Is NaN, then 1 will be returned. It Is the responsibility
* of caller to Check for d IsNaN if some other value Is desired.
* @param d
*/
public static short Sign(double d)
{
return (short)((d == 0)
? 0
: (d < 0)
? -1
: 1);
}
/**
* average of all values
* @param values
*/
public static double Average(double[] values)
{
double ave = 0;
double sum = 0;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
sum += values[i];
}
ave = sum / values.Length;
return ave;
}
/**
* sum of all values
* @param values
*/
public static double Sum(double[] values)
{
double sum = 0;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
sum += values[i];
}
return sum;
}
/**
* sum of squares of all values
* @param values
*/
public static double Sumsq(double[] values)
{
double sumsq = 0;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
sumsq += values[i] * values[i];
}
return sumsq;
}
/**
* product of all values
* @param values
*/
public static double Product(double[] values)
{
double product = 0;
if (values != null && values.Length > 0)
{
product = 1;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
product *= values[i];
}
}
return product;
}
/**
* min of all values. If supplied array Is zero Length,
* double.POSITIVE_INFINITY Is returned.
* @param values
*/
public static double Min(double[] values)
{
double min = double.PositiveInfinity;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
min = Math.Min(min, values[i]);
}
return min;
}
/**
* min of all values. If supplied array Is zero Length,
* double.NEGATIVE_INFINITY Is returned.
* @param values
*/
public static double Max(double[] values)
{
double max = double.NegativeInfinity;
for (int i = 0, iSize = values.Length; i < iSize; i++)
{
max = Math.Max(max, values[i]);
}
return max;
}
/**
* Note: this function Is different from java.lang.Math.floor(..).
*
* When n and s are "valid" arguments, the returned value Is: Math.floor(n/s) * s;
* <br/>
* n and s are invalid if any of following conditions are true:
* <ul>
* <li>s Is zero</li>
* <li>n Is negative and s Is positive</li>
* <li>n Is positive and s Is negative</li>
* </ul>
* In all such cases, double.NaN Is returned.
* @param n
* @param s
*/
public static double Floor(double n, double s)
{
double f;
if ((n < 0 && s > 0) || (n > 0 && s < 0) || (s == 0 && n != 0))
{
f = double.NaN;
}
else
{
f = (n == 0 || s == 0) ? 0 : Math.Floor(n / s) * s;
}
return f;
}
/**
* Note: this function Is different from java.lang.Math.ceil(..).
*
* When n and s are "valid" arguments, the returned value Is: Math.ceiling(n/s) * s;
* <br/>
* n and s are invalid if any of following conditions are true:
* <ul>
* <li>s Is zero</li>
* <li>n Is negative and s Is positive</li>
* <li>n Is positive and s Is negative</li>
* </ul>
* In all such cases, double.NaN Is returned.
* @param n
* @param s
*/
public static double Ceiling(double n, double s)
{
double c;
if ((n < 0 && s > 0) || (n > 0 && s < 0))
{
c = double.NaN;
}
else
{
c = (n == 0 || s == 0) ? 0 : Math.Ceiling(n / s) * s;
}
return c;
}
/**
* <br/> for all n >= 1; factorial n = n * (n-1) * (n-2) * ... * 1
* <br/> else if n == 0; factorial n = 1
* <br/> else if n < 0; factorial n = double.NaN
* <br/> Loss of precision can occur if n Is large enough.
* If n Is large so that the resulting value would be greater
* than double.MAX_VALUE; double.POSITIVE_INFINITY Is returned.
* If n < 0, double.NaN Is returned.
* @param n
*/
public static double Factorial(int n)
{
double d = 1;
if (n >= 0)
{
if (n <= 170)
{
for (int i = 1; i <= n; i++)
{
d *= i;
}
}
else
{
d = double.PositiveInfinity;
}
}
else
{
d = double.NaN;
}
return d;
}
/**
* returns the remainder resulting from operation:
* n / d.
* <br/> The result has the sign of the divisor.
* <br/> Examples:
* <ul>
* <li>mod(3.4, 2) = 1.4</li>
* <li>mod(-3.4, 2) = 0.6</li>
* <li>mod(-3.4, -2) = -1.4</li>
* <li>mod(3.4, -2) = -0.6</li>
* </ul>
* If d == 0, result Is NaN
* @param n
* @param d
*/
public static double Mod(double n, double d)
{
double result = 0;
if (d == 0)
{
result = double.NaN;
}
else if (Sign(n) == Sign(d))
{
//double t = Math.Abs(n / d);
//t = t - (long)t;
//result = sign(d) * Math.Abs(t * d);
result = n % d;
}
else
{
//double t = Math.Abs(n / d);
//t = t - (long)t;
//t = Math.Ceiling(t) - t;
//result = sign(d) * Math.Abs(t * d);
result = ((n % d) + d) % d;
}
return result;
}
/**
* inverse hyperbolic cosine
* @param d
*/
public static double Acosh(double d)
{
return Math.Log(Math.Sqrt(Math.Pow(d, 2) - 1) + d);
}
/**
* inverse hyperbolic sine
* @param d
*/
public static double Asinh(double d)
{
double d2 = d * d;
return Math.Log(Math.Sqrt(d * d + 1) + d);
}
/**
* inverse hyperbolic tangent
* @param d
*/
public static double Atanh(double d)
{
return Math.Log((1 + d) / (1 - d)) / 2;
}
/**
* hyperbolic cosine
* @param d
*/
public static double Cosh(double d)
{
double ePowX = Math.Pow(Math.E, d);
double ePowNegX = Math.Pow(Math.E, -d);
d = (ePowX + ePowNegX) / 2;
return d;
}
/**
* hyperbolic sine
* @param d
*/
public static double Sinh(double d)
{
double ePowX = Math.Pow(Math.E, d);
double ePowNegX = Math.Pow(Math.E, -d);
d = (ePowX - ePowNegX) / 2;
return d;
}
/**
* hyperbolic tangent
* @param d
*/
public static double Tanh(double d)
{
double ePowX = Math.Pow(Math.E, d);
double ePowNegX = Math.Pow(Math.E, -d);
d = (ePowX - ePowNegX) / (ePowX + ePowNegX);
return d;
}
/**
* returns the sum of product of corresponding double value in each
* subarray. It Is the responsibility of the caller to Ensure that
* all the subarrays are of equal Length. If the subarrays are
* not of equal Length, the return value can be Unpredictable.
* @param arrays
*/
public static double SumProduct(double[][] arrays)
{
double d = 0;
try
{
int narr = arrays.Length;
int arrlen = arrays[0].Length;
for (int j = 0; j < arrlen; j++)
{
double t = 1;
for (int i = 0; i < narr; i++)
{
t *= arrays[i][j];
}
d += t;
}
}
catch (IndexOutOfRangeException)
{
d = double.NaN;
}
return d;
}
/**
* returns the sum of difference of squares of corresponding double
* value in each subarray: ie. sigma (xarr[i]^2-yarr[i]^2)
* <br/>
* It Is the responsibility of the caller
* to Ensure that the two subarrays are of equal Length. If the
* subarrays are not of equal Length, the return value can be
* Unpredictable.
* @param xarr
* @param yarr
*/
public static double Sumx2my2(double[] xarr, double[] yarr)
{
double d = 0;
try
{
for (int i = 0, iSize = xarr.Length; i < iSize; i++)
{
d += (xarr[i] + yarr[i]) * (xarr[i] - yarr[i]);
}
}
catch (IndexOutOfRangeException)
{
d = double.NaN;
}
return d;
}
/**
* returns the sum of sum of squares of corresponding double
* value in each subarray: ie. sigma (xarr[i]^2 + yarr[i]^2)
* <br/>
* It Is the responsibility of the caller
* to Ensure that the two subarrays are of equal Length. If the
* subarrays are not of equal Length, the return value can be
* Unpredictable.
* @param xarr
* @param yarr
*/
public static double Sumx2py2(double[] xarr, double[] yarr)
{
double d = 0;
try
{
for (int i = 0, iSize = xarr.Length; i < iSize; i++)
{
d += (xarr[i] * xarr[i]) + (yarr[i] * yarr[i]);
}
}
catch (IndexOutOfRangeException )
{
d = double.NaN;
}
return d;
}
/**
* returns the sum of squares of difference of corresponding double
* value in each subarray: ie. sigma ( (xarr[i]-yarr[i])^2 )
* <br/>
* It Is the responsibility of the caller
* to Ensure that the two subarrays are of equal Length. If the
* subarrays are not of equal Length, the return value can be
* Unpredictable.
* @param xarr
* @param yarr
*/
public static double Sumxmy2(double[] xarr, double[] yarr)
{
double d = 0;
try
{
for (int i = 0, iSize = xarr.Length; i < iSize; i++)
{
double t = (xarr[i] - yarr[i]);
d += t * t;
}
}
catch (IndexOutOfRangeException )
{
d = double.NaN;
}
return d;
}
/**
* returns the total number of combinations possible when
* k items are chosen out of total of n items. If the number
* Is too large, loss of precision may occur (since returned
* value Is double). If the returned value Is larger than
* double.MAX_VALUE, double.POSITIVE_INFINITY Is returned.
* If either of the parameters Is negative, double.NaN Is returned.
* @param n
* @param k
*/
public static double NChooseK(int n, int k)
{
double d = 1;
if (n < 0 || k < 0 || n < k)
{
d = double.NaN;
}
else
{
int minnk = Math.Min(n - k, k);
int maxnk = Math.Max(n - k, k);
for (int i = maxnk; i < n; i++)
{
d *= i + 1;
}
d /= Factorial(minnk);
}
return d;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="ActorPublisher.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Runtime.Serialization;
using Akka.Actor;
using Akka.Event;
using Akka.Pattern;
using Akka.Util;
using Reactive.Streams;
namespace Akka.Streams.Implementation
{
/// <summary>
/// TBD
/// </summary>
[Serializable]
internal sealed class SubscribePending
{
/// <summary>
/// TBD
/// </summary>
public static readonly SubscribePending Instance = new SubscribePending();
private SubscribePending() { }
}
/// <summary>
/// TBD
/// </summary>
[Serializable]
internal sealed class RequestMore : IDeadLetterSuppression
{
/// <summary>
/// TBD
/// </summary>
public readonly IActorSubscription Subscription;
/// <summary>
/// TBD
/// </summary>
public readonly long Demand;
/// <summary>
/// TBD
/// </summary>
/// <param name="subscription">TBD</param>
/// <param name="demand">TBD</param>
public RequestMore(IActorSubscription subscription, long demand)
{
Subscription = subscription;
Demand = demand;
}
}
/// <summary>
/// TBD
/// </summary>
[Serializable]
internal sealed class Cancel : IDeadLetterSuppression
{
/// <summary>
/// TBD
/// </summary>
public readonly IActorSubscription Subscription;
/// <summary>
/// TBD
/// </summary>
/// <param name="subscription">TBD</param>
public Cancel(IActorSubscription subscription)
{
Subscription = subscription;
}
}
/// <summary>
/// TBD
/// </summary>
[Serializable]
internal sealed class ExposedPublisher : IDeadLetterSuppression
{
/// <summary>
/// TBD
/// </summary>
public readonly IActorPublisher Publisher;
/// <summary>
/// TBD
/// </summary>
/// <param name="publisher">TBD</param>
public ExposedPublisher(IActorPublisher publisher)
{
Publisher = publisher;
}
}
/// <summary>
/// TBD
/// </summary>
[Serializable]
public class NormalShutdownException : IllegalStateException
{
/// <summary>
/// TBD
/// </summary>
/// <param name="message">TBD</param>
public NormalShutdownException(string message) : base(message) { }
/// <summary>
/// TBD
/// </summary>
/// <param name="info">TBD</param>
/// <param name="context">TBD</param>
protected NormalShutdownException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
/// <summary>
/// TBD
/// </summary>
public interface IActorPublisher : IUntypedPublisher
{
/// <summary>
/// TBD
/// </summary>
/// <param name="reason">TBD</param>
void Shutdown(Exception reason);
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
IEnumerable<IUntypedSubscriber> TakePendingSubscribers();
}
/// <summary>
/// TBD
/// </summary>
public static class ActorPublisher
{
/// <summary>
/// TBD
/// </summary>
public const string NormalShutdownReasonMessage = "Cannot subscribe to shut-down Publisher";
/// <summary>
/// TBD
/// </summary>
public static readonly NormalShutdownException NormalShutdownReason = new NormalShutdownException(NormalShutdownReasonMessage);
}
/// <summary>
/// INTERNAL API
///
/// When you instantiate this class, or its subclasses, you MUST send an ExposedPublisher message to the wrapped
/// ActorRef! If you don't need to subclass, prefer the apply() method on the companion object which takes care of this.
/// </summary>
/// <typeparam name="TOut">TBD</typeparam>
public class ActorPublisher<TOut> : IActorPublisher, IPublisher<TOut>
{
/// <summary>
/// TBD
/// </summary>
protected readonly IActorRef Impl;
// The subscriber of an subscription attempt is first placed in this list of pending subscribers.
// The actor will call takePendingSubscribers to remove it from the list when it has received the
// SubscribePending message. The AtomicReference is set to null by the shutdown method, which is
// called by the actor from postStop. Pending (unregistered) subscription attempts are denied by
// the shutdown method. Subscription attempts after shutdown can be denied immediately.
private readonly AtomicReference<ImmutableList<ISubscriber<TOut>>> _pendingSubscribers =
new AtomicReference<ImmutableList<ISubscriber<TOut>>>(ImmutableList<ISubscriber<TOut>>.Empty);
private volatile Exception _shutdownReason;
/// <summary>
/// TBD
/// </summary>
protected virtual object WakeUpMessage => SubscribePending.Instance;
/// <summary>
/// TBD
/// </summary>
/// <param name="impl">TBD</param>
public ActorPublisher(IActorRef impl)
{
Impl = impl;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="subscriber">TBD</param>
/// <exception cref="ArgumentNullException">TBD</exception>
public void Subscribe(ISubscriber<TOut> subscriber)
{
if (subscriber == null) throw new ArgumentNullException(nameof(subscriber));
while (true)
{
var current = _pendingSubscribers.Value;
if (current == null)
{
ReportSubscribeFailure(subscriber);
break;
}
if (_pendingSubscribers.CompareAndSet(current, current.Add(subscriber)))
{
Impl.Tell(WakeUpMessage);
break;
}
}
}
void IUntypedPublisher.Subscribe(IUntypedSubscriber subscriber) => Subscribe(UntypedSubscriber.ToTyped<TOut>(subscriber));
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public IEnumerable<ISubscriber<TOut>> TakePendingSubscribers()
{
var pending = _pendingSubscribers.GetAndSet(ImmutableList<ISubscriber<TOut>>.Empty);
return pending ?? ImmutableList<ISubscriber<TOut>>.Empty;
}
IEnumerable<IUntypedSubscriber> IActorPublisher.TakePendingSubscribers() => TakePendingSubscribers().Select(UntypedSubscriber.FromTyped);
/// <summary>
/// TBD
/// </summary>
/// <param name="reason">TBD</param>
public void Shutdown(Exception reason)
{
_shutdownReason = reason;
var pending = _pendingSubscribers.GetAndSet(null);
if (pending != null)
{
foreach (var subscriber in pending.Reverse())
ReportSubscribeFailure(subscriber);
}
}
private void ReportSubscribeFailure(ISubscriber<TOut> subscriber)
{
try
{
if (_shutdownReason == null)
{
ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance);
ReactiveStreamsCompliance.TryOnComplete(subscriber);
}
else if (_shutdownReason is ISpecViolation)
{
// ok, not allowed to call OnError
}
else
{
ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance);
ReactiveStreamsCompliance.TryOnError(subscriber, _shutdownReason);
}
}
catch (Exception exception)
{
if (!(exception is ISpecViolation))
throw;
}
}
}
/// <summary>
/// TBD
/// </summary>
public interface IActorSubscription : ISubscription
{
}
/// <summary>
/// TBD
/// </summary>
public static class ActorSubscription
{
/// <summary>
/// TBD
/// </summary>
/// <param name="implementor">TBD</param>
/// <param name="subscriber">TBD</param>
/// <returns>TBD</returns>
internal static IActorSubscription Create(IActorRef implementor, IUntypedSubscriber subscriber)
{
var subscribedType = subscriber.GetType().GetGenericArguments().First(); // assumes type is UntypedSubscriberWrapper
var subscriptionType = typeof(ActorSubscription<>).MakeGenericType(subscribedType);
return (IActorSubscription) Activator.CreateInstance(subscriptionType, implementor, UntypedSubscriber.ToTyped(subscriber));
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
/// <param name="implementor">TBD</param>
/// <param name="subscriber">TBD</param>
/// <returns>TBD</returns>
public static IActorSubscription Create<T>(IActorRef implementor, ISubscriber<T> subscriber)
=> new ActorSubscription<T>(implementor, subscriber);
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public class ActorSubscription<T> : IActorSubscription
{
/// <summary>
/// TBD
/// </summary>
public readonly IActorRef Implementor;
/// <summary>
/// TBD
/// </summary>
public readonly ISubscriber<T> Subscriber;
/// <summary>
/// TBD
/// </summary>
/// <param name="implementor">TBD</param>
/// <param name="subscriber">TBD</param>
public ActorSubscription(IActorRef implementor, ISubscriber<T> subscriber)
{
Implementor = implementor;
Subscriber = subscriber;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="n">TBD</param>
public void Request(long n) => Implementor.Tell(new RequestMore(this, n));
/// <summary>
/// TBD
/// </summary>
public void Cancel() => Implementor.Tell(new Cancel(this));
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="TIn">TBD</typeparam>
public class ActorSubscriptionWithCursor<TIn> : ActorSubscription<TIn>, ISubscriptionWithCursor<TIn>
{
/// <summary>
/// TBD
/// </summary>
/// <param name="implementor">TBD</param>
/// <param name="subscriber">TBD</param>
public ActorSubscriptionWithCursor(IActorRef implementor, ISubscriber<TIn> subscriber) : base(implementor, subscriber)
{
IsActive = true;
TotalDemand = 0;
Cursor = 0;
}
ISubscriber<TIn> ISubscriptionWithCursor<TIn>.Subscriber => Subscriber;
/// <summary>
/// TBD
/// </summary>
/// <param name="element">TBD</param>
public void Dispatch(object element) => ReactiveStreamsCompliance.TryOnNext(Subscriber, (TIn)element);
bool ISubscriptionWithCursor<TIn>.IsActive
{
get { return IsActive; }
set { IsActive = value; }
}
/// <summary>
/// TBD
/// </summary>
public bool IsActive { get; private set; }
/// <summary>
/// TBD
/// </summary>
public int Cursor { get; private set; }
long ISubscriptionWithCursor<TIn>.TotalDemand
{
get { return TotalDemand; }
set { TotalDemand = value; }
}
/// <summary>
/// TBD
/// </summary>
public long TotalDemand { get; private set; }
/// <summary>
/// TBD
/// </summary>
/// <param name="element">TBD</param>
public void Dispatch(TIn element) => ReactiveStreamsCompliance.TryOnNext(Subscriber, element);
int ICursor.Cursor
{
get { return Cursor; }
set { Cursor = value; }
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// .Net client wrapper for the REST API for Azure ApiManagement Service
/// </summary>
public static partial class ProductApisOperationsExtensions
{
/// <summary>
/// Adds existing API to the Product.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IProductApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Add(this IProductApisOperations operations, string resourceGroupName, string serviceName, string pid, string aid)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProductApisOperations)s).AddAsync(resourceGroupName, serviceName, pid, aid);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Adds existing API to the Product.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IProductApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> AddAsync(this IProductApisOperations operations, string resourceGroupName, string serviceName, string pid, string aid)
{
return operations.AddAsync(resourceGroupName, serviceName, pid, aid, CancellationToken.None);
}
/// <summary>
/// List all Product APIs.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IProductApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <returns>
/// List Api operations response details.
/// </returns>
public static ApiListResponse List(this IProductApisOperations operations, string resourceGroupName, string serviceName, string pid, QueryParameters query)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProductApisOperations)s).ListAsync(resourceGroupName, serviceName, pid, query);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List all Product APIs.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IProductApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='query'>
/// Optional.
/// </param>
/// <returns>
/// List Api operations response details.
/// </returns>
public static Task<ApiListResponse> ListAsync(this IProductApisOperations operations, string resourceGroupName, string serviceName, string pid, QueryParameters query)
{
return operations.ListAsync(resourceGroupName, serviceName, pid, query, CancellationToken.None);
}
/// <summary>
/// List all Product APIs.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IProductApisOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List Api operations response details.
/// </returns>
public static ApiListResponse ListNext(this IProductApisOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProductApisOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List all Product APIs.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IProductApisOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List Api operations response details.
/// </returns>
public static Task<ApiListResponse> ListNextAsync(this IProductApisOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Removes specific API from the Product.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IProductApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Remove(this IProductApisOperations operations, string resourceGroupName, string serviceName, string pid, string aid)
{
return Task.Factory.StartNew((object s) =>
{
return ((IProductApisOperations)s).RemoveAsync(resourceGroupName, serviceName, pid, aid);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Removes specific API from the Product.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.ApiManagement.IProductApisOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='pid'>
/// Required. Identifier of the product.
/// </param>
/// <param name='aid'>
/// Required. Identifier of the API.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> RemoveAsync(this IProductApisOperations operations, string resourceGroupName, string serviceName, string pid, string aid)
{
return operations.RemoveAsync(resourceGroupName, serviceName, pid, aid, CancellationToken.None);
}
}
}
| |
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_4_8 || UNITY_4_9
#define UNITY_4
#endif
#if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_3_5 || UNITY_3_4 || UNITY_3_3
#define UNITY_LE_4_3
#endif
using UnityEngine;
using UnityEditor;
using Pathfinding;
using System.Collections;
using Pathfinding.Serialization.JsonFx;
namespace Pathfinding {
/*
#if !AstarRelease
[CustomGraphEditor (typeof(CustomGridGraph),"CustomGrid Graph")]
//[CustomGraphEditor (typeof(LineTraceGraph),"Grid Tracing Graph")]
#endif
*/
[CustomGraphEditor (typeof(GridGraph),"Grid Graph")]
public class GridGraphEditor : GraphEditor {
[JsonMember]
public bool locked = true;
float newNodeSize;
[JsonMember]
public bool showExtra = false;
/** Should textures be allowed to be used.
* This can be set to false by inheriting graphs not implemeting that feature */
[JsonMember]
public bool textureVisible = true;
Matrix4x4 savedMatrix;
Vector3 savedCenter;
public bool isMouseDown = false;
[JsonMember]
public GridPivot pivot;
GraphNode node1;
/** Rounds a vector's components to whole numbers if very close to them */
public static Vector3 RoundVector3 ( Vector3 v ) {
if (Mathf.Abs ( v.x - Mathf.Round(v.x)) < 0.001f ) v.x = Mathf.Round ( v.x );
if (Mathf.Abs ( v.y - Mathf.Round(v.y)) < 0.001f ) v.y = Mathf.Round ( v.y );
if (Mathf.Abs ( v.z - Mathf.Round(v.z)) < 0.001f ) v.z = Mathf.Round ( v.z );
return v;
}
#if UNITY_LE_4_3
/** Draws an integer field */
public int IntField (string label, int value, int offset, int adjust, out Rect r) {
return IntField (new GUIContent (label),value,offset,adjust,out r);
}
/** Draws an integer field */
public int IntField (GUIContent label, int value, int offset, int adjust, out Rect r) {
GUIStyle intStyle = EditorStyles.numberField;
EditorGUILayoutx.BeginIndent ();
Rect r1 = GUILayoutUtility.GetRect (label,intStyle);
Rect r2 = GUILayoutUtility.GetRect (new GUIContent (value.ToString ()),intStyle);
EditorGUILayoutx.EndIndent();
r2.width += (r2.x-r1.x);
r2.x = r1.x+offset;
r2.width -= offset+offset+adjust;
r = new Rect ();
r.x = r2.x+r2.width;
r.y = r1.y;
r.width = offset;
r.height = r1.height;
GUI.SetNextControlName ("IntField_"+label.text);
value = EditorGUI.IntField (r2,"",value);
bool on = GUI.GetNameOfFocusedControl () == "IntField_"+label.text;
if (Event.current.type == EventType.Repaint) {
intStyle.Draw (r1,label,false,false,false,on);
}
return value;
}
#endif
public override void OnInspectorGUI (NavGraph target) {
GridGraph graph = target as GridGraph;
//GUILayout.BeginHorizontal ();
//GUILayout.BeginVertical ();
Rect lockRect;
GUIStyle lockStyle = AstarPathEditor.astarSkin.FindStyle ("GridSizeLock");
if (lockStyle == null) {
lockStyle = new GUIStyle ();
}
#if !UNITY_LE_4_3 || true
GUILayout.BeginHorizontal ();
GUILayout.BeginVertical ();
int newWidth = EditorGUILayout.IntField (new GUIContent ("Width (nodes)","Width of the graph in nodes"), graph.width);
int newDepth = EditorGUILayout.IntField (new GUIContent ("Depth (nodes)","Depth (or height you might also call it) of the graph in nodes"), graph.depth);
GUILayout.EndVertical ();
lockRect = GUILayoutUtility.GetRect (lockStyle.fixedWidth,lockStyle.fixedHeight);
// Add a small offset to make it better centred around the controls
lockRect.y += 3;
GUILayout.EndHorizontal ();
// All the layouts mess up the margin to the next control, so add it manually
GUILayout.Space (2);
#elif UNITY_4
Rect tmpLockRect;
int newWidth = IntField (new GUIContent ("Width (nodes)","Width of the graph in nodes"),graph.width,100,0, out lockRect, out sizeSelected1);
int newDepth = IntField (new GUIContent ("Depth (nodes)","Depth (or height you might also call it) of the graph in nodes"),graph.depth,100,0, out tmpLockRect, out sizeSelected2);
#else
Rect tmpLockRect;
int newWidth = IntField (new GUIContent ("Width (nodes)","Width of the graph in nodes"),graph.width,50,0, out lockRect, out sizeSelected1);
int newDepth = IntField (new GUIContent ("Depth (nodes)","Depth (or height you might also call it) of the graph in nodes"),graph.depth,50,0, out tmpLockRect, out sizeSelected2);
#endif
lockRect.width = lockStyle.fixedWidth;
lockRect.height = lockStyle.fixedHeight;
lockRect.x += lockStyle.margin.left;
lockRect.y += lockStyle.margin.top;
locked = GUI.Toggle (lockRect,locked,new GUIContent ("","If the width and depth values are locked, changing the node size will scale the grid which keeping the number of nodes consistent instead of keeping the size the same and changing the number of nodes in the graph"),lockStyle);
//GUILayout.EndHorizontal ();
if (newWidth != graph.width || newDepth != graph.depth) {
SnapSizeToNodes (newWidth,newDepth,graph);
}
GUI.SetNextControlName ("NodeSize");
newNodeSize = EditorGUILayout.FloatField (new GUIContent ("Node size","The size of a single node. The size is the side of the node square in world units"),graph.nodeSize);
newNodeSize = newNodeSize <= 0.01F ? 0.01F : newNodeSize;
float prevRatio = graph.aspectRatio;
graph.aspectRatio = EditorGUILayout.FloatField (new GUIContent ("Aspect Ratio","Scaling of the nodes width/depth ratio. Good for isometric games"),graph.aspectRatio);
if (graph.nodeSize != newNodeSize || prevRatio != graph.aspectRatio) {
if (!locked) {
graph.nodeSize = newNodeSize;
Matrix4x4 oldMatrix = graph.matrix;
graph.GenerateMatrix ();
if (graph.matrix != oldMatrix) {
//Rescann the graphs
//AstarPath.active.AutoScan ();
GUI.changed = true;
}
} else {
float delta = newNodeSize / graph.nodeSize;
graph.nodeSize = newNodeSize;
graph.unclampedSize = new Vector2 (newWidth*graph.nodeSize,newDepth*graph.nodeSize);
Vector3 newCenter = graph.matrix.MultiplyPoint3x4 (new Vector3 ((newWidth/2F)*delta,0,(newDepth/2F)*delta));
graph.center = newCenter;
graph.GenerateMatrix ();
//Make sure the width & depths stay the same
graph.width = newWidth;
graph.depth = newDepth;
AstarPath.active.AutoScan ();
}
}
Vector3 pivotPoint;
Vector3 diff;
#if UNITY_LE_4_3
EditorGUIUtility.LookLikeControls ();
#endif
#if !UNITY_4
EditorGUILayoutx.BeginIndent ();
#else
GUILayout.BeginHorizontal ();
#endif
switch (pivot) {
case GridPivot.Center:
graph.center = RoundVector3 ( graph.center );
graph.center = EditorGUILayout.Vector3Field ("Center",graph.center);
break;
case GridPivot.TopLeft:
pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (0,0,graph.depth));
pivotPoint = RoundVector3 ( pivotPoint );
diff = pivotPoint-graph.center;
pivotPoint = EditorGUILayout.Vector3Field ("Top-Left",pivotPoint);
graph.center = pivotPoint-diff;
break;
case GridPivot.TopRight:
pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (graph.width,0,graph.depth));
pivotPoint = RoundVector3 ( pivotPoint );
diff = pivotPoint-graph.center;
pivotPoint = EditorGUILayout.Vector3Field ("Top-Right",pivotPoint);
graph.center = pivotPoint-diff;
break;
case GridPivot.BottomLeft:
pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (0,0,0));
pivotPoint = RoundVector3 ( pivotPoint );
diff = pivotPoint-graph.center;
pivotPoint = EditorGUILayout.Vector3Field ("Bottom-Left",pivotPoint);
graph.center = pivotPoint-diff;
break;
case GridPivot.BottomRight:
pivotPoint = graph.matrix.MultiplyPoint3x4 (new Vector3 (graph.width,0,0));
pivotPoint = RoundVector3 ( pivotPoint );
diff = pivotPoint-graph.center;
pivotPoint = EditorGUILayout.Vector3Field ("Bottom-Right",pivotPoint);
graph.center = pivotPoint-diff;
break;
}
graph.GenerateMatrix ();
pivot = PivotPointSelector (pivot);
#if !UNITY_4
EditorGUILayoutx.EndIndent ();
EditorGUILayoutx.BeginIndent ();
#else
GUILayout.EndHorizontal ();
#endif
graph.rotation = EditorGUILayout.Vector3Field ("Rotation",graph.rotation);
#if UNITY_LE_4_3
//Add some space to make the Rotation and postion fields be better aligned (instead of the pivot point selector)
//GUILayout.Space (19+7);
#endif
//GUILayout.EndHorizontal ();
#if !UNITY_4
EditorGUILayoutx.EndIndent ();
#endif
#if UNITY_LE_4_3
EditorGUIUtility.LookLikeInspector ();
#endif
if (GUILayout.Button (new GUIContent ("Snap Size","Snap the size to exactly fit nodes"),GUILayout.MaxWidth (100),GUILayout.MaxHeight (16))) {
SnapSizeToNodes (newWidth,newDepth,graph);
}
Separator ();
graph.cutCorners = EditorGUILayout.Toggle (new GUIContent ("Cut Corners","Enables or disables cutting corners. See docs for image example"),graph.cutCorners);
graph.neighbours = (NumNeighbours)EditorGUILayout.EnumPopup (new GUIContent ("Connections","Sets how many connections a node should have to it's neighbour nodes."),graph.neighbours);
//GUILayout.BeginHorizontal ();
//EditorGUILayout.PrefixLabel ("Max Climb");
graph.maxClimb = EditorGUILayout.FloatField (new GUIContent ("Max Climb","How high, relative to the graph, should a climbable level be. A zero (0) indicates infinity"),graph.maxClimb);
if ( graph.maxClimb < 0 ) graph.maxClimb = 0;
EditorGUI.indentLevel++;
graph.maxClimbAxis = EditorGUILayout.IntPopup (new GUIContent ("Climb Axis","Determines which axis the above setting should test on"),graph.maxClimbAxis,new GUIContent[3] {new GUIContent ("X"),new GUIContent ("Y"),new GUIContent ("Z")},new int[3] {0,1,2});
EditorGUI.indentLevel--;
if ( graph.maxClimb > 0 && Mathf.Abs((Quaternion.Euler (graph.rotation) * new Vector3 (graph.nodeSize,0,graph.nodeSize))[graph.maxClimbAxis]) > graph.maxClimb ) {
EditorGUILayout.HelpBox ("Nodes are spaced further apart than this in the grid. You might want to increase this value or change the axis", MessageType.Warning );
}
//GUILayout.EndHorizontal ();
graph.maxSlope = EditorGUILayout.Slider (new GUIContent ("Max Slope","Sets the max slope in degrees for a point to be walkable. Only enabled if Height Testing is enabled."),graph.maxSlope,0,90F);
graph.erodeIterations = EditorGUILayout.IntField (new GUIContent ("Erosion iterations","Sets how many times the graph should be eroded. This adds extra margin to objects. This will not work when using Graph Updates, so if you can, use the Diameter setting in collision settings instead"),graph.erodeIterations);
graph.erodeIterations = graph.erodeIterations < 0 ? 0 : (graph.erodeIterations > 16 ? 16 : graph.erodeIterations); //Clamp iterations to [0,16]
if ( graph.erodeIterations > 0 ) {
EditorGUI.indentLevel++;
graph.erosionUseTags = EditorGUILayout.Toggle (new GUIContent ("Erosion Uses Tags","Instead of making nodes unwalkable, " +
"nodes will have their tag set to a value corresponding to their erosion level, " +
"which is a quite good measurement of their distance to the closest wall.\nSee online documentation for more info."),
graph.erosionUseTags);
if (graph.erosionUseTags) {
EditorGUI.indentLevel++;
graph.erosionFirstTag = EditorGUILayoutx.SingleTagField ("First Tag",graph.erosionFirstTag);
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
}
DrawCollisionEditor (graph.collision);
if ( graph.collision.use2D ) {
if ( Mathf.Abs ( Vector3.Dot ( Vector3.forward, Quaternion.Euler (graph.rotation) * Vector3.up ) ) < 0.9f ) {
EditorGUILayout.HelpBox ("When using 2D it is recommended to rotate the graph so that it aligns with the 2D plane.", MessageType.Warning );
}
}
Separator ();
showExtra = EditorGUILayout.Foldout (showExtra, "Extra");
if (showExtra) {
EditorGUI.indentLevel+=2;
graph.penaltyAngle = ToggleGroup (new GUIContent ("Angle Penalty","Adds a penalty based on the slope of the node"),graph.penaltyAngle);
//bool preGUI = GUI.enabled;
//GUI.enabled = graph.penaltyAngle && GUI.enabled;
if (graph.penaltyAngle) {
EditorGUI.indentLevel++;
graph.penaltyAngleFactor = EditorGUILayout.FloatField (new GUIContent ("Factor","Scale of the penalty. A negative value should not be used"),graph.penaltyAngleFactor);
//GUI.enabled = preGUI;
HelpBox ("Applies penalty to nodes based on the angle of the hit surface during the Height Testing");
EditorGUI.indentLevel--;
}
graph.penaltyPosition = ToggleGroup ("Position Penalty",graph.penaltyPosition);
//EditorGUILayout.Toggle ("Position Penalty",graph.penaltyPosition);
//preGUI = GUI.enabled;
//GUI.enabled = graph.penaltyPosition && GUI.enabled;
if (graph.penaltyPosition) {
EditorGUI.indentLevel++;
graph.penaltyPositionOffset = EditorGUILayout.FloatField ("Offset",graph.penaltyPositionOffset);
graph.penaltyPositionFactor = EditorGUILayout.FloatField ("Factor",graph.penaltyPositionFactor);
HelpBox ("Applies penalty to nodes based on their Y coordinate\nSampled in Int3 space, i.e it is multiplied with Int3.Precision first ("+Int3.Precision+")\n" +
"Be very careful when using negative values since a negative penalty will underflow and instead get really high");
//GUI.enabled = preGUI;
EditorGUI.indentLevel--;
}
GUI.enabled = false;
ToggleGroup (new GUIContent ("Use Texture",AstarPathEditor.AstarProTooltip),false);
GUI.enabled = true;
EditorGUI.indentLevel-=2;
}
}
/** Displays an object field for objects which must be in the 'Resources' folder.
* If the selected object is not in the resources folder, a warning message with a Fix button will be shown
*/
[System.Obsolete("Use ObjectField instead")]
public UnityEngine.Object ResourcesField (string label, UnityEngine.Object obj, System.Type type) {
#if UNITY_3_3
obj = EditorGUILayout.ObjectField (label,obj,type);
#else
obj = EditorGUILayout.ObjectField (label,obj,type,false);
#endif
if (obj != null) {
string path = AssetDatabase.GetAssetPath (obj);
if (!path.Contains ("Resources/")) {
if (FixLabel ("Object must be in the 'Resources' folder")) {
if (!System.IO.Directory.Exists (Application.dataPath+"/Resources")) {
System.IO.Directory.CreateDirectory (Application.dataPath+"/Resources");
AssetDatabase.Refresh ();
}
string ext = System.IO.Path.GetExtension(path);
string error = AssetDatabase.MoveAsset (path,"Assets/Resources/"+obj.name+ext);
if (error == "") {
//Debug.Log ("Successful move");
} else {
Debug.LogError ("Couldn't move asset - "+error);
}
}
}
}
return obj;
}
public void SnapSizeToNodes (int newWidth, int newDepth, GridGraph graph) {
//Vector2 preSize = graph.unclampedSize;
/*if (locked) {
graph.unclampedSize = new Vector2 (newWidth*newNodeSize,newDepth*newNodeSize);
graph.nodeSize = newNodeSize;
graph.GenerateMatrix ();
Vector3 newCenter = graph.matrix.MultiplyPoint3x4 (new Vector3 (newWidth/2F,0,newDepth/2F));
graph.center = newCenter;
AstarPath.active.AutoScan ();
} else {*/
graph.unclampedSize = new Vector2 (newWidth*graph.nodeSize,newDepth*graph.nodeSize);
Vector3 newCenter = graph.matrix.MultiplyPoint3x4 (new Vector3 (newWidth/2F,0,newDepth/2F));
graph.center = newCenter;
graph.GenerateMatrix ();
AstarPath.active.AutoScan ();
//}
GUI.changed = true;
}
public static GridPivot PivotPointSelector (GridPivot pivot) {
GUISkin skin = AstarPathEditor.astarSkin;
GUIStyle background = skin.FindStyle ("GridPivotSelectBackground");
Rect r = GUILayoutUtility.GetRect (19,19,background);
#if !UNITY_LE_4_3
// I have no idea... but it is required for it to work well
r.y -= 14;
#endif
r.width = 19;
r.height = 19;
if (background == null) {
return pivot;
}
if (Event.current.type == EventType.Repaint) {
background.Draw (r,false,false,false,false);
}
if (GUI.Toggle (new Rect (r.x,r.y,7,7),pivot == GridPivot.TopLeft, "",skin.FindStyle ("GridPivotSelectButton")))
pivot = GridPivot.TopLeft;
if (GUI.Toggle (new Rect (r.x+12,r.y,7,7),pivot == GridPivot.TopRight,"",skin.FindStyle ("GridPivotSelectButton")))
pivot = GridPivot.TopRight;
if (GUI.Toggle (new Rect (r.x+12,r.y+12,7,7),pivot == GridPivot.BottomRight,"",skin.FindStyle ("GridPivotSelectButton")))
pivot = GridPivot.BottomRight;
if (GUI.Toggle (new Rect (r.x,r.y+12,7,7),pivot == GridPivot.BottomLeft,"",skin.FindStyle ("GridPivotSelectButton")))
pivot = GridPivot.BottomLeft;
if (GUI.Toggle (new Rect (r.x+6,r.y+6,7,7),pivot == GridPivot.Center,"",skin.FindStyle ("GridPivotSelectButton")))
pivot = GridPivot.Center;
return pivot;
}
//GraphUndo undoState;
//byte[] savedBytes;
public override void OnSceneGUI (NavGraph target) {
Event e = Event.current;
GridGraph graph = target as GridGraph;
Matrix4x4 matrixPre = graph.matrix;
graph.GenerateMatrix ();
if (e.type == EventType.MouseDown) {
isMouseDown = true;
} else if (e.type == EventType.MouseUp) {
isMouseDown = false;
}
if (!isMouseDown) {
savedMatrix = graph.boundsMatrix;
}
Handles.matrix = savedMatrix;
if ((graph.GetType() == typeof(GridGraph) && graph.nodes == null) || (graph.uniformWidthDepthGrid && graph.depth*graph.width != graph.nodes.Length) || graph.matrix != matrixPre) {
//Rescan the graphs
if (AstarPath.active.AutoScan ()) {
GUI.changed = true;
}
}
Matrix4x4 inversed = savedMatrix.inverse;
Handles.color = AstarColor.BoundsHandles;
Handles.DrawCapFunction cap = Handles.CylinderCap;
Vector2 extents = graph.unclampedSize*0.5F;
Vector3 center = inversed.MultiplyPoint3x4 (graph.center);
#if UNITY_3_3
if (Tools.current == 3) {
#else
if (Tools.current == Tool.Scale) {
#endif
Vector3 p1 = Handles.Slider (center+new Vector3 (extents.x,0,0), Vector3.right, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (extents.x,0,0)),cap,0);
Vector3 p2 = Handles.Slider (center+new Vector3 (0,0,extents.y), Vector3.forward, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,0,extents.y)),cap,0);
//Vector3 p3 = Handles.Slider (center+new Vector3 (0,extents.y,0), Vector3.up, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,extents.y,0)),cap,0);
Vector3 p4 = Handles.Slider (center+new Vector3 (-extents.x,0,0), -Vector3.right, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (-extents.x,0,0)),cap,0);
Vector3 p5 = Handles.Slider (center+new Vector3 (0,0,-extents.y), -Vector3.forward, 0.1F*HandleUtility.GetHandleSize (center+new Vector3 (0,0,-extents.y)),cap,0);
Vector3 p6 = Handles.Slider (center, Vector3.up, 0.1F*HandleUtility.GetHandleSize (center),cap,0);
Vector3 r1 = new Vector3 (p1.x,p6.y,p2.z);
Vector3 r2 = new Vector3 (p4.x,p6.y,p5.z);
//Debug.Log (graph.boundsMatrix.MultiplyPoint3x4 (Vector3.zero)+" "+graph.boundsMatrix.MultiplyPoint3x4 (Vector3.one));
//if (Tools.viewTool != ViewTool.Orbit) {
graph.center = savedMatrix.MultiplyPoint3x4 ((r1+r2)/2F);
Vector3 tmp = r1-r2;
graph.unclampedSize = new Vector2(tmp.x,tmp.z);
//}
#if UNITY_3_3
} else if (Tools.current == 1) {
#else
} else if (Tools.current == Tool.Move) {
#endif
if (Tools.pivotRotation == PivotRotation.Local) {
center = Handles.PositionHandle (center,Quaternion.identity);
if (Tools.viewTool != ViewTool.Orbit) {
graph.center = savedMatrix.MultiplyPoint3x4 (center);
}
} else {
Handles.matrix = Matrix4x4.identity;
center = Handles.PositionHandle (graph.center,Quaternion.identity);
if (Tools.viewTool != ViewTool.Orbit) {
graph.center = center;
}
}
#if UNITY_3_3
} else if (Tools.current == 2) {
#else
} else if (Tools.current == Tool.Rotate) {
#endif
//The rotation handle doesn't seem to be able to handle different matrixes of some reason
Handles.matrix = Matrix4x4.identity;
Quaternion rot = Handles.RotationHandle (Quaternion.Euler (graph.rotation),graph.center);
if (Tools.viewTool != ViewTool.Orbit) {
graph.rotation = rot.eulerAngles;
}
}
//graph.size.x = Mathf.Max (graph.size.x,1);
//graph.size.y = Mathf.Max (graph.size.y,1);
//graph.size.z = Mathf.Max (graph.size.z,1);
Handles.matrix = Matrix4x4.identity;
}
public enum GridPivot {
Center,
TopLeft,
TopRight,
BottomLeft,
BottomRight
}
}
}
| |
#region MIT License
/*
* Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.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.
*/
#endregion
#if UseDouble
using Scalar = System.Double;
#else
using Scalar = System.Single;
#endif
using System;
using System.Runtime.InteropServices;
using AdvanceMath.Design;
namespace AdvanceMath.Geometry2D
{
[StructLayout(LayoutKind.Sequential, Size = Line.Size)]
[AdvBrowsableOrder("Normal,D"), Serializable]
#if !CompactFramework && !WindowsCE && !PocketPC && !XBOX360 && !SILVERLIGHT
[System.ComponentModel.TypeConverter(typeof(AdvTypeConverter<Line>))]
#endif
public struct Line : IEquatable<Line>
{
public static Line Transform(Matrix3x3 matrix, Line line)
{
Line result;
Transform(ref matrix, ref line, out result);
return result;
}
public static void Transform(ref Matrix3x3 matrix, ref Line line, out Line result)
{
Vector2D point;
Vector2D origin = Vector2D.Zero;
Vector2D.Multiply(ref line.Normal, ref line.D, out point);
Vector2D.Transform(ref matrix, ref point, out point);
Vector2D.Transform(ref matrix, ref origin, out origin);
Vector2D.Subtract(ref point, ref origin, out result.Normal);
Vector2D.Normalize(ref result.Normal, out result.Normal);
Vector2D.Dot(ref point, ref result.Normal, out result.D);
}
public static Line Transform(Matrix2x3 matrix, Line line)
{
Line result;
Transform(ref matrix, ref line, out result);
return result;
}
public static void Transform(ref Matrix2x3 matrix, ref Line line, out Line result)
{
Vector2D point;
Vector2D origin = Vector2D.Zero;
Vector2D.Multiply(ref line.Normal, ref line.D, out point);
Vector2D.Transform(ref matrix, ref point, out point);
Vector2D.Transform(ref matrix, ref origin, out origin);
Vector2D.Subtract(ref point, ref origin, out result.Normal);
Vector2D.Normalize(ref result.Normal, out result.Normal);
Vector2D.Dot(ref point, ref result.Normal, out result.D);
}
public const int Size = sizeof(Scalar) + Vector2D.Size;
[AdvBrowsable]
public Vector2D Normal;
[AdvBrowsable]
public Scalar D;
[InstanceConstructor("Normal,D")]
public Line(Vector2D normal, Scalar d)
{
this.Normal = normal;
this.D = d;
}
public Line(Scalar nX, Scalar nY, Scalar d)
{
this.Normal.X = nX;
this.Normal.Y = nY;
this.D = d;
}
public Line(Vector2D point1, Vector2D point2)
{
Scalar x = point1.X - point2.X;
Scalar y = point1.Y - point2.Y;
Scalar magInv = 1 / MathHelper.Sqrt(x * x + y * y);
this.Normal.X = -y * magInv;
this.Normal.Y = x * magInv;
this.D = point1.X * this.Normal.X + point1.Y * this.Normal.Y;
}
public Scalar GetDistance(Vector2D point)
{
Scalar result;
GetDistance(ref point, out result);
return result;
}
public void GetDistance(ref Vector2D point, out Scalar result)
{
Vector2D.Dot(ref point, ref Normal, out result);
result -= D;
}
public Scalar Intersects(Ray ray)
{
Scalar result;
Intersects(ref ray, out result);
return result;
}
public bool Intersects(BoundingRectangle rect)
{
bool result;
Intersects(ref rect, out result);
return result;
}
public bool Intersects(BoundingCircle circle)
{
bool result;
circle.Intersects(ref this, out result);
return result;
}
public bool Intersects(BoundingPolygon polygon)
{
bool result;
Intersects(ref polygon, out result);
return result;
}
public void Intersects(ref Ray ray, out Scalar result)
{
Scalar dir;
Vector2D.Dot(ref Normal, ref ray.Direction, out dir);
if (-dir > 0)
{
Scalar DistanceFromOrigin = Normal * ray.Origin + D;
Vector2D.Dot(ref Normal, ref ray.Origin, out DistanceFromOrigin);
DistanceFromOrigin = -((DistanceFromOrigin + D) / dir);
if (DistanceFromOrigin >= 0)
{
result = DistanceFromOrigin;
return;
}
}
result = -1;
}
public void Intersects(ref BoundingRectangle box, out bool result)
{
Vector2D[] vertexes = box.Corners();
Scalar distance;
GetDistance(ref vertexes[0], out distance);
int sign = Math.Sign(distance);
result = false;
for (int index = 1; index < vertexes.Length; ++index)
{
GetDistance(ref vertexes[index], out distance);
if (Math.Sign(distance) != sign)
{
result = true;
break;
}
}
}
public void Intersects(ref BoundingCircle circle, out bool result)
{
circle.Intersects(ref this, out result);
}
public void Intersects(ref BoundingPolygon polygon, out bool result)
{
if (polygon == null) { throw new ArgumentNullException("polygon"); }
Vector2D[] vertexes = polygon.Vertexes;
Scalar distance;
GetDistance(ref vertexes[0], out distance);
int sign = Math.Sign(distance);
result = false;
for (int index = 1; index < vertexes.Length; ++index)
{
GetDistance(ref vertexes[index], out distance);
if (Math.Sign(distance) != sign)
{
result = true;
break;
}
}
}
public override string ToString()
{
return string.Format("N: {0} D: {1}", Normal, D);
}
public override int GetHashCode()
{
return Normal.GetHashCode() ^ D.GetHashCode();
}
public override bool Equals(object obj)
{
return obj is Line && Equals((Line)obj);
}
public bool Equals(Line other)
{
return Equals(ref this, ref other);
}
public static bool Equals(Line line1, Line line2)
{
return Equals(ref line1, ref line2);
}
[CLSCompliant(false)]
public static bool Equals(ref Line line1, ref Line line2)
{
return Vector2D.Equals(ref line1.Normal, ref line2.Normal) && line1.D == line2.D;
}
public static bool operator ==(Line line1, Line line2)
{
return Equals(ref line1, ref line2);
}
public static bool operator !=(Line line1, Line line2)
{
return !Equals(ref line1, ref line2);
}
}
}
| |
namespace FluentNHibernate.Cfg.Db
{
public class IfxSQLIConnectionStringBuilder : ConnectionStringBuilder
{
private string clientLocale = "";
private string database = "";
private string databaseLocale = "";
private bool delimident = true;
private string host = "";
private string maxPoolSize = "";
private string minPoolSize = "";
private string password = "";
private string pooling = "";
private string server = "";
private string service = "";
private string username = "";
private string otherOptions = "";
/// <summary>
/// Client locale, default value is en_us.CP1252 (Windows)
/// </summary>
/// <param name="clientLocale"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxSQLIConnectionStringBuilder ClientLocale(string clientLocale)
{
this.clientLocale = clientLocale;
IsDirty = true;
return this;
}
/// <summary>
/// The name of the database within the server instance.
/// </summary>
/// <param name="database"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxSQLIConnectionStringBuilder Database(string database)
{
this.database = database;
IsDirty = true;
return this;
}
/// <summary>
/// The language locale of the database. Default value is en_US.8859-1
/// </summary>
/// <param name="databaseLocale"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxSQLIConnectionStringBuilder DatabaseLocale(string databaseLocale)
{
this.databaseLocale = databaseLocale;
IsDirty = true;
return this;
}
/// <summary>
/// When set to true or y for yes, any string within double
/// quotes (") is treated as an identifier, and any string within
/// single quotes (') is treated as a string literal. Default value 'y'.
/// </summary>
/// <param name="delimident"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxSQLIConnectionStringBuilder Delimident(bool delimident)
{
this.delimident = delimident;
IsDirty = true;
return this;
}
/// <summary>
/// The name or IP address of the machine on which the
/// Informix server is running. Required.
/// </summary>
/// <param name="host"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxSQLIConnectionStringBuilder Host(string host)
{
this.host = host;
IsDirty = true;
return this;
}
/// <summary>
/// The maximum number of connections allowed in the pool. Default value 100.
/// </summary>
/// <param name="maxPoolSize"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxSQLIConnectionStringBuilder MaxPoolSize(string maxPoolSize)
{
this.maxPoolSize = maxPoolSize;
IsDirty = true;
return this;
}
/// <summary>
/// The minimum number of connections allowed in the pool. Default value 0.
/// </summary>
/// <param name="minPoolSize"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxSQLIConnectionStringBuilder MinPoolSize(string minPoolSize)
{
this.minPoolSize = minPoolSize;
IsDirty = true;
return this;
}
/// <summary>
/// The password associated with the User ID. Required if the
/// client machine or user account is not trusted by the host.
/// Prohibited if a User ID is not given.
/// </summary>
/// <param name="password"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxSQLIConnectionStringBuilder Password(string password)
{
this.password = password;
IsDirty = true;
return this;
}
/// <summary>
/// When set to true, the IfxConnection object is drawn from
/// the appropriate pool, or if necessary, it is created and added
/// to the appropriate pool. Default value 'true'.
/// </summary>
/// <param name="pooling"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxSQLIConnectionStringBuilder Pooling(string pooling)
{
this.pooling = pooling;
IsDirty = true;
return this;
}
/// <summary>
/// The name or alias of the instance of the Informix server to
/// which to connect. Required.
/// </summary>
/// <param name="server"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxSQLIConnectionStringBuilder Server(string server)
{
this.server = server;
IsDirty = true;
return this;
}
/// <summary>
/// The service name or port number through which the server
/// is listening for connection requests.
/// </summary>
/// <param name="service"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxSQLIConnectionStringBuilder Service(string service)
{
this.service = service;
IsDirty = true;
return this;
}
/// <summary>
/// The login account. Required, unless the client machine is
/// trusted by the host machine.
/// </summary>
/// <param name="username"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxSQLIConnectionStringBuilder Username(string username)
{
this.username = username;
IsDirty = true;
return this;
}
/// <summary>
/// Other options like: Connection Lifetime, Enlist, Exclusive, Optimize OpenFetchClose,
/// Fetch Buffer Size, Persist Security Info, Protocol, Single Threaded, Skip Parsing
/// </summary>
/// <param name="otherOptions"></param>
/// <returns>IfxSQLIConnectionStringBuilder object</returns>
public IfxSQLIConnectionStringBuilder OtherOptions(string otherOptions)
{
this.otherOptions = otherOptions;
IsDirty = true;
return this;
}
protected internal override string Create()
{
var connectionString = base.Create();
if (!string.IsNullOrEmpty(connectionString))
return connectionString;
if (this.clientLocale.Length > 0)
{
connectionString += string.Format("Client_Locale={0};", this.clientLocale);
}
if (this.database.Length > 0)
{
connectionString += string.Format("DB={0};", this.database);
}
if (this.databaseLocale.Length > 0)
{
connectionString += string.Format("DB_LOCALE={0};", this.databaseLocale);
}
if (this.delimident != true)
{
connectionString += "DELIMIDENT='n'";
}
if (this.host.Length > 0)
{
connectionString += string.Format("Host={0};", this.host);
}
if (this.maxPoolSize.Length > 0)
{
connectionString += string.Format("Max Pool Size={0};", this.maxPoolSize);
}
if (this.minPoolSize.Length > 0)
{
connectionString += string.Format("Min Pool Size={0};", this.minPoolSize);
}
if (this.password.Length > 0)
{
connectionString += string.Format("PWD={0};", this.password);
}
if (this.pooling.Length > 0)
{
connectionString += string.Format("Pooling={0};", this.pooling);
}
if (this.server.Length > 0)
{
connectionString += string.Format("Server={0};", this.server);
}
if (this.service.Length > 0)
{
connectionString += string.Format("Service={0};", this.service);
}
if (this.username.Length > 0)
{
connectionString += string.Format("UID={0};", this.username);
}
if (this.otherOptions.Length > 0)
{
connectionString += this.otherOptions;
}
return connectionString;
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
using Cassandra.ProtocolEvents.Internal;
using Cassandra.Tasks;
namespace Cassandra.ProtocolEvents
{
/// <inheritdoc />
internal class ProtocolEventDebouncer : IProtocolEventDebouncer
{
private static readonly Logger Logger = new Logger(typeof(ProtocolEventDebouncer));
private readonly ActionBlock<Tuple<TaskCompletionSource<bool>, ProtocolEvent, bool>> _enqueueBlock;
private readonly ActionBlock<EventQueue> _processQueueBlock;
private readonly SlidingWindowExclusiveTimer _timer;
private volatile EventQueue _queue = null;
public ProtocolEventDebouncer(ITimerFactory timerFactory, TimeSpan delay, TimeSpan maxDelay)
{
_timer = new SlidingWindowExclusiveTimer(timerFactory, delay, maxDelay, Process);
// delegate for this block can't be async otherwise the shared exclusive scheduler is pointless
_enqueueBlock = new ActionBlock<Tuple<TaskCompletionSource<bool>, ProtocolEvent, bool>>(tuple =>
{
try
{
if (tuple.Item2 is KeyspaceProtocolEvent keyspaceEvent)
{
KeyspaceEventReceived(keyspaceEvent, tuple.Item3, tuple.Item1);
}
else
{
MainEventReceived(tuple.Item2, tuple.Item3, tuple.Item1);
}
}
catch (Exception ex)
{
ProtocolEventDebouncer.Logger.Error("Unexpected exception in Protocol Event Debouncer while receiving events.", ex);
}
}, new ExecutionDataflowBlockOptions
{
EnsureOrdered = true,
MaxDegreeOfParallelism = 1,
TaskScheduler = _timer.ExclusiveScheduler
});
_processQueueBlock = new ActionBlock<EventQueue>(async queue =>
{
try
{
await ProtocolEventDebouncer.ProcessQueue(queue).ConfigureAwait(false);
}
catch (Exception ex)
{
ProtocolEventDebouncer.Logger.Error("Unexpected exception in Protocol Event Debouncer while processing queue.", ex);
}
}, new ExecutionDataflowBlockOptions
{
EnsureOrdered = true,
MaxDegreeOfParallelism = 1
});
}
/// <inheritdoc />
public async Task ScheduleEventAsync(ProtocolEvent ev, bool processNow)
{
var sent = await _enqueueBlock
.SendAsync(new Tuple<TaskCompletionSource<bool>, ProtocolEvent, bool>(null, ev, processNow))
.ConfigureAwait(false);
if (!sent)
{
throw new DriverInternalError("Could not schedule event in the ProtocolEventDebouncer.");
}
}
/// <inheritdoc />
public async Task HandleEventAsync(ProtocolEvent ev, bool processNow)
{
var callback = new TaskCompletionSource<bool>();
var sent = await _enqueueBlock.SendAsync(new Tuple<TaskCompletionSource<bool>, ProtocolEvent, bool>(callback, ev, processNow)).ConfigureAwait(false);
if (!sent)
{
throw new DriverInternalError("Could not schedule event in the ProtocolEventDebouncer.");
}
await callback.Task.ConfigureAwait(false);
}
/// <inheritdoc />
public async Task ShutdownAsync()
{
_enqueueBlock.Complete();
await _enqueueBlock.Completion.ConfigureAwait(false);
await _timer.SlideDelayAsync(true).ConfigureAwait(false);
_timer.Dispose();
_processQueueBlock.Complete();
await _processQueueBlock.Completion.ConfigureAwait(false);
}
// for tests
internal EventQueue GetQueue() => _queue;
private void MainEventReceived(ProtocolEvent ev, bool processNow, TaskCompletionSource<bool> callback)
{
if (_queue == null)
{
_queue = new EventQueue();
}
_queue.MainEvent = ev;
if (callback != null)
{
_queue.Callbacks.Add(callback);
}
_timer.SlideDelay(processNow);
}
private void KeyspaceEventReceived(KeyspaceProtocolEvent ev, bool processNow, TaskCompletionSource<bool> callback)
{
if (_queue == null)
{
_queue = new EventQueue();
}
if (callback != null)
{
_queue.Callbacks.Add(callback);
}
if (_queue.MainEvent != null)
{
_timer.SlideDelay(processNow);
return;
}
if (!_queue.Keyspaces.TryGetValue(ev.Keyspace, out var keyspaceEvents))
{
keyspaceEvents = new KeyspaceEvents();
_queue.Keyspaces.Add(ev.Keyspace, keyspaceEvents);
}
if (ev.IsRefreshKeyspaceEvent)
{
keyspaceEvents.RefreshKeyspaceEvent = ev;
}
keyspaceEvents.Events.Add(new InternalKeyspaceProtocolEvent { Callback = callback, KeyspaceEvent = ev });
_timer.SlideDelay(processNow);
}
private void Process()
{
if (_queue == null)
{
return;
}
// this is running with the exclusive scheduler so this is fine
var queue = _queue;
_queue = null;
// not necessary to enqueue within the exclusive scheduler
Task.Run(async () =>
{
var sent = false;
try
{
sent = await _processQueueBlock.SendAsync(queue).ConfigureAwait(false);
}
catch (Exception ex)
{
ProtocolEventDebouncer.Logger.Error("EventDebouncer timer callback threw an exception.", ex);
}
if (!sent)
{
foreach (var cb in queue.Callbacks)
{
cb?.TrySetException(new DriverInternalError("Could not process events in the ProtocolEventDebouncer."));
}
}
}).Forget();
}
private static async Task ProcessQueue(EventQueue queue)
{
if (queue.MainEvent != null)
{
try
{
await queue.MainEvent.Handler().ConfigureAwait(false);
foreach (var cb in queue.Callbacks)
{
if (cb != null)
{
Task.Run(() => cb.TrySetResult(true)).Forget();
}
}
}
catch (Exception ex)
{
foreach (var cb in queue.Callbacks)
{
if (cb != null)
{
Task.Run(() => cb.TrySetException(ex)).Forget();
}
}
}
return;
}
foreach (var keyspace in queue.Keyspaces)
{
if (keyspace.Value.RefreshKeyspaceEvent != null)
{
try
{
await keyspace.Value.RefreshKeyspaceEvent.Handler().ConfigureAwait(false);
foreach (var cb in keyspace.Value.Events.Select(e => e.Callback).Where(e => e != null))
{
Task.Run(() => cb.TrySetResult(true)).Forget();
}
}
catch (Exception ex)
{
foreach (var cb in keyspace.Value.Events.Select(e => e.Callback).Where(e => e != null))
{
Task.Run(() => cb.TrySetException(ex)).Forget();
}
}
continue;
}
foreach (var ev in keyspace.Value.Events)
{
try
{
await ev.KeyspaceEvent.Handler().ConfigureAwait(false);
if (ev.Callback != null)
{
Task.Run(() => ev.Callback.TrySetResult(true)).Forget();
}
}
catch (Exception ex)
{
if (ev.Callback != null)
{
Task.Run(() => ev.Callback.TrySetException(ex)).Forget();
}
}
}
}
}
}
}
| |
// 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.
using System.IO;
using System.Diagnostics;
using System.Globalization;
using System.Security;
using System.Xml.Schema;
namespace System.Xml
{
// XmlReaderSettings class specifies basic features of an XmlReader.
public sealed class XmlReaderSettings
{
//
// Fields
//
private bool _useAsync;
// Nametable
private XmlNameTable _nameTable;
// XmlResolver
private XmlResolver _xmlResolver = null;
// Text settings
private int _lineNumberOffset;
private int _linePositionOffset;
// Conformance settings
private ConformanceLevel _conformanceLevel;
private bool _checkCharacters;
private long _maxCharactersInDocument;
private long _maxCharactersFromEntities;
// Filtering settings
private bool _ignoreWhitespace;
private bool _ignorePIs;
private bool _ignoreComments;
// security settings
private DtdProcessing _dtdProcessing;
//Validation settings
private ValidationType _validationType;
private XmlSchemaValidationFlags _validationFlags;
private XmlSchemaSet _schemas;
private ValidationEventHandler _valEventHandler;
// other settings
private bool _closeInput;
// read-only flag
private bool _isReadOnly;
//
// Constructor
//
public XmlReaderSettings()
{
Initialize();
}
//
// Properties
//
public bool Async
{
get
{
return _useAsync;
}
set
{
CheckReadOnly("Async");
_useAsync = value;
}
}
// Nametable
public XmlNameTable NameTable
{
get
{
return _nameTable;
}
set
{
CheckReadOnly("NameTable");
_nameTable = value;
}
}
// XmlResolver
internal bool IsXmlResolverSet
{
get;
set; // keep set internal as we need to call it from the schema validation code
}
public XmlResolver XmlResolver
{
set
{
CheckReadOnly("XmlResolver");
_xmlResolver = value;
IsXmlResolverSet = true;
}
}
internal XmlResolver GetXmlResolver()
{
return _xmlResolver;
}
//This is used by get XmlResolver in Xsd.
//Check if the config set to prohibit default resovler
//notice we must keep GetXmlResolver() to avoid dead lock when init System.Config.ConfigurationManager
internal XmlResolver GetXmlResolver_CheckConfig()
{
if (!LocalAppContextSwitches.AllowDefaultResolver && !IsXmlResolverSet)
return null;
else
return _xmlResolver;
}
// Text settings
public int LineNumberOffset
{
get
{
return _lineNumberOffset;
}
set
{
CheckReadOnly("LineNumberOffset");
_lineNumberOffset = value;
}
}
public int LinePositionOffset
{
get
{
return _linePositionOffset;
}
set
{
CheckReadOnly("LinePositionOffset");
_linePositionOffset = value;
}
}
// Conformance settings
public ConformanceLevel ConformanceLevel
{
get
{
return _conformanceLevel;
}
set
{
CheckReadOnly("ConformanceLevel");
if ((uint)value > (uint)ConformanceLevel.Document)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_conformanceLevel = value;
}
}
public bool CheckCharacters
{
get
{
return _checkCharacters;
}
set
{
CheckReadOnly("CheckCharacters");
_checkCharacters = value;
}
}
public long MaxCharactersInDocument
{
get
{
return _maxCharactersInDocument;
}
set
{
CheckReadOnly("MaxCharactersInDocument");
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_maxCharactersInDocument = value;
}
}
public long MaxCharactersFromEntities
{
get
{
return _maxCharactersFromEntities;
}
set
{
CheckReadOnly("MaxCharactersFromEntities");
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_maxCharactersFromEntities = value;
}
}
// Filtering settings
public bool IgnoreWhitespace
{
get
{
return _ignoreWhitespace;
}
set
{
CheckReadOnly("IgnoreWhitespace");
_ignoreWhitespace = value;
}
}
public bool IgnoreProcessingInstructions
{
get
{
return _ignorePIs;
}
set
{
CheckReadOnly("IgnoreProcessingInstructions");
_ignorePIs = value;
}
}
public bool IgnoreComments
{
get
{
return _ignoreComments;
}
set
{
CheckReadOnly("IgnoreComments");
_ignoreComments = value;
}
}
[Obsolete("Use XmlReaderSettings.DtdProcessing property instead.")]
public bool ProhibitDtd
{
get
{
return _dtdProcessing == DtdProcessing.Prohibit;
}
set
{
CheckReadOnly("ProhibitDtd");
_dtdProcessing = value ? DtdProcessing.Prohibit : DtdProcessing.Parse;
}
}
public DtdProcessing DtdProcessing
{
get
{
return _dtdProcessing;
}
set
{
CheckReadOnly("DtdProcessing");
if ((uint)value > (uint)DtdProcessing.Parse)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dtdProcessing = value;
}
}
public bool CloseInput
{
get
{
return _closeInput;
}
set
{
CheckReadOnly("CloseInput");
_closeInput = value;
}
}
public ValidationType ValidationType
{
get
{
return _validationType;
}
set
{
CheckReadOnly("ValidationType");
if ((uint)value > (uint)ValidationType.Schema)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_validationType = value;
}
}
public XmlSchemaValidationFlags ValidationFlags
{
get
{
return _validationFlags;
}
set
{
CheckReadOnly("ValidationFlags");
if ((uint)value > (uint)(XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.AllowXmlAttributes))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_validationFlags = value;
}
}
public XmlSchemaSet Schemas
{
get
{
if (_schemas == null)
{
_schemas = new XmlSchemaSet();
}
return _schemas;
}
set
{
CheckReadOnly("Schemas");
_schemas = value;
}
}
public event ValidationEventHandler ValidationEventHandler
{
add
{
CheckReadOnly("ValidationEventHandler");
_valEventHandler += value;
}
remove
{
CheckReadOnly("ValidationEventHandler");
_valEventHandler -= value;
}
}
//
// Public methods
//
public void Reset()
{
CheckReadOnly("Reset");
Initialize();
}
public XmlReaderSettings Clone()
{
XmlReaderSettings clonedSettings = this.MemberwiseClone() as XmlReaderSettings;
clonedSettings.ReadOnly = false;
return clonedSettings;
}
//
// Internal methods
//
internal ValidationEventHandler GetEventHandler()
{
return _valEventHandler;
}
internal XmlReader CreateReader(String inputUri, XmlParserContext inputContext)
{
if (inputUri == null)
{
throw new ArgumentNullException(nameof(inputUri));
}
if (inputUri.Length == 0)
{
throw new ArgumentException(SR.XmlConvert_BadUri, nameof(inputUri));
}
// resolve and open the url
XmlResolver tmpResolver = this.GetXmlResolver();
if (tmpResolver == null)
{
tmpResolver = CreateDefaultResolver();
}
// create text XML reader
XmlReader reader = new XmlTextReaderImpl(inputUri, this, inputContext, tmpResolver);
// wrap with validating reader
if (this.ValidationType != ValidationType.None)
{
reader = AddValidation(reader);
}
if (_useAsync)
{
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
return reader;
}
internal XmlReader CreateReader(Stream input, Uri baseUri, string baseUriString, XmlParserContext inputContext)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
if (baseUriString == null)
{
if (baseUri == null)
{
baseUriString = string.Empty;
}
else
{
baseUriString = baseUri.ToString();
}
}
// create text XML reader
XmlReader reader = new XmlTextReaderImpl(input, null, 0, this, baseUri, baseUriString, inputContext, _closeInput);
// wrap with validating reader
if (this.ValidationType != ValidationType.None)
{
reader = AddValidation(reader);
}
if (_useAsync)
{
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
return reader;
}
internal XmlReader CreateReader(TextReader input, string baseUriString, XmlParserContext inputContext)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
if (baseUriString == null)
{
baseUriString = string.Empty;
}
// create xml text reader
XmlReader reader = new XmlTextReaderImpl(input, this, baseUriString, inputContext);
// wrap with validating reader
if (this.ValidationType != ValidationType.None)
{
reader = AddValidation(reader);
}
if (_useAsync)
{
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
return reader;
}
internal XmlReader CreateReader(XmlReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
return AddValidationAndConformanceWrapper(reader);
}
internal bool ReadOnly
{
get
{
return _isReadOnly;
}
set
{
_isReadOnly = value;
}
}
private void CheckReadOnly(string propertyName)
{
if (_isReadOnly)
{
throw new XmlException(SR.Xml_ReadOnlyProperty, this.GetType().Name + '.' + propertyName);
}
}
//
// Private methods
//
private void Initialize()
{
Initialize(null);
}
private void Initialize(XmlResolver resolver)
{
_nameTable = null;
_xmlResolver = resolver;
// limit the entity resolving to 10 million character. the caller can still
// override it to any other value or set it to zero for unlimiting it
_maxCharactersFromEntities = (long)1e7;
_lineNumberOffset = 0;
_linePositionOffset = 0;
_checkCharacters = true;
_conformanceLevel = ConformanceLevel.Document;
_ignoreWhitespace = false;
_ignorePIs = false;
_ignoreComments = false;
_dtdProcessing = DtdProcessing.Prohibit;
_closeInput = false;
_maxCharactersInDocument = 0;
_schemas = null;
_validationType = ValidationType.None;
_validationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints;
_validationFlags |= XmlSchemaValidationFlags.AllowXmlAttributes;
_useAsync = false;
_isReadOnly = false;
IsXmlResolverSet = false;
}
private static XmlResolver CreateDefaultResolver()
{
return new XmlSystemPathResolver();
}
internal XmlReader AddValidation(XmlReader reader)
{
if (_validationType == ValidationType.Schema)
{
XmlResolver resolver = GetXmlResolver_CheckConfig();
if (resolver == null &&
!this.IsXmlResolverSet)
{
resolver = new XmlUrlResolver();
}
reader = new XsdValidatingReader(reader, resolver, this);
}
else if (_validationType == ValidationType.DTD)
{
reader = CreateDtdValidatingReader(reader);
}
return reader;
}
private XmlReader AddValidationAndConformanceWrapper(XmlReader reader)
{
// wrap with DTD validating reader
if (_validationType == ValidationType.DTD)
{
reader = CreateDtdValidatingReader(reader);
}
// add conformance checking (must go after DTD validation because XmlValidatingReader works only on XmlTextReader),
// but before XSD validation because of typed value access
reader = AddConformanceWrapper(reader);
if (_validationType == ValidationType.Schema)
{
reader = new XsdValidatingReader(reader, GetXmlResolver_CheckConfig(), this);
}
return reader;
}
private XmlValidatingReaderImpl CreateDtdValidatingReader(XmlReader baseReader)
{
return new XmlValidatingReaderImpl(baseReader, this.GetEventHandler(), (this.ValidationFlags & XmlSchemaValidationFlags.ProcessIdentityConstraints) != 0);
}
internal XmlReader AddConformanceWrapper(XmlReader baseReader)
{
XmlReaderSettings baseReaderSettings = baseReader.Settings;
bool checkChars = false;
bool noWhitespace = false;
bool noComments = false;
bool noPIs = false;
DtdProcessing dtdProc = (DtdProcessing)(-1);
bool needWrap = false;
if (baseReaderSettings == null)
{
#pragma warning disable 618
if (_conformanceLevel != ConformanceLevel.Auto && _conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader))
{
throw new InvalidOperationException(SR.Format(SR.Xml_IncompatibleConformanceLevel, _conformanceLevel.ToString()));
}
// get the V1 XmlTextReader ref
XmlTextReader v1XmlTextReader = baseReader as XmlTextReader;
if (v1XmlTextReader == null)
{
XmlValidatingReader vr = baseReader as XmlValidatingReader;
if (vr != null)
{
v1XmlTextReader = (XmlTextReader)vr.Reader;
}
}
// assume the V1 readers already do all conformance checking;
// wrap only if IgnoreWhitespace, IgnoreComments, IgnoreProcessingInstructions or ProhibitDtd is true;
if (_ignoreWhitespace)
{
WhitespaceHandling wh = WhitespaceHandling.All;
// special-case our V1 readers to see if whey already filter whitespace
if (v1XmlTextReader != null)
{
wh = v1XmlTextReader.WhitespaceHandling;
}
if (wh == WhitespaceHandling.All)
{
noWhitespace = true;
needWrap = true;
}
}
if (_ignoreComments)
{
noComments = true;
needWrap = true;
}
if (_ignorePIs)
{
noPIs = true;
needWrap = true;
}
// DTD processing
DtdProcessing baseDtdProcessing = DtdProcessing.Parse;
if (v1XmlTextReader != null)
{
baseDtdProcessing = v1XmlTextReader.DtdProcessing;
}
if ((_dtdProcessing == DtdProcessing.Prohibit && baseDtdProcessing != DtdProcessing.Prohibit) ||
(_dtdProcessing == DtdProcessing.Ignore && baseDtdProcessing == DtdProcessing.Parse))
{
dtdProc = _dtdProcessing;
needWrap = true;
}
#pragma warning restore 618
}
else
{
if (_conformanceLevel != baseReaderSettings.ConformanceLevel && _conformanceLevel != ConformanceLevel.Auto)
{
throw new InvalidOperationException(SR.Format(SR.Xml_IncompatibleConformanceLevel, _conformanceLevel.ToString()));
}
if (_checkCharacters && !baseReaderSettings.CheckCharacters)
{
checkChars = true;
needWrap = true;
}
if (_ignoreWhitespace && !baseReaderSettings.IgnoreWhitespace)
{
noWhitespace = true;
needWrap = true;
}
if (_ignoreComments && !baseReaderSettings.IgnoreComments)
{
noComments = true;
needWrap = true;
}
if (_ignorePIs && !baseReaderSettings.IgnoreProcessingInstructions)
{
noPIs = true;
needWrap = true;
}
if ((_dtdProcessing == DtdProcessing.Prohibit && baseReaderSettings.DtdProcessing != DtdProcessing.Prohibit) ||
(_dtdProcessing == DtdProcessing.Ignore && baseReaderSettings.DtdProcessing == DtdProcessing.Parse))
{
dtdProc = _dtdProcessing;
needWrap = true;
}
}
if (needWrap)
{
IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver;
if (readerAsNSResolver != null)
{
return new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkChars, noWhitespace, noComments, noPIs, dtdProc);
}
else
{
return new XmlCharCheckingReader(baseReader, checkChars, noWhitespace, noComments, noPIs, dtdProc);
}
}
else
{
return baseReader;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``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 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.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using log4net;
namespace OpenSim.Framework.Monitoring
{
/// <summary>
/// Static class used to register/deregister checks on runtime conditions.
/// </summary>
public static class ChecksManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Subcommand used to list other stats.
public const string ListSubCommand = "list";
// All subcommands
public static HashSet<string> SubCommands = new HashSet<string> { ListSubCommand };
/// <summary>
/// Checks categorized by category/container/shortname
/// </summary>
/// <remarks>
/// Do not add or remove directly from this dictionary.
/// </remarks>
public static SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Check>>> RegisteredChecks
= new SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Check>>>();
public static void RegisterConsoleCommands(ICommandConsole console)
{
console.Commands.AddCommand(
"General",
false,
"show checks",
"show checks",
"Show checks configured for this server",
"If no argument is specified then info on all checks will be shown.\n"
+ "'list' argument will show check categories.\n"
+ "THIS FACILITY IS EXPERIMENTAL",
HandleShowchecksCommand);
}
public static void HandleShowchecksCommand(string module, string[] cmd)
{
ICommandConsole con = MainConsole.Instance;
if (cmd.Length > 2)
{
foreach (string name in cmd.Skip(2))
{
string[] components = name.Split('.');
string categoryName = components[0];
// string containerName = components.Length > 1 ? components[1] : null;
if (categoryName == ListSubCommand)
{
con.Output("check categories available are:");
foreach (string category in RegisteredChecks.Keys)
con.OutputFormat(" {0}", category);
}
// else
// {
// SortedDictionary<string, SortedDictionary<string, Check>> category;
// if (!Registeredchecks.TryGetValue(categoryName, out category))
// {
// con.OutputFormat("No such category as {0}", categoryName);
// }
// else
// {
// if (String.IsNullOrEmpty(containerName))
// {
// OutputConfiguredToConsole(con, category);
// }
// else
// {
// SortedDictionary<string, Check> container;
// if (category.TryGetValue(containerName, out container))
// {
// OutputContainerChecksToConsole(con, container);
// }
// else
// {
// con.OutputFormat("No such container {0} in category {1}", containerName, categoryName);
// }
// }
// }
// }
}
}
else
{
OutputAllChecksToConsole(con);
}
}
/// <summary>
/// Registers a statistic.
/// </summary>
/// <param name='stat'></param>
/// <returns></returns>
public static bool RegisterCheck(Check check)
{
SortedDictionary<string, SortedDictionary<string, Check>> category = null;
SortedDictionary<string, Check> container = null;
lock (RegisteredChecks)
{
// Check name is not unique across category/container/shortname key.
// XXX: For now just return false. This is to avoid problems in regression tests where all tests
// in a class are run in the same instance of the VM.
if (TryGetCheckParents(check, out category, out container))
return false;
// We take a copy-on-write approach here of replacing dictionaries when keys are added or removed.
// This means that we don't need to lock or copy them on iteration, which will be a much more
// common operation after startup.
if (container == null)
container = new SortedDictionary<string, Check>();
if (category == null)
category = new SortedDictionary<string, SortedDictionary<string, Check>>();
container[check.ShortName] = check;
category[check.Container] = container;
RegisteredChecks[check.Category] = category;
}
return true;
}
/// <summary>
/// Deregister an check
/// </summary>>
/// <param name='stat'></param>
/// <returns></returns>
public static bool DeregisterCheck(Check check)
{
SortedDictionary<string, SortedDictionary<string, Check>> category = null;
SortedDictionary<string, Check> container = null;
lock (RegisteredChecks)
{
if (!TryGetCheckParents(check, out category, out container))
return false;
if(container != null)
{
container.Remove(check.ShortName);
if(category != null && container.Count == 0)
{
category.Remove(check.Container);
if(category.Count == 0)
RegisteredChecks.Remove(check.Category);
}
}
return true;
}
}
public static bool TryGetCheckParents(
Check check,
out SortedDictionary<string, SortedDictionary<string, Check>> category,
out SortedDictionary<string, Check> container)
{
category = null;
container = null;
lock (RegisteredChecks)
{
if (RegisteredChecks.TryGetValue(check.Category, out category))
{
if (category.TryGetValue(check.Container, out container))
{
if (container.ContainsKey(check.ShortName))
return true;
}
}
}
return false;
}
public static void CheckChecks()
{
lock (RegisteredChecks)
{
foreach (SortedDictionary<string, SortedDictionary<string, Check>> category in RegisteredChecks.Values)
{
foreach (SortedDictionary<string, Check> container in category.Values)
{
foreach (Check check in container.Values)
{
if (!check.CheckIt())
m_log.WarnFormat(
"[CHECKS MANAGER]: Check {0}.{1}.{2} failed with message {3}", check.Category, check.Container, check.ShortName, check.LastFailureMessage);
}
}
}
}
}
private static void OutputAllChecksToConsole(ICommandConsole con)
{
foreach (var category in RegisteredChecks.Values)
{
OutputCategoryChecksToConsole(con, category);
}
}
private static void OutputCategoryChecksToConsole(
ICommandConsole con, SortedDictionary<string, SortedDictionary<string, Check>> category)
{
foreach (var container in category.Values)
{
OutputContainerChecksToConsole(con, container);
}
}
private static void OutputContainerChecksToConsole(ICommandConsole con, SortedDictionary<string, Check> container)
{
foreach (Check check in container.Values)
{
con.Output(check.ToConsoleString());
}
}
}
}
| |
// 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.
using System.Reflection;
using System.Text;
using System.Collections;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Diagnostics;
// The code below includes partial support for float/double and
// pointer sized enums.
//
// The type loader does not prohibit such enums, and older versions of
// the ECMA spec include them as possible enum types.
//
// However there are many things broken throughout the stack for
// float/double/intptr/uintptr enums. There was a conscious decision
// made to not fix the whole stack to work well for them because of
// the right behavior is often unclear, and it is hard to test and
// very low value because of such enums cannot be expressed in C#.
namespace System
{
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible
{
#region Private Constants
private const char enumSeparatorChar = ',';
private const String enumSeparatorString = ", ";
#endregion
#region Private Static Methods
private static TypeValuesAndNames GetCachedValuesAndNames(RuntimeType enumType, bool getNames)
{
TypeValuesAndNames entry = enumType.GenericCache as TypeValuesAndNames;
if (entry == null || (getNames && entry.Names == null))
{
ulong[] values = null;
String[] names = null;
bool isFlags = enumType.IsDefined(typeof(System.FlagsAttribute), false);
GetEnumValuesAndNames(
enumType.GetTypeHandleInternal(),
JitHelpers.GetObjectHandleOnStack(ref values),
JitHelpers.GetObjectHandleOnStack(ref names),
getNames);
entry = new TypeValuesAndNames(isFlags, values, names);
enumType.GenericCache = entry;
}
return entry;
}
private unsafe String InternalFormattedHexString()
{
fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
{
switch (InternalGetCorElementType())
{
case CorElementType.I1:
case CorElementType.U1:
return (*(byte*)pValue).ToString("X2", null);
case CorElementType.Boolean:
// direct cast from bool to byte is not allowed
return Convert.ToByte(*(bool*)pValue).ToString("X2", null);
case CorElementType.I2:
case CorElementType.U2:
case CorElementType.Char:
return (*(ushort*)pValue).ToString("X4", null);
case CorElementType.I4:
case CorElementType.U4:
return (*(uint*)pValue).ToString("X8", null);
case CorElementType.I8:
case CorElementType.U8:
return (*(ulong*)pValue).ToString("X16", null);
default:
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
}
private static String InternalFormattedHexString(object value)
{
TypeCode typeCode = Convert.GetTypeCode(value);
switch (typeCode)
{
case TypeCode.SByte:
return ((byte)(sbyte)value).ToString("X2", null);
case TypeCode.Byte:
return ((byte)value).ToString("X2", null);
case TypeCode.Boolean:
// direct cast from bool to byte is not allowed
return Convert.ToByte((bool)value).ToString("X2", null);
case TypeCode.Int16:
return ((UInt16)(Int16)value).ToString("X4", null);
case TypeCode.UInt16:
return ((UInt16)value).ToString("X4", null);
case TypeCode.Char:
return ((UInt16)(Char)value).ToString("X4", null);
case TypeCode.UInt32:
return ((UInt32)value).ToString("X8", null);
case TypeCode.Int32:
return ((UInt32)(Int32)value).ToString("X8", null);
case TypeCode.UInt64:
return ((UInt64)value).ToString("X16", null);
case TypeCode.Int64:
return ((UInt64)(Int64)value).ToString("X16", null);
// All unsigned types will be directly cast
default:
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
internal static String GetEnumName(RuntimeType eT, ulong ulValue)
{
Debug.Assert(eT != null);
ulong[] ulValues = Enum.InternalGetValues(eT);
int index = Array.BinarySearch(ulValues, ulValue);
if (index >= 0)
{
string[] names = Enum.InternalGetNames(eT);
return names[index];
}
return null; // return null so the caller knows to .ToString() the input
}
private static String InternalFormat(RuntimeType eT, ulong value)
{
Debug.Assert(eT != null);
// These values are sorted by value. Don't change this
TypeValuesAndNames entry = GetCachedValuesAndNames(eT, true);
if (!entry.IsFlag) // Not marked with Flags attribute
{
return Enum.GetEnumName(eT, value);
}
else // These are flags OR'ed together (We treat everything as unsigned types)
{
return InternalFlagsFormat(eT, entry, value);
}
}
private static String InternalFlagsFormat(RuntimeType eT, ulong result)
{
// These values are sorted by value. Don't change this
TypeValuesAndNames entry = GetCachedValuesAndNames(eT, true);
return InternalFlagsFormat(eT, entry, result);
}
private static String InternalFlagsFormat(RuntimeType eT, TypeValuesAndNames entry, ulong result)
{
Debug.Assert(eT != null);
String[] names = entry.Names;
ulong[] values = entry.Values;
Debug.Assert(names.Length == values.Length);
int index = values.Length - 1;
StringBuilder sb = StringBuilderCache.Acquire();
bool firstTime = true;
ulong saveResult = result;
// We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied
// to minimize the comparsions required. This code works the same for the best/worst case. In general the number of
// items in an enum are sufficiently small and not worth the optimization.
while (index >= 0)
{
if ((index == 0) && (values[index] == 0))
break;
if ((result & values[index]) == values[index])
{
result -= values[index];
if (!firstTime)
sb.Insert(0, enumSeparatorString);
sb.Insert(0, names[index]);
firstTime = false;
}
index--;
}
string returnString;
if (result != 0)
{
// We were unable to represent this number as a bitwise or of valid flags
returnString = null; // return null so the caller knows to .ToString() the input
}
else if (saveResult == 0)
{
// For the cases when we have zero
if (values.Length > 0 && values[0] == 0)
{
returnString = names[0]; // Zero was one of the enum values.
}
else
{
returnString = "0";
}
}
else
{
returnString = sb.ToString(); // Return the string representation
}
StringBuilderCache.Release(sb);
return returnString;
}
internal static ulong ToUInt64(Object value)
{
// Helper function to silently convert the value to UInt64 from the other base types for enum without throwing an exception.
// This is need since the Convert functions do overflow checks.
TypeCode typeCode = Convert.GetTypeCode(value);
ulong result;
switch (typeCode)
{
case TypeCode.SByte:
result = (ulong)(sbyte)value;
break;
case TypeCode.Byte:
result = (byte)value;
break;
case TypeCode.Boolean:
// direct cast from bool to byte is not allowed
result = Convert.ToByte((bool)value);
break;
case TypeCode.Int16:
result = (ulong)(Int16)value;
break;
case TypeCode.UInt16:
result = (UInt16)value;
break;
case TypeCode.Char:
result = (UInt16)(Char)value;
break;
case TypeCode.UInt32:
result = (UInt32)value;
break;
case TypeCode.Int32:
result = (ulong)(int)value;
break;
case TypeCode.UInt64:
result = (ulong)value;
break;
case TypeCode.Int64:
result = (ulong)(Int64)value;
break;
// All unsigned types will be directly cast
default:
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
return result;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int InternalCompareTo(Object o1, Object o2);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern RuntimeType InternalGetUnderlyingType(RuntimeType enumType);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[System.Security.SuppressUnmanagedCodeSecurity]
private static extern void GetEnumValuesAndNames(RuntimeTypeHandle enumType, ObjectHandleOnStack values, ObjectHandleOnStack names, bool getNames);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern Object InternalBoxEnum(RuntimeType enumType, long value);
#endregion
#region Public Static Methods
private enum ParseFailureKind
{
None = 0,
Argument = 1,
ArgumentNull = 2,
ArgumentWithParameter = 3,
UnhandledException = 4
}
// This will store the result of the parsing.
private struct EnumResult
{
internal object parsedEnum;
internal bool canThrow;
internal ParseFailureKind m_failure;
internal string m_failureMessageID;
internal string m_failureParameter;
internal object m_failureMessageFormatArgument;
internal Exception m_innerException;
internal void SetFailure(Exception unhandledException)
{
m_failure = ParseFailureKind.UnhandledException;
m_innerException = unhandledException;
}
internal void SetFailure(ParseFailureKind failure, string failureParameter)
{
m_failure = failure;
m_failureParameter = failureParameter;
if (canThrow)
throw GetEnumParseException();
}
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument)
{
m_failure = failure;
m_failureMessageID = failureMessageID;
m_failureMessageFormatArgument = failureMessageFormatArgument;
if (canThrow)
throw GetEnumParseException();
}
internal Exception GetEnumParseException()
{
switch (m_failure)
{
case ParseFailureKind.Argument:
return new ArgumentException(SR.GetResourceString(m_failureMessageID));
case ParseFailureKind.ArgumentNull:
return new ArgumentNullException(m_failureParameter);
case ParseFailureKind.ArgumentWithParameter:
return new ArgumentException(SR.Format(SR.GetResourceString(m_failureMessageID), m_failureMessageFormatArgument));
case ParseFailureKind.UnhandledException:
return m_innerException;
default:
Debug.Assert(false, "Unknown EnumParseFailure: " + m_failure);
return new ArgumentException(SR.Arg_EnumValueNotFound);
}
}
}
public static bool TryParse(Type enumType, String value, out Object result)
{
return TryParse(enumType, value, false, out result);
}
public static bool TryParse(Type enumType, String value, bool ignoreCase, out Object result)
{
result = null;
EnumResult parseResult = new EnumResult();
bool retValue;
if (retValue = TryParseEnum(enumType, value, ignoreCase, ref parseResult))
result = parseResult.parsedEnum;
return retValue;
}
public static bool TryParse<TEnum>(String value, out TEnum result) where TEnum : struct
{
return TryParse(value, false, out result);
}
public static bool TryParse<TEnum>(String value, bool ignoreCase, out TEnum result) where TEnum : struct
{
result = default(TEnum);
EnumResult parseResult = new EnumResult();
bool retValue;
if (retValue = TryParseEnum(typeof(TEnum), value, ignoreCase, ref parseResult))
result = (TEnum)parseResult.parsedEnum;
return retValue;
}
public static Object Parse(Type enumType, String value)
{
return Parse(enumType, value, false);
}
public static Object Parse(Type enumType, String value, bool ignoreCase)
{
EnumResult parseResult = new EnumResult() { canThrow = true };
if (TryParseEnum(enumType, value, ignoreCase, ref parseResult))
return parseResult.parsedEnum;
else
throw parseResult.GetEnumParseException();
}
public static TEnum Parse<TEnum>(String value) where TEnum : struct
{
return Parse<TEnum>(value, false);
}
public static TEnum Parse<TEnum>(String value, bool ignoreCase) where TEnum : struct
{
EnumResult parseResult = new EnumResult() { canThrow = true };
if (TryParseEnum(typeof(TEnum), value, ignoreCase, ref parseResult))
return (TEnum)parseResult.parsedEnum;
else
throw parseResult.GetEnumParseException();
}
private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, ref EnumResult parseResult)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
if (value == null)
{
parseResult.SetFailure(ParseFailureKind.ArgumentNull, nameof(value));
return false;
}
int firstNonWhitespaceIndex = -1;
for (int i = 0; i < value.Length; i++)
{
if (!Char.IsWhiteSpace(value[i]))
{
firstNonWhitespaceIndex = i;
break;
}
}
if (firstNonWhitespaceIndex == -1)
{
parseResult.SetFailure(ParseFailureKind.Argument, nameof(SR.Arg_MustContainEnumInfo), null);
return false;
}
// We have 2 code paths here. One if they are values else if they are Strings.
// values will have the first character as as number or a sign.
ulong result = 0;
char firstNonWhitespaceChar = value[firstNonWhitespaceIndex];
if (Char.IsDigit(firstNonWhitespaceChar) || firstNonWhitespaceChar == '-' || firstNonWhitespaceChar == '+')
{
Type underlyingType = GetUnderlyingType(enumType);
Object temp;
try
{
value = value.Trim();
temp = Convert.ChangeType(value, underlyingType, CultureInfo.InvariantCulture);
parseResult.parsedEnum = ToObject(enumType, temp);
return true;
}
catch (FormatException)
{ // We need to Parse this as a String instead. There are cases
// when you tlbimp enums that can have values of the form "3D".
// Don't fix this code.
}
catch (Exception ex)
{
if (parseResult.canThrow)
throw;
else
{
parseResult.SetFailure(ex);
return false;
}
}
}
// Find the field. Let's assume that these are always static classes
// because the class is an enum.
TypeValuesAndNames entry = GetCachedValuesAndNames(rtType, true);
String[] enumNames = entry.Names;
ulong[] enumValues = entry.Values;
StringComparison comparison = ignoreCase ?
StringComparison.OrdinalIgnoreCase :
StringComparison.Ordinal;
int valueIndex = firstNonWhitespaceIndex;
while (valueIndex <= value.Length) // '=' is to handle invalid case of an ending comma
{
// Find the next separator, if there is one, otherwise the end of the string.
int endIndex = value.IndexOf(enumSeparatorChar, valueIndex);
if (endIndex == -1)
{
endIndex = value.Length;
}
// Shift the starting and ending indices to eliminate whitespace
int endIndexNoWhitespace = endIndex;
while (valueIndex < endIndex && Char.IsWhiteSpace(value[valueIndex])) valueIndex++;
while (endIndexNoWhitespace > valueIndex && Char.IsWhiteSpace(value[endIndexNoWhitespace - 1])) endIndexNoWhitespace--;
int valueSubstringLength = endIndexNoWhitespace - valueIndex;
// Try to match this substring against each enum name
bool success = false;
for (int i = 0; i < enumNames.Length; i++)
{
if (enumNames[i].Length == valueSubstringLength &&
string.Compare(enumNames[i], 0, value, valueIndex, valueSubstringLength, comparison) == 0)
{
result |= enumValues[i];
success = true;
break;
}
}
// If we couldn't find a match, throw an argument exception.
if (!success)
{
// Not found, throw an argument exception.
parseResult.SetFailure(ParseFailureKind.ArgumentWithParameter, nameof(SR.Arg_EnumValueNotFound), value);
return false;
}
// Move our pointer to the ending index to go again.
valueIndex = endIndex + 1;
}
try
{
parseResult.parsedEnum = ToObject(enumType, result);
return true;
}
catch (Exception ex)
{
if (parseResult.canThrow)
throw;
else
{
parseResult.SetFailure(ex);
return false;
}
}
}
public static Type GetUnderlyingType(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
return enumType.GetEnumUnderlyingType();
}
public static Array GetValues(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
return enumType.GetEnumValues();
}
internal static ulong[] InternalGetValues(RuntimeType enumType)
{
// Get all of the values
return GetCachedValuesAndNames(enumType, false).Values;
}
public static String GetName(Type enumType, Object value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
return enumType.GetEnumName(value);
}
public static String[] GetNames(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
return enumType.GetEnumNames();
}
internal static String[] InternalGetNames(RuntimeType enumType)
{
// Get all of the names
return GetCachedValuesAndNames(enumType, true).Names;
}
public static Object ToObject(Type enumType, Object value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
// Delegate rest of error checking to the other functions
TypeCode typeCode = Convert.GetTypeCode(value);
switch (typeCode)
{
case TypeCode.Int32:
return ToObject(enumType, (int)value);
case TypeCode.SByte:
return ToObject(enumType, (sbyte)value);
case TypeCode.Int16:
return ToObject(enumType, (short)value);
case TypeCode.Int64:
return ToObject(enumType, (long)value);
case TypeCode.UInt32:
return ToObject(enumType, (uint)value);
case TypeCode.Byte:
return ToObject(enumType, (byte)value);
case TypeCode.UInt16:
return ToObject(enumType, (ushort)value);
case TypeCode.UInt64:
return ToObject(enumType, (ulong)value);
case TypeCode.Char:
return ToObject(enumType, (char)value);
case TypeCode.Boolean:
return ToObject(enumType, (bool)value);
default:
// All unsigned types will be directly cast
throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value));
}
}
public static bool IsDefined(Type enumType, Object value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
return enumType.IsEnumDefined(value);
}
public static String Format(Type enumType, Object value, String format)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
if (value == null)
throw new ArgumentNullException(nameof(value));
if (format == null)
throw new ArgumentNullException(nameof(format));
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
// Check if both of them are of the same type
Type valueType = value.GetType();
Type underlyingType = GetUnderlyingType(enumType);
// If the value is an Enum then we need to extract the underlying value from it
if (valueType.IsEnum)
{
if (!valueType.IsEquivalentTo(enumType))
throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, valueType.ToString(), enumType.ToString()));
if (format.Length != 1)
{
// all acceptable format string are of length 1
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
return ((Enum)value).ToString(format);
}
// The value must be of the same type as the Underlying type of the Enum
else if (valueType != underlyingType)
{
throw new ArgumentException(SR.Format(SR.Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType, valueType.ToString(), underlyingType.ToString()));
}
if (format.Length != 1)
{
// all acceptable format string are of length 1
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
char formatCh = format[0];
if (formatCh == 'G' || formatCh == 'g')
return GetEnumName(rtType, ToUInt64(value)) ?? value.ToString();
if (formatCh == 'D' || formatCh == 'd')
return value.ToString();
if (formatCh == 'X' || formatCh == 'x')
return InternalFormattedHexString(value);
if (formatCh == 'F' || formatCh == 'f')
return Enum.InternalFlagsFormat(rtType, ToUInt64(value)) ?? value.ToString();
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
#endregion
#region Definitions
private class TypeValuesAndNames
{
// Each entry contains a list of sorted pair of enum field names and values, sorted by values
public TypeValuesAndNames(bool isFlag, ulong[] values, String[] names)
{
this.IsFlag = isFlag;
this.Values = values;
this.Names = names;
}
public bool IsFlag;
public ulong[] Values;
public String[] Names;
}
#endregion
#region Private Methods
internal unsafe Object GetValue()
{
fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
{
switch (InternalGetCorElementType())
{
case CorElementType.I1:
return *(sbyte*)pValue;
case CorElementType.U1:
return *(byte*)pValue;
case CorElementType.Boolean:
return *(bool*)pValue;
case CorElementType.I2:
return *(short*)pValue;
case CorElementType.U2:
return *(ushort*)pValue;
case CorElementType.Char:
return *(char*)pValue;
case CorElementType.I4:
return *(int*)pValue;
case CorElementType.U4:
return *(uint*)pValue;
case CorElementType.R4:
return *(float*)pValue;
case CorElementType.I8:
return *(long*)pValue;
case CorElementType.U8:
return *(ulong*)pValue;
case CorElementType.R8:
return *(double*)pValue;
case CorElementType.I:
return *(IntPtr*)pValue;
case CorElementType.U:
return *(UIntPtr*)pValue;
default:
Debug.Assert(false, "Invalid primitive type");
return null;
}
}
}
private unsafe ulong ToUInt64()
{
fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
{
switch (InternalGetCorElementType())
{
case CorElementType.I1:
return (ulong)*(sbyte*)pValue;
case CorElementType.U1:
return *(byte*)pValue;
case CorElementType.Boolean:
return Convert.ToUInt64(*(bool*)pValue, CultureInfo.InvariantCulture);
case CorElementType.I2:
return (ulong)*(short*)pValue;
case CorElementType.U2:
case CorElementType.Char:
return *(ushort*)pValue;
case CorElementType.I4:
return (ulong)*(int*)pValue;
case CorElementType.U4:
case CorElementType.R4:
return *(uint*)pValue;
case CorElementType.I8:
return (ulong)*(long*)pValue;
case CorElementType.U8:
case CorElementType.R8:
return *(ulong*)pValue;
case CorElementType.I:
if (IntPtr.Size == 8)
{
return *(ulong*)pValue;
}
else
{
return (ulong)*(int*)pValue;
}
case CorElementType.U:
if (IntPtr.Size == 8)
{
return *(ulong*)pValue;
}
else
{
return *(uint*)pValue;
}
default:
Debug.Assert(false, "Invalid primitive type");
return 0;
}
}
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool InternalHasFlag(Enum flags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern CorElementType InternalGetCorElementType();
#endregion
#region Object Overrides
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern override bool Equals(Object obj);
public override unsafe int GetHashCode()
{
// CONTRACT with the runtime: GetHashCode of enum types is implemented as GetHashCode of the underlying type.
// The runtime can bypass calls to Enum::GetHashCode and call the underlying type's GetHashCode directly
// to avoid boxing the enum.
fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data)
{
switch (InternalGetCorElementType())
{
case CorElementType.I1:
return (*(sbyte*)pValue).GetHashCode();
case CorElementType.U1:
return (*(byte*)pValue).GetHashCode();
case CorElementType.Boolean:
return (*(bool*)pValue).GetHashCode();
case CorElementType.I2:
return (*(short*)pValue).GetHashCode();
case CorElementType.U2:
return (*(ushort*)pValue).GetHashCode();
case CorElementType.Char:
return (*(char*)pValue).GetHashCode();
case CorElementType.I4:
return (*(int*)pValue).GetHashCode();
case CorElementType.U4:
return (*(uint*)pValue).GetHashCode();
case CorElementType.R4:
return (*(float*)pValue).GetHashCode();
case CorElementType.I8:
return (*(long*)pValue).GetHashCode();
case CorElementType.U8:
return (*(ulong*)pValue).GetHashCode();
case CorElementType.R8:
return (*(double*)pValue).GetHashCode();
case CorElementType.I:
return (*(IntPtr*)pValue).GetHashCode();
case CorElementType.U:
return (*(UIntPtr*)pValue).GetHashCode();
default:
Debug.Assert(false, "Invalid primitive type");
return 0;
}
}
}
public override String ToString()
{
// Returns the value in a human readable format. For PASCAL style enums who's value maps directly the name of the field is returned.
// For PASCAL style enums who's values do not map directly the decimal value of the field is returned.
// For BitFlags (indicated by the Flags custom attribute): If for each bit that is set in the value there is a corresponding constant
//(a pure power of 2), then the OR string (ie "Red | Yellow") is returned. Otherwise, if the value is zero or if you can't create a string that consists of
// pure powers of 2 OR-ed together, you return a hex value
// Try to see if its one of the enum values, then we return a String back else the value
return Enum.InternalFormat((RuntimeType)GetType(), ToUInt64()) ?? GetValue().ToString();
}
#endregion
#region IFormattable
[Obsolete("The provider argument is not used. Please use ToString(String).")]
public String ToString(String format, IFormatProvider provider)
{
return ToString(format);
}
#endregion
#region IComparable
public int CompareTo(Object target)
{
const int retIncompatibleMethodTables = 2; // indicates that the method tables did not match
const int retInvalidEnumType = 3; // indicates that the enum was of an unknown/unsupported underlying type
if (this == null)
throw new NullReferenceException();
int ret = InternalCompareTo(this, target);
if (ret < retIncompatibleMethodTables)
{
// -1, 0 and 1 are the normal return codes
return ret;
}
else if (ret == retIncompatibleMethodTables)
{
Type thisType = this.GetType();
Type targetType = target.GetType();
throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, targetType.ToString(), thisType.ToString()));
}
else
{
// assert valid return code (3)
Debug.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid");
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
#endregion
#region Public Methods
public String ToString(String format)
{
char formatCh;
if (format == null || format.Length == 0)
formatCh = 'G';
else if (format.Length != 1)
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
else
formatCh = format[0];
if (formatCh == 'G' || formatCh == 'g')
return ToString();
if (formatCh == 'D' || formatCh == 'd')
return GetValue().ToString();
if (formatCh == 'X' || formatCh == 'x')
return InternalFormattedHexString();
if (formatCh == 'F' || formatCh == 'f')
return InternalFlagsFormat((RuntimeType)GetType(), ToUInt64()) ?? GetValue().ToString();
throw new FormatException(SR.Format_InvalidEnumFormatSpecification);
}
[Obsolete("The provider argument is not used. Please use ToString().")]
public String ToString(IFormatProvider provider)
{
return ToString();
}
[Intrinsic]
public Boolean HasFlag(Enum flag)
{
if (flag == null)
throw new ArgumentNullException(nameof(flag));
if (!this.GetType().IsEquivalentTo(flag.GetType()))
{
throw new ArgumentException(SR.Format(SR.Argument_EnumTypeDoesNotMatch, flag.GetType(), this.GetType()));
}
return InternalHasFlag(flag);
}
#endregion
#region IConvertable
public TypeCode GetTypeCode()
{
switch (InternalGetCorElementType())
{
case CorElementType.I1:
return TypeCode.SByte;
case CorElementType.U1:
return TypeCode.Byte;
case CorElementType.Boolean:
return TypeCode.Boolean;
case CorElementType.I2:
return TypeCode.Int16;
case CorElementType.U2:
return TypeCode.UInt16;
case CorElementType.Char:
return TypeCode.Char;
case CorElementType.I4:
return TypeCode.Int32;
case CorElementType.U4:
return TypeCode.UInt32;
case CorElementType.I8:
return TypeCode.Int64;
case CorElementType.U8:
return TypeCode.UInt64;
default:
throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType);
}
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture);
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture);
}
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Enum", "DateTime"));
}
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
#endregion
#region ToObject
[CLSCompliant(false)]
public static Object ToObject(Type enumType, sbyte value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
public static Object ToObject(Type enumType, short value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
public static Object ToObject(Type enumType, int value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
public static Object ToObject(Type enumType, byte value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
[CLSCompliant(false)]
public static Object ToObject(Type enumType, ushort value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
[CLSCompliant(false)]
public static Object ToObject(Type enumType, uint value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
public static Object ToObject(Type enumType, long value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
[CLSCompliant(false)]
public static Object ToObject(Type enumType, ulong value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, unchecked((long)value));
}
private static Object ToObject(Type enumType, char value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value);
}
private static Object ToObject(Type enumType, bool value)
{
if (enumType == null)
throw new ArgumentNullException(nameof(enumType));
if (!enumType.IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType));
RuntimeType rtType = enumType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType));
return InternalBoxEnum(rtType, value ? 1 : 0);
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
/// Returns true if the current quality settings equal
/// this graphics quality level.
function GraphicsQualityLevel::isCurrent( %this )
{
// Test each pref to see if the current value
// equals our stored value.
for ( %i=0; %i < %this.count(); %i++ )
{
%pref = %this.getKey( %i );
%value = %this.getValue( %i );
if ( getVariable( %pref ) !$= %value )
return false;
}
return true;
}
/// Applies the graphics quality settings and calls
/// 'onApply' on itself or its parent group if its
/// been overloaded.
function GraphicsQualityLevel::apply( %this )
{
for ( %i=0; %i < %this.count(); %i++ )
{
%pref = %this.getKey( %i );
%value = %this.getValue( %i );
setVariable( %pref, %value );
}
// If we have an overloaded onApply method then
// call it now to finalize the changes.
if ( %this.isMethod( "onApply" ) )
%this.onApply();
else
{
%group = %this.getGroup();
if ( isObject( %group ) && %group.isMethod( "onApply" ) )
%group.onApply( %this );
}
}
function GraphicsQualityPopup::init( %this, %qualityGroup )
{
assert( isObject( %this ) );
assert( isObject( %qualityGroup ) );
// Clear the existing content first.
%this.clear();
// Fill it.
%select = -1;
for ( %i=0; %i < %qualityGroup.getCount(); %i++ )
{
%level = %qualityGroup.getObject( %i );
if ( %level.isCurrent() )
%select = %i;
%this.add( %level.getInternalName(), %i );
}
// Setup a default selection.
if ( %select == -1 )
%this.setText( "Custom" );
else
%this.setSelected( %select );
}
function GraphicsQualityPopup::apply( %this, %qualityGroup, %testNeedApply )
{
assert( isObject( %this ) );
assert( isObject( %qualityGroup ) );
%quality = %this.getText();
%index = %this.findText( %quality );
if ( %index == -1 )
return false;
%level = %qualityGroup.getObject( %index );
if ( isObject( %level ) && !%level.isCurrent() )
{
if ( %testNeedApply )
return true;
%level.apply();
}
return false;
}
function OptionsDlg::setPane(%this, %pane)
{
%this-->OptAudioPane.setVisible(false);
%this-->OptGraphicsPane.setVisible(false);
%this-->OptNetworkPane.setVisible(false);
%this-->OptControlsPane.setVisible(false);
%this.findObjectByInternalName( "Opt" @ %pane @ "Pane", true ).setVisible(true);
%this.fillRemapList();
// Update the state of the apply button.
%this._updateApplyState();
}
function OptionsDlg::onWake(%this)
{
if ( isFunction("getWebDeployment") && getWebDeployment() )
{
// Cannot enable full screen under web deployment
%this-->OptGraphicsFullscreenToggle.setStateOn( false );
%this-->OptGraphicsFullscreenToggle.setVisible( false );
}
else
{
%this-->OptGraphicsFullscreenToggle.setStateOn( Canvas.isFullScreen() );
}
%this-->OptGraphicsVSyncToggle.setStateOn( !$pref::Video::disableVerticalSync );
OptionsDlg.initResMenu();
%resSelId = OptionsDlg-->OptGraphicsResolutionMenu.findText( _makePrettyResString( $pref::Video::mode ) );
if( %resSelId != -1 )
OptionsDlg-->OptGraphicsResolutionMenu.setSelected( %resSelId );
OptGraphicsDriverMenu.clear();
%buffer = getDisplayDeviceList();
%count = getFieldCount( %buffer );
for(%i = 0; %i < %count; %i++)
OptGraphicsDriverMenu.add(getField(%buffer, %i), %i);
%selId = OptGraphicsDriverMenu.findText( getDisplayDeviceInformation() );
if ( %selId == -1 )
OptGraphicsDriverMenu.setFirstSelected();
else
OptGraphicsDriverMenu.setSelected( %selId );
// Setup the graphics quality dropdown menus.
%this-->OptMeshQualityPopup.init( MeshQualityGroup );
%this-->OptTextureQualityPopup.init( TextureQualityGroup );
%this-->OptLightingQualityPopup.init( LightingQualityGroup );
%this-->OptShaderQualityPopup.init( ShaderQualityGroup );
// Setup the anisotropic filtering menu.
%ansioCtrl = %this-->OptAnisotropicPopup;
%ansioCtrl.clear();
%ansioCtrl.add( "Off", 0 );
%ansioCtrl.add( "4X", 4 );
%ansioCtrl.add( "8X", 8 );
%ansioCtrl.add( "16X", 16 );
%ansioCtrl.setSelected( $pref::Video::defaultAnisotropy, false );
// set up the Refresh Rate menu.
%refreshMenu = %this-->OptRefreshSelectMenu;
%refreshMenu.clear();
// %refreshMenu.add("Auto", 60);
%refreshMenu.add("60", 60);
%refreshMenu.add("75", 75);
%refreshMenu.setSelected( getWord( $pref::Video::mode, $WORD::REFRESH ) );
// Audio
//OptAudioHardwareToggle.setStateOn($pref::SFX::useHardware);
//OptAudioHardwareToggle.setActive( true );
%this-->OptAudioVolumeMaster.setValue( $pref::SFX::masterVolume );
%this-->OptAudioVolumeShell.setValue( $pref::SFX::channelVolume[ $GuiAudioType] );
%this-->OptAudioVolumeSim.setValue( $pref::SFX::channelVolume[ $SimAudioType ] );
%this-->OptAudioVolumeMusic.setValue( $pref::SFX::channelVolume[ $MusicAudioType ] );
OptAudioProviderList.clear();
%buffer = sfxGetAvailableDevices();
%count = getRecordCount( %buffer );
for(%i = 0; %i < %count; %i++)
{
%record = getRecord(%buffer, %i);
%provider = getField(%record, 0);
if ( OptAudioProviderList.findText( %provider ) == -1 )
OptAudioProviderList.add( %provider, %i );
}
OptAudioProviderList.sort();
%selId = OptAudioProviderList.findText($pref::SFX::provider);
if ( %selId == -1 )
OptAudioProviderList.setFirstSelected();
else
OptAudioProviderList.setSelected( %selId );
// Populate the Anti-aliasing popup.
%aaMenu = %this-->OptAAQualityPopup;
%aaMenu.clear();
%aaMenu.Add( "Off", 0 );
%aaMenu.Add( "1x", 1 );
%aaMenu.Add( "2x", 2 );
%aaMenu.Add( "4x", 4 );
%aaMenu.setSelected( getWord( $pref::Video::mode, $WORD::AA ) );
OptMouseSensitivity.value = $pref::Input::LinkMouseSensitivity;
// Set the graphics pane to start.
%this-->OptGraphicsButton.performClick();
}
function OptionsDlg::onSleep(%this)
{
// write out the control config into the rw/config.cs file
moveMap.save( "marble/client/config.cs" );
}
function OptGraphicsDriverMenu::onSelect( %this, %id, %text )
{
// Attempt to keep the same resolution settings:
%resMenu = OptionsDlg-->OptGraphicsResolutionMenu;
%currRes = %resMenu.getText();
// If its empty the use the current.
if ( %currRes $= "" )
%currRes = _makePrettyResString( Canvas.getVideoMode() );
// Fill the resolution list.
optionsDlg.initResMenu();
// Try to select the previous settings:
%selId = %resMenu.findText( %currRes );
if ( %selId == -1 )
%selId = 0;
%resMenu.setSelected( %selId );
OptionsDlg._updateApplyState();
}
function _makePrettyResString( %resString )
{
%width = getWord( %resString, $WORD::RES_X );
%height = getWord( %resString, $WORD::RES_Y );
%aspect = %width / %height;
%aspect = mRound( %aspect * 100 ) * 0.01;
switch$( %aspect )
{
case "1.33":
%aspect = "4:3";
case "1.78":
%aspect = "16:9";
default:
%aspect = "";
}
%outRes = %width @ " x " @ %height;
if ( %aspect !$= "" )
%outRes = %outRes @ " (" @ %aspect @ ")";
return %outRes;
}
function OptionsDlg::initResMenu( %this )
{
// Clear out previous values
%resMenu = %this-->OptGraphicsResolutionMenu;
%resMenu.clear();
// If we are in a browser then we can't change our resolution through
// the options dialog
if (getWebDeployment())
{
%count = 0;
%currRes = getWords(Canvas.getVideoMode(), $WORD::RES_X, $WORD::RES_Y);
%resMenu.add(%currRes, %count);
%count++;
return;
}
// Loop through all and add all valid resolutions
%count = 0;
%resCount = Canvas.getModeCount();
for (%i = 0; %i < %resCount; %i++)
{
%testResString = Canvas.getMode( %i );
%testRes = _makePrettyResString( %testResString );
// Only add to list if it isn't there already.
if (%resMenu.findText(%testRes) == -1)
{
%resMenu.add(%testRes, %i);
%count++;
}
}
%resMenu.sort();
}
function OptionsDlg::applyGraphics( %this, %testNeedApply )
{
%newAdapter = OptGraphicsDriverMenu.getText();
%numAdapters = GFXInit::getAdapterCount();
%newDevice = $pref::Video::displayDevice;
for( %i = 0; %i < %numAdapters; %i ++ )
if( GFXInit::getAdapterName( %i ) $= %newAdapter )
{
%newDevice = GFXInit::getAdapterType( %i );
break;
}
// Change the device.
if ( %newDevice !$= $pref::Video::displayDevice )
{
if ( %testNeedApply )
return true;
$pref::Video::displayDevice = %newDevice;
if( %newAdapter !$= getDisplayDeviceInformation() )
MessageBoxOK( "Change requires restart", "Please restart the game for a display device change to take effect." );
}
// Gather the new video mode.
if ( isFunction("getWebDeployment") && getWebDeployment() )
{
// Under web deployment, we use the custom resolution rather than a Canvas
// defined one.
%newRes = %this-->OptGraphicsResolutionMenu.getText();
}
else
{
%newRes = getWords( Canvas.getMode( %this-->OptGraphicsResolutionMenu.getSelected() ), $WORD::RES_X, $WORD::RES_Y );
}
%newBpp = 32; // ... its not 1997 anymore.
%newFullScreen = %this-->OptGraphicsFullscreenToggle.getValue() ? "true" : "false";
%newRefresh = %this-->OptRefreshSelectMenu.getSelected();
%newVsync = !%this-->OptGraphicsVSyncToggle.getValue();
%newFSAA = %this-->OptAAQualityPopup.getSelected();
// Under web deployment we can't be full screen.
if ( isFunction("getWebDeployment") && getWebDeployment() )
{
%newFullScreen = false;
}
else if ( %newFullScreen $= "false" )
{
// If we're in windowed mode switch the fullscreen check
// if the resolution is bigger than the desktop.
%deskRes = getDesktopResolution();
%deskResX = getWord(%deskRes, $WORD::RES_X);
%deskResY = getWord(%deskRes, $WORD::RES_Y);
if ( getWord( %newRes, $WORD::RES_X ) > %deskResX ||
getWord( %newRes, $WORD::RES_Y ) > %deskResY )
{
%newFullScreen = "true";
%this-->OptGraphicsFullscreenToggle.setStateOn( true );
}
}
// Build the final mode string.
%newMode = %newRes SPC %newFullScreen SPC %newBpp SPC %newRefresh SPC %newFSAA;
// Change the video mode.
if ( %newMode !$= $pref::Video::mode ||
%newVsync != $pref::Video::disableVerticalSync )
{
if ( %testNeedApply )
return true;
$pref::Video::mode = %newMode;
$pref::Video::disableVerticalSync = %newVsync;
configureCanvas();
}
// Test and apply the graphics settings.
if ( %this-->OptMeshQualityPopup.apply( MeshQualityGroup, %testNeedApply ) ) return true;
if ( %this-->OptTextureQualityPopup.apply( TextureQualityGroup, %testNeedApply ) ) return true;
if ( %this-->OptLightingQualityPopup.apply( LightingQualityGroup, %testNeedApply ) ) return true;
if ( %this-->OptShaderQualityPopup.apply( ShaderQualityGroup, %testNeedApply ) ) return true;
// Check the anisotropic filtering.
%level = %this-->OptAnisotropicPopup.getSelected();
if ( %level != $pref::Video::defaultAnisotropy )
{
if ( %testNeedApply )
return true;
$pref::Video::defaultAnisotropy = %level;
}
// If we're applying the state then recheck the
// state to update the apply button.
if ( !%testNeedApply )
%this._updateApplyState();
return false;
}
function OptionsDlg::_updateApplyState( %this )
{
%applyCtrl = %this-->Apply;
%graphicsPane = %this-->OptGraphicsPane;
assert( isObject( %applyCtrl ) );
assert( isObject( %graphicsPane ) );
%applyCtrl.active = %graphicsPane.isVisible() && %this.applyGraphics( true );
}
function OptionsDlg::_autoDetectQuality( %this )
{
%msg = GraphicsQualityAutodetect();
%this.onWake();
if ( %msg !$= "" )
{
MessageBoxOK( "Notice", %msg );
}
}
$RemapCount = 0;
$RemapName[$RemapCount] = "Forward";
$RemapCmd[$RemapCount] = "moveforward";
$RemapCount++;
$RemapName[$RemapCount] = "Backward";
$RemapCmd[$RemapCount] = "movebackward";
$RemapCount++;
$RemapName[$RemapCount] = "Strafe Left";
$RemapCmd[$RemapCount] = "moveleft";
$RemapCount++;
$RemapName[$RemapCount] = "Strafe Right";
$RemapCmd[$RemapCount] = "moveright";
$RemapCount++;
$RemapName[$RemapCount] = "Turn Left";
$RemapCmd[$RemapCount] = "turnLeft";
$RemapCount++;
$RemapName[$RemapCount] = "Turn Right";
$RemapCmd[$RemapCount] = "turnRight";
$RemapCount++;
$RemapName[$RemapCount] = "Look Up";
$RemapCmd[$RemapCount] = "panUp";
$RemapCount++;
$RemapName[$RemapCount] = "Look Down";
$RemapCmd[$RemapCount] = "panDown";
$RemapCount++;
$RemapName[$RemapCount] = "Jump";
$RemapCmd[$RemapCount] = "jump";
$RemapCount++;
$RemapName[$RemapCount] = "Fire Weapon";
$RemapCmd[$RemapCount] = "mouseFire";
$RemapCount++;
$RemapName[$RemapCount] = "Adjust Zoom";
$RemapCmd[$RemapCount] = "setZoomFov";
$RemapCount++;
$RemapName[$RemapCount] = "Toggle Zoom";
$RemapCmd[$RemapCount] = "toggleZoom";
$RemapCount++;
$RemapName[$RemapCount] = "Free Look";
$RemapCmd[$RemapCount] = "toggleFreeLook";
$RemapCount++;
$RemapName[$RemapCount] = "Switch 1st/3rd";
$RemapCmd[$RemapCount] = "toggleFirstPerson";
$RemapCount++;
$RemapName[$RemapCount] = "Chat to Everyone";
$RemapCmd[$RemapCount] = "toggleMessageHud";
$RemapCount++;
$RemapName[$RemapCount] = "Message Hud PageUp";
$RemapCmd[$RemapCount] = "pageMessageHudUp";
$RemapCount++;
$RemapName[$RemapCount] = "Message Hud PageDown";
$RemapCmd[$RemapCount] = "pageMessageHudDown";
$RemapCount++;
$RemapName[$RemapCount] = "Resize Message Hud";
$RemapCmd[$RemapCount] = "resizeMessageHud";
$RemapCount++;
$RemapName[$RemapCount] = "Show Scores";
$RemapCmd[$RemapCount] = "showPlayerList";
$RemapCount++;
$RemapName[$RemapCount] = "Animation - Wave";
$RemapCmd[$RemapCount] = "celebrationWave";
$RemapCount++;
$RemapName[$RemapCount] = "Animation - Salute";
$RemapCmd[$RemapCount] = "celebrationSalute";
$RemapCount++;
$RemapName[$RemapCount] = "Suicide";
$RemapCmd[$RemapCount] = "suicide";
$RemapCount++;
$RemapName[$RemapCount] = "Toggle Camera";
$RemapCmd[$RemapCount] = "toggleCamera";
$RemapCount++;
$RemapName[$RemapCount] = "Drop Camera at Player";
$RemapCmd[$RemapCount] = "dropCameraAtPlayer";
$RemapCount++;
$RemapName[$RemapCount] = "Drop Player at Camera";
$RemapCmd[$RemapCount] = "dropPlayerAtCamera";
$RemapCount++;
$RemapName[$RemapCount] = "Bring up Options Dialog";
$RemapCmd[$RemapCount] = "bringUpOptions";
$RemapCount++;
function restoreDefaultMappings()
{
moveMap.delete();
exec( "marble/client/default.bind.cs" );
optionsDlg.fillRemapList();
}
function getMapDisplayName( %device, %action )
{
if ( %device $= "keyboard" )
return( %action );
else if ( strstr( %device, "mouse" ) != -1 )
{
// Substitute "mouse" for "button" in the action string:
%pos = strstr( %action, "button" );
if ( %pos != -1 )
{
%mods = getSubStr( %action, 0, %pos );
%object = getSubStr( %action, %pos, 1000 );
%instance = getSubStr( %object, strlen( "button" ), 1000 );
return( %mods @ "mouse" @ ( %instance + 1 ) );
}
else
error( "Mouse input object other than button passed to getDisplayMapName!" );
}
else if ( strstr( %device, "joystick" ) != -1 )
{
// Substitute "joystick" for "button" in the action string:
%pos = strstr( %action, "button" );
if ( %pos != -1 )
{
%mods = getSubStr( %action, 0, %pos );
%object = getSubStr( %action, %pos, 1000 );
%instance = getSubStr( %object, strlen( "button" ), 1000 );
return( %mods @ "joystick" @ ( %instance + 1 ) );
}
else
{
%pos = strstr( %action, "pov" );
if ( %pos != -1 )
{
%wordCount = getWordCount( %action );
%mods = %wordCount > 1 ? getWords( %action, 0, %wordCount - 2 ) @ " " : "";
%object = getWord( %action, %wordCount - 1 );
switch$ ( %object )
{
case "upov": %object = "POV1 up";
case "dpov": %object = "POV1 down";
case "lpov": %object = "POV1 left";
case "rpov": %object = "POV1 right";
case "upov2": %object = "POV2 up";
case "dpov2": %object = "POV2 down";
case "lpov2": %object = "POV2 left";
case "rpov2": %object = "POV2 right";
default: %object = "??";
}
return( %mods @ %object );
}
else
error( "Unsupported Joystick input object passed to getDisplayMapName!" );
}
}
return( "??" );
}
function buildFullMapString( %index )
{
%name = $RemapName[%index];
%cmd = $RemapCmd[%index];
%temp = moveMap.getBinding( %cmd );
if ( %temp $= "" )
return %name TAB "";
%mapString = "";
%count = getFieldCount( %temp );
for ( %i = 0; %i < %count; %i += 2 )
{
if ( %mapString !$= "" )
%mapString = %mapString @ ", ";
%device = getField( %temp, %i + 0 );
%object = getField( %temp, %i + 1 );
%mapString = %mapString @ getMapDisplayName( %device, %object );
}
return %name TAB %mapString;
}
function OptionsDlg::fillRemapList( %this )
{
%remapList = %this-->OptRemapList;
%remapList.clear();
for ( %i = 0; %i < $RemapCount; %i++ )
%remapList.addRow( %i, buildFullMapString( %i ) );
}
function OptionsDlg::doRemap( %this )
{
%remapList = %this-->OptRemapList;
%selId = %remapList.getSelectedId();
%name = $RemapName[%selId];
RemapDlg-->OptRemapText.setValue( "Re-bind \"" @ %name @ "\" to..." );
OptRemapInputCtrl.index = %selId;
Canvas.pushDialog( RemapDlg );
}
function redoMapping( %device, %action, %cmd, %oldIndex, %newIndex )
{
//%actionMap.bind( %device, %action, $RemapCmd[%newIndex] );
moveMap.bind( %device, %action, %cmd );
%remapList = %this-->OptRemapList;
%remapList.setRowById( %oldIndex, buildFullMapString( %oldIndex ) );
%remapList.setRowById( %newIndex, buildFullMapString( %newIndex ) );
}
function findRemapCmdIndex( %command )
{
for ( %i = 0; %i < $RemapCount; %i++ )
{
if ( %command $= $RemapCmd[%i] )
return( %i );
}
return( -1 );
}
/// This unbinds actions beyond %count associated to the
/// particular moveMap %commmand.
function unbindExtraActions( %command, %count )
{
%temp = moveMap.getBinding( %command );
if ( %temp $= "" )
return;
%count = getFieldCount( %temp ) - ( %count * 2 );
for ( %i = 0; %i < %count; %i += 2 )
{
%device = getField( %temp, %i + 0 );
%action = getField( %temp, %i + 1 );
moveMap.unbind( %device, %action );
}
}
function OptRemapInputCtrl::onInputEvent( %this, %device, %action )
{
//error( "** onInputEvent called - device = " @ %device @ ", action = " @ %action @ " **" );
Canvas.popDialog( RemapDlg );
// Test for the reserved keystrokes:
if ( %device $= "keyboard" )
{
// Cancel...
if ( %action $= "escape" )
{
// Do nothing...
return;
}
}
%cmd = $RemapCmd[%this.index];
%name = $RemapName[%this.index];
// Grab the friendly display name for this action
// which we'll use when prompting the user below.
%mapName = getMapDisplayName( %device, %action );
// Get the current command this action is mapped to.
%prevMap = moveMap.getCommand( %device, %action );
// If nothing was mapped to the previous command
// mapping then it's easy... just bind it.
if ( %prevMap $= "" )
{
unbindExtraActions( %cmd, 1 );
moveMap.bind( %device, %action, %cmd );
optionsDlg-->OptRemapList.setRowById( %this.index, buildFullMapString( %this.index ) );
return;
}
// If the previous command is the same as the
// current then they hit the same input as what
// was already assigned.
if ( %prevMap $= %cmd )
{
unbindExtraActions( %cmd, 0 );
moveMap.bind( %device, %action, %cmd );
optionsDlg-->OptRemapList.setRowById( %this.index, buildFullMapString( %this.index ) );
return;
}
// Look for the index of the previous mapping.
%prevMapIndex = findRemapCmdIndex( %prevMap );
// If we get a negative index then the previous
// mapping was to an item that isn't included in
// the mapping list... so we cannot unmap it.
if ( %prevMapIndex == -1 )
{
MessageBoxOK( "Remap Failed", "\"" @ %mapName @ "\" is already bound to a non-remappable command!" );
return;
}
// Setup the forced remapping callback command.
%callback = "redoMapping(" @ %device @ ", \"" @ %action @ "\", \"" @
%cmd @ "\", " @ %prevMapIndex @ ", " @ %this.index @ ");";
// Warn that we're about to remove the old mapping and
// replace it with another.
%prevCmdName = $RemapName[%prevMapIndex];
MessageBoxYesNo( "Warning",
"\"" @ %mapName @ "\" is already bound to \""
@ %prevCmdName @ "\"!\nDo you wish to replace this mapping?",
%callback, "" );
}
$AudioTestHandle = 0;
// Description to use for playing the volume test sound. This isn't
// played with the description of the channel that has its volume changed
// because we know nothing about the playback state of the channel. If it
// is paused or stopped, the test sound would not play then.
$AudioTestDescription = new SFXDescription()
{
sourceGroup = AudioChannelMaster;
};
function OptAudioUpdateMasterVolume( %volume )
{
if( %volume == $pref::SFX::masterVolume )
return;
sfxSetMasterVolume( %volume );
$pref::SFX::masterVolume = %volume;
if( !isObject( $AudioTestHandle ) )
$AudioTestHandle = sfxPlayOnce( AudioChannel, "core/art/sound/volumeTest.wav" );
}
function OptAudioUpdateChannelVolume( %description, %volume )
{
%channel = sfxGroupToOldChannel( %description.sourceGroup );
if( %volume == $pref::SFX::channelVolume[ %channel ] )
return;
sfxSetChannelVolume( %channel, %volume );
$pref::SFX::channelVolume[ %channel ] = %volume;
if( !isObject( $AudioTestHandle ) )
{
$AudioTestDescription.volume = %volume;
$AudioTestHandle = sfxPlayOnce( $AudioTestDescription, "core/art/sound/volumeTest.wav" );
}
}
function OptAudioProviderList::onSelect( %this, %id, %text )
{
// Skip empty provider selections.
if ( %text $= "" )
return;
$pref::SFX::provider = %text;
OptAudioDeviceList.clear();
%buffer = sfxGetAvailableDevices();
%count = getRecordCount( %buffer );
for(%i = 0; %i < %count; %i++)
{
%record = getRecord(%buffer, %i);
%provider = getField(%record, 0);
%device = getField(%record, 1);
if (%provider !$= %text)
continue;
if ( OptAudioDeviceList.findText( %device ) == -1 )
OptAudioDeviceList.add( %device, %i );
}
// Find the previous selected device.
%selId = OptAudioDeviceList.findText($pref::SFX::device);
if ( %selId == -1 )
OptAudioDeviceList.setFirstSelected();
else
OptAudioDeviceList.setSelected( %selId );
}
function OptAudioDeviceList::onSelect( %this, %id, %text )
{
// Skip empty selections.
if ( %text $= "" )
return;
$pref::SFX::device = %text;
if ( !sfxCreateDevice( $pref::SFX::provider,
$pref::SFX::device,
$pref::SFX::useHardware,
-1 ) )
error( "Unable to create SFX device: " @ $pref::SFX::provider
SPC $pref::SFX::device
SPC $pref::SFX::useHardware );
}
function OptMouseSetSensitivity(%value)
{
$pref::Input::LinkMouseSensitivity = %value;
}
/*
function OptAudioHardwareToggle::onClick(%this)
{
if (!sfxCreateDevice($pref::SFX::provider, $pref::SFX::device, $pref::SFX::useHardware, -1))
error("Unable to create SFX device: " @ $pref::SFX::provider SPC $pref::SFX::device SPC $pref::SFX::useHardware);
}
*/
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Msagl.Core;
using Microsoft.Msagl.Core.DataStructures;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using Microsoft.Msagl.Core.GraphAlgorithms;
using Microsoft.Msagl.Core.Layout;
using Microsoft.Msagl.Core.ProjectionSolver;
using Microsoft.Msagl.Routing;
namespace Microsoft.Msagl.Layout.Layered {
internal class TwoLayerFlatEdgeRouter : AlgorithmBase {
readonly int[] bottomLayer;
InteractiveEdgeRouter interactiveEdgeRouter;
double[] labelCenters;
Dictionary<Label, ICurve> labelsToLabelObstacles = new Dictionary<Label, ICurve>();
IntPair[] pairArray;
readonly Routing routing;
readonly int[] topLayer;
private SugiyamaLayoutSettings settings;
internal TwoLayerFlatEdgeRouter(SugiyamaLayoutSettings settings, Routing routing, int[] bottomLayer, int[] topLayer)
{
this.settings = settings;
this.topLayer = topLayer;
this.bottomLayer = bottomLayer;
this.routing = routing;
InitLabelsInfo();
}
Database Database {
get { return routing.Database; }
}
int[] Layering {
get { return routing.LayerArrays.Y; }
}
BasicGraph<IntEdge> IntGraph {
get { return routing.IntGraph; }
}
LayerArrays LayerArrays {
get { return routing.LayerArrays; }
}
double PaddingForEdges {
get { return settings.LayerSeparation / 8; }
}
void InitLabelsInfo() {
pairArray = new Set<IntPair>(from v in bottomLayer
where v < IntGraph.NodeCount
from edge in IntGraph.OutEdges(v)
where edge.Source != edge.Target
where Layering[edge.Target] == Layering[edge.Source]
select new IntPair(edge.Source, edge.Target)).ToArray();
labelCenters = new double[pairArray.Length];
int i = 0;
foreach (IntPair p in pairArray) {
int leftNode, rightNode;
if (LayerArrays.X[p.First] < LayerArrays.X[p.Second]) {
leftNode = p.First;
rightNode = p.Second;
} else {
leftNode = p.Second;
rightNode = p.First;
}
labelCenters[i++] = (Database.Anchors[leftNode].Right + Database.Anchors[rightNode].Left)/2;
//labelCenters contains ideal position for nodes at the moment
}
InitLabelsToLabelObstacles();
}
void InitLabelsToLabelObstacles() {
labelsToLabelObstacles = new Dictionary<Label, ICurve>();
IEnumerable<Label> labels = from p in pairArray from label in PairLabels(p) select label;
foreach (Label label in labels)
labelsToLabelObstacles[label] = CreatObstaceOnLabel(label);
}
double GetMaxLabelWidth(IntPair intPair) {
IEnumerable<Label> multiEdgeLabels = PairLabels(intPair);
if (multiEdgeLabels.Any())
return multiEdgeLabels.Max(label => label.Width);
return 0;
}
IEnumerable<Label> PairLabels(IntPair intPair) {
return from edge in Database.GetMultiedge(intPair)
let label = edge.Edge.Label
where label != null
select label;
}
/// <summary>
/// Executes the algorithm.
/// </summary>
protected override void RunInternal() {
if (pairArray.Length > 0) {
PositionLabelsOfFlatEdges();
interactiveEdgeRouter = new InteractiveEdgeRouter(GetObstacles(), PaddingForEdges, PaddingForEdges/3, Math.PI/6);
interactiveEdgeRouter.CalculateWholeTangentVisibilityGraph();
foreach (IntEdge intEdge in IntEdges())
{
this.ProgressStep();
RouteEdge(intEdge);
}
}
}
IEnumerable<ICurve> GetObstacles() {
return (from v in topLayer.Concat(bottomLayer)
where v < routing.OriginalGraph.Nodes.Count
select routing.IntGraph.Nodes[v].BoundaryCurve).Concat(LabelCurves());
}
IEnumerable<ICurve> LabelCurves() {
return from edge in IntEdges()
let label = edge.Edge.Label
where label != null
select CreatObstaceOnLabel(label);
}
static ICurve CreatObstaceOnLabel(Label label) {
var c = new Curve();
double obstacleBottom = label.Center.Y - label.Height/4;
c.AddSegment(new LineSegment(new Point(label.BoundingBox.Left, obstacleBottom),
new Point(label.BoundingBox.Right, obstacleBottom)));
Curve.ContinueWithLineSegment(c, label.BoundingBox.RightTop);
Curve.ContinueWithLineSegment(c, label.BoundingBox.LeftTop);
Curve.CloseCurve(c);
return c;
}
IEnumerable<IntEdge> IntEdges() {
return from pair in pairArray from edge in Database.GetMultiedge(pair) select edge;
}
void RouteEdge(IntEdge edge) {
if (edge.HasLabel)
RouteEdgeWithLabel(edge, edge.Edge.Label);
else
RouteEdgeWithNoLabel(edge);
}
void RouteEdgeWithLabel(IntEdge intEdge, Label label) {
//we allow here for the edge to cross its own label
Node sourceNode = routing.IntGraph.Nodes[intEdge.Source];
Node targetNode = routing.IntGraph.Nodes[intEdge.Target];
var sourcePort = new FloatingPort(sourceNode.BoundaryCurve, sourceNode.Center);
var targetPort = new FloatingPort(targetNode.BoundaryCurve, targetNode.Center);
ICurve labelObstacle = labelsToLabelObstacles[label];
var labelPort = new FloatingPort(labelObstacle, label.Center);
SmoothedPolyline poly0;
interactiveEdgeRouter.RouteSplineFromPortToPortWhenTheWholeGraphIsReady(sourcePort, labelPort, true, out poly0);
SmoothedPolyline poly1;
interactiveEdgeRouter.RouteSplineFromPortToPortWhenTheWholeGraphIsReady(labelPort, targetPort, true, out poly1);
Site site = poly1.HeadSite.Next;
Site lastSite = poly0.LastSite;
lastSite.Next = site;
site.Previous = lastSite;
var eg = intEdge.Edge.EdgeGeometry;
eg.SetSmoothedPolylineAndCurve(poly0);
Arrowheads.TrimSplineAndCalculateArrowheads(eg, intEdge.Edge.Source.BoundaryCurve,
intEdge.Edge.Target.BoundaryCurve, eg.Curve, false,
settings.EdgeRoutingSettings.KeepOriginalSpline);
}
void RouteEdgeWithNoLabel(IntEdge intEdge) {
Node sourceNode = routing.IntGraph.Nodes[intEdge.Source];
Node targetNode = routing.IntGraph.Nodes[intEdge.Target];
var sourcePort = new FloatingPort(sourceNode.BoundaryCurve, sourceNode.Center);
var targetPort = new FloatingPort(targetNode.BoundaryCurve, targetNode.Center);
var eg = intEdge.Edge.EdgeGeometry;
SmoothedPolyline sp;
eg.Curve = interactiveEdgeRouter.RouteSplineFromPortToPortWhenTheWholeGraphIsReady(sourcePort, targetPort, true, out sp);
Arrowheads.TrimSplineAndCalculateArrowheads(eg, intEdge.Edge.Source.BoundaryCurve,
intEdge.Edge.Target.BoundaryCurve, eg.Curve, false,
settings.EdgeRoutingSettings.KeepOriginalSpline);
intEdge.Edge.EdgeGeometry = eg;
}
void PositionLabelsOfFlatEdges() {
if (labelCenters == null || labelCenters.Length == 0)
return;
SortLabelsByX();
CalculateLabelsX();
}
void CalculateLabelsX() {
int i;
ISolverShell solver = ConstrainedOrdering.CreateSolver();
for (i = 0; i < pairArray.Length; i++)
solver.AddVariableWithIdealPosition(i, labelCenters[i], GetLabelWeight(pairArray[i]));
//add non overlapping constraints between to neighbor labels
double prevLabelWidth = GetMaxLabelWidth(pairArray[0]);
for (i = 0; i < pairArray.Length - 1; i++)
solver.AddLeftRightSeparationConstraint(i, i + 1,
(prevLabelWidth +
(prevLabelWidth = GetMaxLabelWidth(pairArray[i + 1])))/2 +
settings.NodeSeparation);
for (i = 0; i < labelCenters.Length; i++) {
double x = labelCenters[i] = solver.GetVariableResolvedPosition(i);
foreach (Label label in PairLabels(pairArray[i]))
label.Center = new Point(x, label.Center.Y);
}
}
double GetLabelWeight(IntPair intPair) {
return Database.GetMultiedge(intPair).Count;
}
void SortLabelsByX() {
Array.Sort(labelCenters, pairArray);
}
}
}
| |
// -----------------------------------------------------------------------
// <copyright file="AddFilterRulePicker.Generated.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// <auto-generated>
// This code was generated by a tool. DO NOT EDIT
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// -----------------------------------------------------------------------
#region StyleCop Suppression - generated code
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
namespace Microsoft.Management.UI.Internal
{
[Localizability(LocalizationCategory.None)]
partial class AddFilterRulePicker
{
//
// CancelAddFilterRules routed command
//
/// <summary>
/// Closes the picker and unchecks all items in the panel.
/// </summary>
public static readonly RoutedCommand CancelAddFilterRulesCommand = new RoutedCommand("CancelAddFilterRules",typeof(AddFilterRulePicker));
static private void CancelAddFilterRulesCommand_CommandExecuted(object sender, ExecutedRoutedEventArgs e)
{
AddFilterRulePicker obj = (AddFilterRulePicker) sender;
obj.OnCancelAddFilterRulesExecuted( e );
}
/// <summary>
/// Called when CancelAddFilterRules executes.
/// </summary>
/// <remarks>
/// Closes the picker and unchecks all items in the panel.
/// </remarks>
protected virtual void OnCancelAddFilterRulesExecuted(ExecutedRoutedEventArgs e)
{
OnCancelAddFilterRulesExecutedImplementation(e);
}
partial void OnCancelAddFilterRulesExecutedImplementation(ExecutedRoutedEventArgs e);
//
// OkAddFilterRules routed command
//
/// <summary>
/// Closes the picker and calls AddFilterRulesCommand with the collection of checked items from the picker.
/// </summary>
public static readonly RoutedCommand OkAddFilterRulesCommand = new RoutedCommand("OkAddFilterRules",typeof(AddFilterRulePicker));
static private void OkAddFilterRulesCommand_CommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
AddFilterRulePicker obj = (AddFilterRulePicker) sender;
obj.OnOkAddFilterRulesCanExecute( e );
}
static private void OkAddFilterRulesCommand_CommandExecuted(object sender, ExecutedRoutedEventArgs e)
{
AddFilterRulePicker obj = (AddFilterRulePicker) sender;
obj.OnOkAddFilterRulesExecuted( e );
}
/// <summary>
/// Called to determine if OkAddFilterRules can execute.
/// </summary>
protected virtual void OnOkAddFilterRulesCanExecute(CanExecuteRoutedEventArgs e)
{
OnOkAddFilterRulesCanExecuteImplementation(e);
}
partial void OnOkAddFilterRulesCanExecuteImplementation(CanExecuteRoutedEventArgs e);
/// <summary>
/// Called when OkAddFilterRules executes.
/// </summary>
/// <remarks>
/// Closes the picker and calls AddFilterRulesCommand with the collection of checked items from the picker.
/// </remarks>
protected virtual void OnOkAddFilterRulesExecuted(ExecutedRoutedEventArgs e)
{
OnOkAddFilterRulesExecutedImplementation(e);
}
partial void OnOkAddFilterRulesExecutedImplementation(ExecutedRoutedEventArgs e);
//
// AddFilterRulesCommand dependency property
//
/// <summary>
/// Identifies the AddFilterRulesCommand dependency property.
/// </summary>
public static readonly DependencyProperty AddFilterRulesCommandProperty = DependencyProperty.Register( "AddFilterRulesCommand", typeof(ICommand), typeof(AddFilterRulePicker), new PropertyMetadata( null, AddFilterRulesCommandProperty_PropertyChanged) );
/// <summary>
/// Gets or sets the command used to communicate that the action has occurred.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets the command used to communicate that the action has occurred.")]
[Localizability(LocalizationCategory.None)]
public ICommand AddFilterRulesCommand
{
get
{
return (ICommand) GetValue(AddFilterRulesCommandProperty);
}
set
{
SetValue(AddFilterRulesCommandProperty,value);
}
}
static private void AddFilterRulesCommandProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
AddFilterRulePicker obj = (AddFilterRulePicker) o;
obj.OnAddFilterRulesCommandChanged( new PropertyChangedEventArgs<ICommand>((ICommand)e.OldValue, (ICommand)e.NewValue) );
}
/// <summary>
/// Occurs when AddFilterRulesCommand property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<ICommand>> AddFilterRulesCommandChanged;
/// <summary>
/// Called when AddFilterRulesCommand property changes.
/// </summary>
protected virtual void OnAddFilterRulesCommandChanged(PropertyChangedEventArgs<ICommand> e)
{
OnAddFilterRulesCommandChangedImplementation(e);
RaisePropertyChangedEvent(AddFilterRulesCommandChanged, e);
}
partial void OnAddFilterRulesCommandChangedImplementation(PropertyChangedEventArgs<ICommand> e);
//
// AddFilterRulesCommandTarget dependency property
//
/// <summary>
/// Identifies the AddFilterRulesCommandTarget dependency property.
/// </summary>
public static readonly DependencyProperty AddFilterRulesCommandTargetProperty = DependencyProperty.Register( "AddFilterRulesCommandTarget", typeof(IInputElement), typeof(AddFilterRulePicker), new PropertyMetadata( null, AddFilterRulesCommandTargetProperty_PropertyChanged) );
/// <summary>
/// Gets or sets a target of the Command.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets a target of the Command.")]
[Localizability(LocalizationCategory.None)]
public IInputElement AddFilterRulesCommandTarget
{
get
{
return (IInputElement) GetValue(AddFilterRulesCommandTargetProperty);
}
set
{
SetValue(AddFilterRulesCommandTargetProperty,value);
}
}
static private void AddFilterRulesCommandTargetProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
AddFilterRulePicker obj = (AddFilterRulePicker) o;
obj.OnAddFilterRulesCommandTargetChanged( new PropertyChangedEventArgs<IInputElement>((IInputElement)e.OldValue, (IInputElement)e.NewValue) );
}
/// <summary>
/// Occurs when AddFilterRulesCommandTarget property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<IInputElement>> AddFilterRulesCommandTargetChanged;
/// <summary>
/// Called when AddFilterRulesCommandTarget property changes.
/// </summary>
protected virtual void OnAddFilterRulesCommandTargetChanged(PropertyChangedEventArgs<IInputElement> e)
{
OnAddFilterRulesCommandTargetChangedImplementation(e);
RaisePropertyChangedEvent(AddFilterRulesCommandTargetChanged, e);
}
partial void OnAddFilterRulesCommandTargetChangedImplementation(PropertyChangedEventArgs<IInputElement> e);
//
// IsOpen dependency property
//
/// <summary>
/// Identifies the IsOpen dependency property.
/// </summary>
public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register( "IsOpen", typeof(bool), typeof(AddFilterRulePicker), new PropertyMetadata( BooleanBoxes.FalseBox, IsOpenProperty_PropertyChanged) );
/// <summary>
/// Gets or sets a value indicating whether the Popup is visible.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets a value indicating whether the Popup is visible.")]
[Localizability(LocalizationCategory.None)]
public bool IsOpen
{
get
{
return (bool) GetValue(IsOpenProperty);
}
set
{
SetValue(IsOpenProperty,BooleanBoxes.Box(value));
}
}
static private void IsOpenProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
AddFilterRulePicker obj = (AddFilterRulePicker) o;
obj.OnIsOpenChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) );
}
/// <summary>
/// Occurs when IsOpen property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<bool>> IsOpenChanged;
/// <summary>
/// Called when IsOpen property changes.
/// </summary>
protected virtual void OnIsOpenChanged(PropertyChangedEventArgs<bool> e)
{
OnIsOpenChangedImplementation(e);
RaisePropertyChangedEvent(IsOpenChanged, e);
}
partial void OnIsOpenChangedImplementation(PropertyChangedEventArgs<bool> e);
/// <summary>
/// Called when a property changes.
/// </summary>
private void RaisePropertyChangedEvent<T>(EventHandler<PropertyChangedEventArgs<T>> eh, PropertyChangedEventArgs<T> e)
{
if(eh != null)
{
eh(this,e);
}
}
//
// Static constructor
//
/// <summary>
/// Called when the type is initialized.
/// </summary>
static AddFilterRulePicker()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(AddFilterRulePicker), new FrameworkPropertyMetadata(typeof(AddFilterRulePicker)));
CommandManager.RegisterClassCommandBinding( typeof(AddFilterRulePicker), new CommandBinding( AddFilterRulePicker.CancelAddFilterRulesCommand, CancelAddFilterRulesCommand_CommandExecuted ));
CommandManager.RegisterClassCommandBinding( typeof(AddFilterRulePicker), new CommandBinding( AddFilterRulePicker.OkAddFilterRulesCommand, OkAddFilterRulesCommand_CommandExecuted, OkAddFilterRulesCommand_CommandCanExecute ));
StaticConstructorImplementation();
}
static partial void StaticConstructorImplementation();
}
}
#endregion
| |
// ***********************************************************************
// Copyright (c) 2012-2014 Charlie Poole
//
// 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.Reflection;
using System.Threading;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.Framework.Internal.Execution;
using System.Collections.Generic;
using System.IO;
#if !PORTABLE && !NETSTANDARD1_6
using System.Diagnostics;
using System.Security;
using System.Windows.Forms;
#endif
namespace NUnit.Framework.Api
{
/// <summary>
/// Implementation of ITestAssemblyRunner
/// </summary>
public class NUnitTestAssemblyRunner : ITestAssemblyRunner
{
private static Logger log = InternalTrace.GetLogger("DefaultTestAssemblyRunner");
private ITestAssemblyBuilder _builder;
private ManualResetEvent _runComplete = new ManualResetEvent(false);
#if !PORTABLE
// Saved Console.Out and Console.Error
private TextWriter _savedOut;
private TextWriter _savedErr;
#endif
#if PARALLEL
// Event Pump
private EventPump _pump;
#endif
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="NUnitTestAssemblyRunner"/> class.
/// </summary>
/// <param name="builder">The builder.</param>
public NUnitTestAssemblyRunner(ITestAssemblyBuilder builder)
{
_builder = builder;
}
#endregion
#region Properties
#if PARALLEL
/// <summary>
/// Gets the default level of parallel execution (worker threads)
/// </summary>
public static int DefaultLevelOfParallelism
{
get { return Math.Max(Environment.ProcessorCount, 2); }
}
#endif
/// <summary>
/// The tree of tests that was loaded by the builder
/// </summary>
public ITest LoadedTest { get; private set; }
/// <summary>
/// The test result, if a run has completed
/// </summary>
public ITestResult Result
{
get { return TopLevelWorkItem == null ? null : TopLevelWorkItem.Result; }
}
/// <summary>
/// Indicates whether a test is loaded
/// </summary>
public bool IsTestLoaded
{
get { return LoadedTest != null; }
}
/// <summary>
/// Indicates whether a test is running
/// </summary>
public bool IsTestRunning
{
get { return TopLevelWorkItem != null && TopLevelWorkItem.State == WorkItemState.Running; }
}
/// <summary>
/// Indicates whether a test run is complete
/// </summary>
public bool IsTestComplete
{
get { return TopLevelWorkItem != null && TopLevelWorkItem.State == WorkItemState.Complete; }
}
/// <summary>
/// Our settings, specified when loading the assembly
/// </summary>
private IDictionary<string, object> Settings { get; set; }
/// <summary>
/// The top level WorkItem created for the assembly as a whole
/// </summary>
private WorkItem TopLevelWorkItem { get; set; }
/// <summary>
/// The TestExecutionContext for the top level WorkItem
/// </summary>
private TestExecutionContext Context { get; set; }
#endregion
#region Public Methods
/// <summary>
/// Loads the tests found in an Assembly
/// </summary>
/// <param name="assemblyName">File name of the assembly to load</param>
/// <param name="settings">Dictionary of option settings for loading the assembly</param>
/// <returns>True if the load was successful</returns>
public ITest Load(string assemblyName, IDictionary<string, object> settings)
{
Settings = settings;
if (settings.ContainsKey(FrameworkPackageSettings.RandomSeed))
Randomizer.InitialSeed = (int)settings[FrameworkPackageSettings.RandomSeed];
return LoadedTest = _builder.Build(assemblyName, settings);
}
/// <summary>
/// Loads the tests found in an Assembly
/// </summary>
/// <param name="assembly">The assembly to load</param>
/// <param name="settings">Dictionary of option settings for loading the assembly</param>
/// <returns>True if the load was successful</returns>
public ITest Load(Assembly assembly, IDictionary<string, object> settings)
{
Settings = settings;
if (settings.ContainsKey(FrameworkPackageSettings.RandomSeed))
Randomizer.InitialSeed = (int)settings[FrameworkPackageSettings.RandomSeed];
return LoadedTest = _builder.Build(assembly, settings);
}
/// <summary>
/// Count Test Cases using a filter
/// </summary>
/// <param name="filter">The filter to apply</param>
/// <returns>The number of test cases found</returns>
public int CountTestCases(ITestFilter filter)
{
if (LoadedTest == null)
throw new InvalidOperationException("The CountTestCases method was called but no test has been loaded");
return CountTestCases(LoadedTest, filter);
}
/// <summary>
/// Explore the test cases using a filter
/// </summary>
/// <param name="filter">The filter to apply</param>
/// <returns>Test Assembly with test cases that matches the filter</returns>
public ITest ExploreTests(ITestFilter filter)
{
if(LoadedTest == null)
throw new InvalidOperationException("The ExploreTests method was called but no test has been loaded");
if(filter == TestFilter.Empty)
return LoadedTest;
return new TestAssembly(LoadedTest as TestAssembly, filter);
}
/// <summary>
/// Run selected tests and return a test result. The test is run synchronously,
/// and the listener interface is notified as it progresses.
/// </summary>
/// <param name="listener">Interface to receive EventListener notifications.</param>
/// <param name="filter">A test filter used to select tests to be run</param>
/// <returns></returns>
public ITestResult Run(ITestListener listener, ITestFilter filter)
{
RunAsync(listener, filter);
WaitForCompletion(Timeout.Infinite);
return Result;
}
/// <summary>
/// Run selected tests asynchronously, notifying the listener interface as it progresses.
/// </summary>
/// <param name="listener">Interface to receive EventListener notifications.</param>
/// <param name="filter">A test filter used to select tests to be run</param>
/// <remarks>
/// RunAsync is a template method, calling various abstract and
/// virtual methods to be overridden by derived classes.
/// </remarks>
public void RunAsync(ITestListener listener, ITestFilter filter)
{
log.Info("Running tests");
if (LoadedTest == null)
throw new InvalidOperationException("The Run method was called but no test has been loaded");
_runComplete.Reset();
CreateTestExecutionContext(listener);
TopLevelWorkItem = WorkItemBuilder.CreateWorkItem(LoadedTest, filter, true);
TopLevelWorkItem.InitializeContext(Context);
TopLevelWorkItem.Completed += OnRunCompleted;
StartRun(listener);
}
/// <summary>
/// Wait for the ongoing run to complete.
/// </summary>
/// <param name="timeout">Time to wait in milliseconds</param>
/// <returns>True if the run completed, otherwise false</returns>
public bool WaitForCompletion(int timeout)
{
return _runComplete.WaitOne(timeout);
}
/// <summary>
/// Signal any test run that is in process to stop. Return without error if no test is running.
/// </summary>
/// <param name="force">If true, kill any tests that are currently running</param>
public void StopRun(bool force)
{
if (IsTestRunning)
{
Context.ExecutionStatus = force
? TestExecutionStatus.AbortRequested
: TestExecutionStatus.StopRequested;
Context.Dispatcher.CancelRun(force);
}
}
#endregion
#region Helper Methods
/// <summary>
/// Initiate the test run.
/// </summary>
private void StartRun(ITestListener listener)
{
#if !PORTABLE
// Save Console.Out and Error for later restoration
_savedOut = Console.Out;
_savedErr = Console.Error;
Console.SetOut(new TextCapture(Console.Out));
Console.SetError(new EventListenerTextWriter("Error", Console.Error));
#endif
#if PARALLEL
// Queue and pump events, unless settings have SynchronousEvents == false
if (!Settings.ContainsKey(FrameworkPackageSettings.SynchronousEvents) || !(bool)Settings[FrameworkPackageSettings.SynchronousEvents])
{
QueuingEventListener queue = new QueuingEventListener();
Context.Listener = queue;
_pump = new EventPump(listener, queue.Events);
_pump.Start();
}
#endif
if (!System.Diagnostics.Debugger.IsAttached &&
Settings.ContainsKey(FrameworkPackageSettings.DebugTests) &&
(bool)Settings[FrameworkPackageSettings.DebugTests])
System.Diagnostics.Debugger.Launch();
#if !PORTABLE && !NETSTANDARD1_6
if (Settings.ContainsKey(FrameworkPackageSettings.PauseBeforeRun) &&
(bool)Settings[FrameworkPackageSettings.PauseBeforeRun])
PauseBeforeRun();
#endif
Context.Dispatcher.Start(TopLevelWorkItem);
}
/// <summary>
/// Create the initial TestExecutionContext used to run tests
/// </summary>
/// <param name="listener">The ITestListener specified in the RunAsync call</param>
private void CreateTestExecutionContext(ITestListener listener)
{
Context = new TestExecutionContext();
// Apply package settings to the context
if (Settings.ContainsKey(FrameworkPackageSettings.DefaultTimeout))
Context.TestCaseTimeout = (int)Settings[FrameworkPackageSettings.DefaultTimeout];
if (Settings.ContainsKey(FrameworkPackageSettings.StopOnError))
Context.StopOnError = (bool)Settings[FrameworkPackageSettings.StopOnError];
// Apply attributes to the context
// Set the listener - overriding runners may replace this
Context.Listener = listener;
#if PARALLEL
int levelOfParallelism = GetLevelOfParallelism();
if (levelOfParallelism > 0)
Context.Dispatcher = new ParallelWorkItemDispatcher(levelOfParallelism);
else
Context.Dispatcher = new SimpleWorkItemDispatcher();
#else
Context.Dispatcher = new SimpleWorkItemDispatcher();
#endif
}
/// <summary>
/// Handle the the Completed event for the top level work item
/// </summary>
private void OnRunCompleted(object sender, EventArgs e)
{
#if PARALLEL
if (_pump != null)
_pump.Dispose();
#endif
#if !PORTABLE
Console.SetOut(_savedOut);
Console.SetError(_savedErr);
#endif
_runComplete.Set();
}
private int CountTestCases(ITest test, ITestFilter filter)
{
if (!test.IsSuite)
return 1;
int count = 0;
foreach (ITest child in test.Tests)
if (filter.Pass(child))
count += CountTestCases(child, filter);
return count;
}
#if PARALLEL
private int GetLevelOfParallelism()
{
return Settings.ContainsKey(FrameworkPackageSettings.NumberOfTestWorkers)
? (int)Settings[FrameworkPackageSettings.NumberOfTestWorkers]
: (LoadedTest.Properties.ContainsKey(PropertyNames.LevelOfParallelism)
? (int)LoadedTest.Properties.Get(PropertyNames.LevelOfParallelism)
: NUnitTestAssemblyRunner.DefaultLevelOfParallelism);
}
#endif
#if !PORTABLE && !NETSTANDARD1_6
// This method invokes members on the 'System.Diagnostics.Process' class and must satisfy the link demand of
// the full-trust 'PermissionSetAttribute' on this class. Callers of this method have no influence on how the
// Process class is used, so we can safely satisfy the link demand with a 'SecuritySafeCriticalAttribute' rather
// than a 'SecurityCriticalAttribute' and allow use by security transparent callers.
[SecuritySafeCritical]
private static void PauseBeforeRun()
{
var process = Process.GetCurrentProcess();
string attachMessage = string.Format("Attach debugger to Process {0}.exe with Id {1} if desired.", process.ProcessName, process.Id);
MessageBox.Show(attachMessage, process.ProcessName, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endif
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Description;
using System.Xml.Serialization;
using NUnit.Framework;
using Should;
using Swank.Configuration;
using Swank.Description;
using Swank.Description.WebApi;
using Swank.Extensions;
using Swank.Specification;
using Swank.Web.Handlers.App;
using Tests.Common;
using Tests.Unit.Specification;
namespace Tests.Unit.Web.Handlers.App
{
[TestFixture]
public class BodyDescriptionServiceTests
{
public List<BodyDefinitionModel> BuildDescription(Type type,
Action<Swank.Configuration.Configuration> configure = null, bool requestGraph = false)
{
var configuration = new Swank.Configuration.Configuration();
configure?.Invoke(configuration);
return new BodyDescriptionService(configuration)
.Create(Builder.BuildTypeGraphService(configuration: configuration)
.BuildForMessage(requestGraph, type, new EndpointDescription { MethodName = "Get" },
new WebApiDescription(new ApiDescription())));
}
public List<BodyDefinitionModel> BuildDescription<T>(
Action<Swank.Configuration.Configuration> configure = null, bool requestGraph = false)
{
return BuildDescription(typeof(T), configure, requestGraph);
}
// Complex types
[Comments("Complex type comments")]
public class ComplexTypeWithNoMembers { }
[Test]
public void should_create_complex_type()
{
var description = BuildDescription<ComplexTypeWithNoMembers>();
description.ShouldBeIndexed().ShouldTotal(2);
description[0].ShouldBeComplexType("ComplexTypeWithNoMembers", 0,
x => x.First().Opening().Comments("Complex type comments")
.Namespace("Get").FullNamespace("Get").LogicalName("Response"));
description[1].ShouldBeComplexType("ComplexTypeWithNoMembers", 0,
x => x.Last().Closing());
}
public class ComplexTypeWithSimpleMembers
{
public string StringMember { get; set; }
public bool BooleanMember { get; set; }
public DateTime DateTimeMember { get; set; }
public TimeSpan DurationMember { get; set; }
public Guid UuidMember { get; set; }
public int NumericMember { get; set; }
}
[Test]
public void should_create_complex_type_with_simple_type_members()
{
var description = BuildDescription<ComplexTypeWithSimpleMembers>();
description.ShouldBeIndexed().ShouldTotal(8);
description[0].ShouldBeComplexType("ComplexTypeWithSimpleMembers", 0,
x => x.First().Opening().Namespace("Get").FullNamespace("Get")
.LogicalName("Response"));
description[1].ShouldBeSimpleTypeMember("StringMember",
"string", 1, "", x => x.IsString(), x => x.Required());
description[2].ShouldBeSimpleTypeMember("BooleanMember",
"boolean", 1, "false", x => x.IsBoolean(), x => x.Required());
description[3].ShouldBeSimpleTypeMember("DateTimeMember",
"dateTime", 1, DateTime.Now.ToString("g"), x => x.IsDateTime(), x => x.Required());
description[4].ShouldBeSimpleTypeMember("DurationMember",
"duration", 1, "0:00:00", x => x.IsDuration(), x => x.Required());
description[5].ShouldBeSimpleTypeMember("UuidMember",
"uuid", 1, "00000000-0000-0000-0000-000000000000", x => x.IsGuid(), x => x.Required());
description[6].ShouldBeSimpleTypeMember("NumericMember",
"int", 1, "0", x => x.IsNumeric(), x => x.IsLastMember().Required());
description[7].ShouldBeComplexType("ComplexTypeWithSimpleMembers", 0,
x => x.Last().Closing());
}
public enum Options
{
Option,
[Comments("This is an option.")]
OptionWithComments
}
public class ComplexTypeWithSimpleOptionMember
{
public Options OptionMember { get; set; }
}
[Test]
[TestCase(EnumFormat.AsString, "String", "Option", "OptionWithComments")]
[TestCase(EnumFormat.AsNumber, "Int", "0", "1")]
public void should_create_complex_type_with_simple_option_member(
EnumFormat format, string dataTypeName, string value1, string value2)
{
var description = BuildDescription<ComplexTypeWithSimpleOptionMember>(
x => x.EnumFormat = format);
description.ShouldBeIndexed().ShouldTotal(3);
description[0].ShouldBeComplexType("ComplexTypeWithSimpleOptionMember", 0,
x => x.First().Opening().Namespace("Get").FullNamespace("Get")
.LogicalName("Response"));
description[1].ShouldBeSimpleTypeMember("OptionMember",
dataTypeName.ToLower(), 1, value1,
x => x.IsNumeric(format == EnumFormat.AsNumber)
.IsString(format == EnumFormat.AsString)
.Namespace("ResponseOptionMember")
.FullNamespace("Get", "ResponseOptionMember")
.Options("Options")
.WithOption("Option", value1)
.WithOptionAndComments("OptionWithComments", value2, "This is an option."),
x => x.IsLastMember().Required());
description[2].ShouldBeComplexType("ComplexTypeWithSimpleOptionMember", 0,
x => x.Last().Closing());
}
public class ComplexTypeWithRequiredMembers
{
public string Reference { get; set; }
public int Value { get; set; }
}
[Test]
public void should_create_complex_type_with_required_members()
{
var description = BuildDescription<ComplexTypeWithRequiredMembers>(requestGraph: true);
description.ShouldBeIndexed().ShouldTotal(4);
description[0].ShouldBeComplexType("ComplexTypeWithRequiredMembers", 0,
x => x.First().Opening().Namespace("Get").FullNamespace("Get")
.LogicalName("Request"));
description[1].ShouldBeSimpleTypeMember("Reference",
"string", 1, "", x => x.IsString(),
x => x.Required());
description[2].ShouldBeSimpleTypeMember("Value",
"int", 1, "0", x => x.IsNumeric(),
x => x.Required().IsLastMember());
description[3].ShouldBeComplexType("ComplexTypeWithRequiredMembers", 0,
x => x.Last().Closing());
}
public class ComplexTypeWithNullableMember
{
public int NonNullableMember { get; set; }
public int? NullableMember { get; set; }
}
[Test]
public void should_create_complex_type_with_nullable_members()
{
var description = BuildDescription<ComplexTypeWithNullableMember>(requestGraph: true);
description.ShouldBeIndexed().ShouldTotal(4);
description[0].ShouldBeComplexType("ComplexTypeWithNullableMember", 0,
x => x.First().Opening().Namespace("Get").FullNamespace("Get")
.LogicalName("Request"));
description[1].ShouldBeSimpleTypeMember("NonNullableMember",
"int", 1, "0", x => x.IsNumeric(), x => x.Required());
description[2].ShouldBeSimpleTypeMember("NullableMember",
"int", 1, "0", x => x.IsNumeric().IsNullable(),
x => x.Optional().IsLastMember());
description[3].ShouldBeComplexType("ComplexTypeWithNullableMember", 0,
x => x.Last().Closing());
}
public class ComplexTypeWithDeprecatedMember
{
[Obsolete("Why u no use different one??")]
public string DeprecatedMember { get; set; }
}
[Test]
public void should_create_complex_type_with_deprecated_members()
{
var description = BuildDescription<ComplexTypeWithDeprecatedMember>();
description.ShouldBeIndexed().ShouldTotal(3);
description[0].ShouldBeComplexType("ComplexTypeWithDeprecatedMember", 0,
x => x.First().Opening().Namespace("Get").FullNamespace("Get")
.LogicalName("Response"));
description[1].ShouldBeSimpleTypeMember("DeprecatedMember",
"string", 1, "", x => x.IsString(), x => x.IsLastMember().Required()
.IsDeprecated("Why u no use different one??"));
description[2].ShouldBeComplexType("ComplexTypeWithDeprecatedMember", 0,
x => x.Last().Closing());
}
public class ComplexTypeWithMaxLengthMember
{
[MaxLength(50)]
public string MaxLengthMember { get; set; }
}
[Test]
public void should_create_complex_type_and_specify_max_length()
{
var description = BuildDescription<ComplexTypeWithMaxLengthMember>();
description.ShouldBeIndexed().ShouldTotal(3);
description[0].ShouldBeComplexType("ComplexTypeWithMaxLengthMember", 0,
x => x.First().Opening().Namespace("Get").FullNamespace("Get")
.LogicalName("Response"));
description[1].ShouldBeSimpleTypeMember("MaxLengthMember",
"string", 1, "", x => x.IsString(), x => x.IsLastMember().Required()
.HasMaxLength(50));
description[2].ShouldBeComplexType("ComplexTypeWithMaxLengthMember", 0,
x => x.Last().Closing());
}
public class ComplexTypeWithEncodedMember
{
[AsciiEncoding]
public string EncodedMember { get; set; }
}
[Test]
public void should_create_complex_type_and_specify_encoding()
{
var description = BuildDescription<ComplexTypeWithEncodedMember>();
description.ShouldBeIndexed().ShouldTotal(3);
description[0].ShouldBeComplexType("ComplexTypeWithEncodedMember", 0,
x => x.First().Opening().Namespace("Get").FullNamespace("Get")
.LogicalName("Response"));
description[1].ShouldBeSimpleTypeMember("EncodedMember",
"string", 1, "", x => x.IsString(), x => x.IsLastMember().Required()
.HasEncoding("ASCII"));
description[2].ShouldBeComplexType("ComplexTypeWithEncodedMember", 0,
x => x.Last().Closing());
}
public class ComplexTypeWithDefaultValueMember
{
[DefaultValue("zero")]
public string DefaultValueMember { get; set; }
}
[Test]
public void should_create_complex_type_with_default_value_members()
{
var description = BuildDescription<ComplexTypeWithDefaultValueMember>(
requestGraph: true);
description.ShouldBeIndexed().ShouldTotal(3);
description[0].ShouldBeComplexType("ComplexTypeWithDefaultValueMember", 0,
x => x.First().Opening().Namespace("Get").FullNamespace("Get")
.LogicalName("Request"));
description[1].ShouldBeSimpleTypeMember("DefaultValueMember",
"string", 1, "", x => x.IsString(),
x => x.Default("zero").Required().IsLastMember());
description[2].ShouldBeComplexType("ComplexTypeWithDefaultValueMember", 0,
x => x.Last().Closing());
}
public class ComplexTypeWithSampleValueMember
{
[SampleValue("zero")]
public string SampleValueMember { get; set; }
}
[Test]
public void should_create_complex_type_with_sample_value_members()
{
var description = BuildDescription<ComplexTypeWithSampleValueMember>();
description.ShouldBeIndexed().ShouldTotal(3);
description[0].ShouldBeComplexType("ComplexTypeWithSampleValueMember", 0,
x => x.First().Opening().Namespace("Get").FullNamespace("Get")
.LogicalName("Response"));
description[1].ShouldBeSimpleTypeMember("SampleValueMember", "string", 1,
"zero", x => x.IsString(), x => x.IsLastMember().Required());
description[2].ShouldBeComplexType("ComplexTypeWithSampleValueMember", 0,
x => x.Last().Closing());
}
public class ComplexTypeWithArrayMembers
{
public List<string> ArrayMember { get; set; }
}
public class ComplexTypeWithArrayMembersWithCustomItemName
{
[XmlArrayItem("Item")]
public List<string> ArrayMember { get; set; }
}
[Test]
[TestCase(typeof(ComplexTypeWithArrayMembers), "string")]
[TestCase(typeof(ComplexTypeWithArrayMembersWithCustomItemName), "Item")]
public void should_create_complex_type_with_array_members(
Type type, string itemName)
{
var description = BuildDescription(type);
description.ShouldBeIndexed().ShouldTotal(5);
description[0].ShouldBeComplexType(type.Name, 0, x =>
x.First().Opening().Namespace("Get").FullNamespace("Get")
.LogicalName("Response"));
description[1].ShouldBeArrayMember("ArrayMember", 1,
x => x.Opening().TypeName("string"),
x => x.IsLastMember().Required().SampleValue(""));
description[2].ShouldBeSimpleType(itemName,
"string", 2, "", x => x.IsString());
description[3].ShouldBeArrayMember("ArrayMember", "string", 1,
x => x.Closing(), x => x.IsLastMember());
description[4].ShouldBeComplexType(type.Name, 0,
x => x.Last().Closing());
}
public class ComplexTypeWithDictionaryMember
{
[DictionaryDescription("Entries", "This is a dictionary.",
"KeyName", "This is a dictionary key.",
"This is a dictionary value.")]
public Dictionary<string, string> DictionaryMember { get; set; }
}
[Test]
public void should_create_complex_type_with_dictionary_members()
{
var description = BuildDescription<ComplexTypeWithDictionaryMember>();
description.ShouldBeIndexed().ShouldTotal(5);
description[0].ShouldBeComplexType("ComplexTypeWithDictionaryMember", 0,
x => x.First().Opening().Namespace("Get").FullNamespace("Get")
.LogicalName("Response"));
description[1].ShouldBeDictionaryMember("Entries", 1,
x => x.Opening().TypeName("string"),
x => x.Comments("This is a dictionary.").IsLastMember()
.SampleValue("").Required());
description[2].ShouldBeSimpleTypeDictionaryEntry(
"KeyName", "string", "string", 2, "",
x => x.IsString().Comments("This is a dictionary value."),
x => x.KeyComments("This is a dictionary key."));
description[3].ShouldBeDictionaryMember("Entries", "string", 1, x => x.Closing(),
x => x.IsLastMember());
description[4].ShouldBeComplexType("ComplexTypeWithDictionaryMember", 0,
x => x.Last().Closing());
}
// Arrays
[ArrayDescription("Items", "This is an array",
"Item", "This is an array item.")]
public class ArrayType : List<string> { }
[Test]
public void should_create_an_array_with_a_description()
{
var description = BuildDescription<ArrayType>();
description.ShouldBeIndexed().ShouldTotal(3);
description[0].ShouldBeArray("Items", 0,
x => x.Comments("This is an array").First()
.Opening().TypeName("string"));
description[1].ShouldBeSimpleType("Item", "string", 1, "", x => x
.Comments("This is an array item.").IsString());
description[2].ShouldBeArray("Items", "string", 0,
x => x.Last().Closing());
}
public enum ArrayOptions { Option1, Option2 }
[Test]
[TestCase(EnumFormat.AsString, "String", "Option1", "Option2")]
[TestCase(EnumFormat.AsNumber, "Int", "0", "1")]
public void should_create_an_array_of_options(EnumFormat format,
string dataTypeName, string value1, string value2)
{
var description = BuildDescription<List<ArrayOptions>>(
x => x.EnumFormat = format);
description.ShouldBeIndexed().ShouldTotal(3);
description[0].ShouldBeArray($"ArrayOf{dataTypeName}", 0,
x => x.First().Opening().Namespace("Get")
.FullNamespace("Get").TypeName(dataTypeName.ToLower())
.Options("ArrayOptions")
.WithOption("Option1", value1)
.WithOption("Option2", value2));
description[1].ShouldBeSimpleType(dataTypeName.ToLower(),
dataTypeName.ToLower(), 1, value1,
x => x.IsNumeric(format == EnumFormat.AsNumber)
.IsString(format == EnumFormat.AsString)
.Namespace("Get").FullNamespace("Get")
.Options("ArrayOptions")
.WithOption("Option1", value1)
.WithOption("Option2", value2));
description[2].ShouldBeArray($"ArrayOf{dataTypeName}", dataTypeName.ToLower(), 0,
x => x.Last().Closing());
}
public class ArrayComplexType { public string Member { get; set; } }
[Test]
public void should_create_an_array_of_complex_types()
{
var description = BuildDescription<List<ArrayComplexType>>();
description.ShouldBeIndexed().ShouldTotal(5);
description[0].ShouldBeArray("ArrayOfArrayComplexType", "ArrayComplexType", 0,
x => x.First().Opening().LogicalName("Response")
.Namespace("Get").FullNamespace("Get"));
description[1].ShouldBeComplexType("ArrayComplexType",
"ArrayComplexType", 1, x => x.Opening().Namespace("Get").FullNamespace("Get")
.LogicalName("Response"));
description[2].ShouldBeSimpleTypeMember("Member", "string", 2, "",
x => x.IsString(), x => x.IsLastMember().Required());
description[3].ShouldBeComplexType("ArrayComplexType", "ArrayComplexType", 1,
x => x.Closing());
description[4].ShouldBeArray("ArrayOfArrayComplexType", "ArrayComplexType", 0,
x => x.Last().Closing());
}
[Test]
public void should_create_an_array_of_arrays()
{
var description = BuildDescription<List<List<string>>>();
description.ShouldBeIndexed().ShouldTotal(5);
description[0].ShouldBeArray("ArrayOfArrayOfString", "ArrayOfString", 0,
x => x.First().Opening());
description[1].ShouldBeArray("ArrayOfString", "String", 1,
x => x.Opening().TypeName("string"));
description[2].ShouldBeSimpleType("string",
"string", 2, "", x => x.IsString());
description[3].ShouldBeArray("ArrayOfString", "string", 1, x => x.Closing());
description[4].ShouldBeArray("ArrayOfArrayOfString", "ArrayOfString",
0, x => x.Last().Closing());
}
[Test]
public void should_create_an_array_of_dictionaries()
{
var description = BuildDescription<List<Dictionary<string, int>>>();
description.ShouldBeIndexed().ShouldTotal(5);
description[0].ShouldBeArray("ArrayOfDictionaryOfInt", "DictionaryOfInt", 0,
x => x.First().Opening());
description[1].ShouldBeDictionary("DictionaryOfInt", 1,
x => x.Opening().TypeName("int"));
description[2].ShouldBeSimpleTypeDictionaryEntry(
"key", "string", "int", 2, "0", x => x.IsNumeric());
description[3].ShouldBeDictionary("DictionaryOfInt",
"int", 1, x => x.Closing());
description[4].ShouldBeArray("ArrayOfDictionaryOfInt", "DictionaryOfInt",
0, x => x.Last().Closing());
}
// Dictionaries
[DictionaryDescription("Entries", "This is a dictionary.",
"KeyName", "This is a dictionary key.",
"This is a dictionary value.")]
public class DictionaryType : Dictionary<string, int> { }
[Test]
public void should_create_a_dictionary_with_a_description()
{
var description = BuildDescription<DictionaryType>();
description.ShouldBeIndexed().ShouldTotal(3);
description[0].ShouldBeDictionary("Entries", 0, x => x
.Comments("This is a dictionary.")
.First().Opening().TypeName("int"));
description[1].ShouldBeSimpleTypeDictionaryEntry(
"KeyName", "string", "int", 1, "0",
x => x.IsNumeric().Comments("This is a dictionary value."),
x => x.KeyComments("This is a dictionary key."));
description[2].ShouldBeDictionary("Entries",
"int", 0, x => x.Last().Closing());
}
public enum DictionaryKeyOptions { KeyOption1, KeyOption2 }
public enum DictionaryValueOptions { ValueOption1, ValueOption2 }
[Test]
[TestCase(EnumFormat.AsString, "String", "KeyOption1",
"KeyOption2", "ValueOption1", "ValueOption2")]
[TestCase(EnumFormat.AsNumber, "Int", "0", "1", "0", "1")]
public void should_create_an_dictionary_of_string_options(
EnumFormat format, string dataTypeName, string key1,
string key2, string value1, string value2)
{
var description = BuildDescription<Dictionary<DictionaryKeyOptions,
DictionaryValueOptions>>(x => x.EnumFormat = format);
description.ShouldBeIndexed().ShouldTotal(3);
description[0].ShouldBeDictionary($"DictionaryOf{dataTypeName}", 0,
x => x.First().Opening().Namespace("Get")
.FullNamespace("Get").TypeName(dataTypeName.ToLower())
.Options("DictionaryValueOptions")
.WithOption("ValueOption1", value1)
.WithOption("ValueOption2", value2));
description[1].ShouldBeSimpleTypeDictionaryEntry(
"key", dataTypeName.ToLower(),
dataTypeName.ToLower(), 1, value1,
x => x.IsNumeric(format == EnumFormat.AsNumber)
.IsString(format == EnumFormat.AsString)
.Namespace("Get").FullNamespace("Get")
.Options("DictionaryValueOptions")
.WithOption("ValueOption1", value1)
.WithOption("ValueOption2", value2),
x => x.KeyOptions("DictionaryKeyOptions")
.WithOption("KeyOption1", key1)
.WithOption("KeyOption2", key2));
description[2].ShouldBeDictionary($"DictionaryOf{dataTypeName}",
dataTypeName.ToLower(), 0, x => x.Last().Closing());
}
public class DictionaryComplexType { public string Member { get; set; } }
[Test]
public void should_create_a_dictionary_of_complex_types()
{
var description = BuildDescription<Dictionary<string, DictionaryComplexType>>();
description.ShouldBeIndexed().ShouldTotal(5);
description[0].ShouldBeDictionary("DictionaryOfDictionaryComplexType",
"DictionaryComplexType", 0, x => x.First().Opening().LogicalName("Response")
.Namespace("Get").FullNamespace("Get"));
description[1].ShouldBeOpeningComplexTypeDictionaryEntry(
"key", "string", "DictionaryComplexType", 1, x => x.Namespace("Get")
.FullNamespace("Get").LogicalName("Response"));
description[2].ShouldBeSimpleTypeMember("Member", "string", 2, "",
x => x.IsString(), x => x.IsLastMember().Required());
description[3].ShouldBeClosingComplexTypeDictionaryEntry("key", "DictionaryComplexType", 1);
description[4].ShouldBeDictionary("DictionaryOfDictionaryComplexType",
"DictionaryComplexType", 0, x => x.Last().Closing());
}
[Test]
public void should_create_a_dictionary_of_arrays()
{
var description = BuildDescription<Dictionary<string, List<int>>>();
description.ShouldBeIndexed().ShouldTotal(5);
description[0].ShouldBeDictionary("DictionaryOfArrayOfInt", "ArrayOfInt", 0,
x => x.First().Opening());
description[1].ShouldBeOpeningArrayDictionaryEntry(
"key", "string", "ArrayOfInt", 1, x => x.TypeName("int"));
description[2].ShouldBeSimpleType("int", "int", 2, "0", x => x.IsNumeric());
description[3].ShouldBeClosingArrayDictionaryEntry("key", "int", 1);
description[4].ShouldBeDictionary("DictionaryOfArrayOfInt", "ArrayOfInt",
0, x => x.Last().Closing());
}
[Test]
public void should_create_a_dictionary_of_dictionaries()
{
var description = BuildDescription<Dictionary<string, Dictionary<string, int>>>();
description.ShouldBeIndexed().ShouldTotal(5);
description[0].ShouldBeDictionary("DictionaryOfDictionaryOfInt", "DictionaryOfInt", 0,
x => x.First().Opening());
description[1].ShouldBeOpeningDictionaryDictionaryEntry(
"key", "string", "DictionaryOfInt", 1, x => x.TypeName("int"));
description[2].ShouldBeSimpleTypeDictionaryEntry(
"key", "string", "int", 2, "0", x => x.IsNumeric());
description[3].ShouldBeClosingDictionaryDictionaryEntry("key", "int", 1);
description[4].ShouldBeDictionary("DictionaryOfDictionaryOfInt", "DictionaryOfInt",
0, x => x.Last().Closing());
}
}
public static class LineItemDescriptionAssertions
{
// Simple type assertions
public static void ShouldBeSimpleType(this BodyDefinitionModel source,
string name, string typeName, int level, string sampleValue,
Action<SimpleTypeDsl> simpleTypeProperties)
{
source.ShouldMatchLineItem(CreateSimpleType(name, typeName,
level, sampleValue, simpleTypeProperties));
}
public static void ShouldBeSimpleTypeMember(this BodyDefinitionModel source,
string name, string typeName, int level, string sampleValue,
Action<SimpleTypeDsl> simpleTypeProperties,
Action<MemberDsl> memberProperties = null)
{
var compare = CreateSimpleType(name, typeName,
level, sampleValue, simpleTypeProperties);
compare.IsMember = true;
memberProperties?.Invoke(new MemberDsl(compare));
source.ShouldMatchLineItem(compare);
}
public static void ShouldBeSimpleTypeDictionaryEntry(this BodyDefinitionModel source,
string name, string keyTypeName, string valueTypeName, int level,
string sampleValue, Action<SimpleTypeDsl> simpleTypeProperties,
Action<DictionaryKeyDsl> dictionaryEntryProperties = null)
{
var compare = CreateSimpleType(name, valueTypeName,
level, sampleValue, simpleTypeProperties);
compare.IsDictionaryEntry = true;
compare.DictionaryKey = new KeyModel { TypeName = keyTypeName };
dictionaryEntryProperties?.Invoke(new DictionaryKeyDsl(compare));
source.ShouldMatchLineItem(compare);
}
private static BodyDefinitionModel CreateSimpleType(
string name, string typeName, int level, string sampleValue,
Action<SimpleTypeDsl> simpleTypeProperties)
{
var simpleType = new BodyDefinitionModel
{
Name = name,
TypeName = typeName,
IsSimpleType = true,
SampleValue = sampleValue,
Whitespace = BodyDescriptionService.Whitespace.Repeat(level)
};
simpleTypeProperties(new SimpleTypeDsl(simpleType));
return simpleType;
}
public class SimpleTypeDsl
{
private readonly BodyDefinitionModel _body;
public SimpleTypeDsl(BodyDefinitionModel body) { _body = body; }
public SimpleTypeDsl Comments(string comments)
{
_body.Comments = comments; return this;
}
public SimpleTypeDsl IsNullable() { _body.Nullable = true; return this; }
public SimpleTypeDsl IsString() { _body.IsString = true; return this; }
public SimpleTypeDsl IsString(bool isString)
{
if (isString) _body.IsString = true; return this;
}
public SimpleTypeDsl IsBoolean() { _body.IsBoolean = true; return this; }
public SimpleTypeDsl IsNumeric() { _body.IsNumeric = true; return this; }
public SimpleTypeDsl IsNumeric(bool isNumeric)
{
if (isNumeric) _body.IsNumeric = true; return this;
}
public SimpleTypeDsl IsDateTime() { _body.IsDateTime = true; return this; }
public SimpleTypeDsl IsDuration() { _body.IsDuration = true; return this; }
public SimpleTypeDsl IsGuid() { _body.IsGuid = true; return this; }
public OptionDsl Options(string name)
{
_body.Enumeration = _body.Enumeration ?? new Enumeration();
_body.Enumeration.Name = name;
return new OptionDsl(_body.Enumeration);
}
public SimpleTypeDsl LogicalName(string logicalName)
{
_body.LogicalName = logicalName; return this;
}
public SimpleTypeDsl Namespace(string @namespace)
{
_body.Namespace = @namespace; return this;
}
public SimpleTypeDsl FullNamespace(params string[] @namespace)
{
_body.FullNamespace = @namespace.ToList(); return this;
}
}
// Array assertions
public static void ShouldBeArray(
this BodyDefinitionModel source, string name, int level,
Action<ArrayDsl> properties)
{
source.ShouldBeArray(name, null, level, properties);
}
public static void ShouldBeArray(
this BodyDefinitionModel source, string name, string typeName, int level,
Action<ArrayDsl> properties)
{
source.ShouldMatchLineItem(CreateArray(name, typeName, level, properties));
}
public static void ShouldBeArrayMember(
this BodyDefinitionModel source, string name, int level,
Action<ArrayDsl> arrayProperties,
Action<MemberDsl> memberProperties = null)
{
source.ShouldBeArrayMember(name, null, level, arrayProperties, memberProperties);
}
public static void ShouldBeArrayMember(
this BodyDefinitionModel source, string name, string typeName, int level,
Action<ArrayDsl> arrayProperties,
Action<MemberDsl> memberProperties = null)
{
var compare = CreateArray(name, typeName, level, arrayProperties);
compare.IsMember = true;
memberProperties?.Invoke(new MemberDsl(compare));
source.ShouldMatchLineItem(compare);
}
public static void ShouldBeOpeningArrayDictionaryEntry(
this BodyDefinitionModel source, string name, string keyTypeName, string typeName, int level,
Action<ArrayDsl> arrayProperties = null,
Action<DictionaryKeyDsl> dictionaryKeyProperties = null)
{
var compare = CreateArray(name, typeName, level, arrayProperties);
compare.IsOpening = true;
compare.IsDictionaryEntry = true;
compare.DictionaryKey = new KeyModel { TypeName = keyTypeName };
dictionaryKeyProperties?.Invoke(new DictionaryKeyDsl(compare));
source.ShouldMatchLineItem(compare);
}
public static void ShouldBeClosingArrayDictionaryEntry(
this BodyDefinitionModel source, string name, int level,
Action<ArrayDsl> arrayProperties = null)
{
source.ShouldBeClosingArrayDictionaryEntry(name, null, level, arrayProperties);
}
public static void ShouldBeClosingArrayDictionaryEntry(
this BodyDefinitionModel source, string name, string typeName, int level,
Action<ArrayDsl> arrayProperties = null)
{
var compare = CreateArray(name, typeName, level, arrayProperties);
compare.IsClosing = true;
compare.IsDictionaryEntry = true;
source.ShouldMatchLineItem(compare);
}
private static BodyDefinitionModel CreateArray(
string name, string typeName, int level, Action<ArrayDsl> properties)
{
var arrayType = new BodyDefinitionModel
{
Name = name,
TypeName = typeName,
IsArray = true,
Whitespace = BodyDescriptionService.Whitespace.Repeat(level)
};
properties?.Invoke(new ArrayDsl(arrayType));
return arrayType;
}
public class ArrayDsl
{
private readonly BodyDefinitionModel _body;
public ArrayDsl(BodyDefinitionModel body) { _body = body; }
public ArrayDsl Comments(string comments)
{
_body.Comments = comments; return this;
}
public ArrayDsl Opening() { _body.IsOpening = true; return this; }
public ArrayDsl Closing() { _body.IsClosing = true; return this; }
public ArrayDsl First() { _body.IsFirst = true; return this; }
public ArrayDsl Last() { _body.IsLast = true; return this; }
public OptionDsl Options(string name)
{
_body.Enumeration = _body.Enumeration ?? new Enumeration();
_body.Enumeration.Name = name;
return new OptionDsl(_body.Enumeration);
}
public ArrayDsl TypeName(string typeName)
{
_body.TypeName = typeName; return this;
}
public ArrayDsl LogicalName(string logicalName)
{
_body.LogicalName = logicalName; return this;
}
public ArrayDsl Namespace(string @namespace)
{
_body.Namespace = @namespace; return this;
}
public ArrayDsl FullNamespace(params string[] @namespace)
{
_body.FullNamespace = @namespace.ToList(); return this;
}
}
// Dictionary assertions
public static void ShouldBeDictionary(
this BodyDefinitionModel source, string name, int level,
Action<DictionaryDsl> properties)
{
source.ShouldBeDictionary(name, null, level, properties);
}
public static void ShouldBeDictionary(
this BodyDefinitionModel source, string name, string typeName, int level,
Action<DictionaryDsl> properties)
{
source.ShouldMatchLineItem(CreateDictionary(name, typeName, level, properties));
}
public static void ShouldBeDictionaryMember(
this BodyDefinitionModel source, string name, int level,
Action<DictionaryDsl> dictionaryProperties,
Action<MemberDsl> memberProperties = null)
{
source.ShouldBeDictionaryMember(name, null, level, dictionaryProperties, memberProperties);
}
public static void ShouldBeDictionaryMember(
this BodyDefinitionModel source, string name, string typeName, int level,
Action<DictionaryDsl> dictionaryProperties,
Action<MemberDsl> memberProperties = null)
{
var compare = CreateDictionary(name, typeName, level, dictionaryProperties);
compare.IsMember = true;
memberProperties?.Invoke(new MemberDsl(compare));
source.ShouldMatchLineItem(compare);
}
public static void ShouldBeDictionaryDictionaryEntry(
this BodyDefinitionModel source, string name, string keyTypeName, string typeName, int level,
Action<DictionaryDsl> dictionaryProperties,
Action<DictionaryKeyDsl> dictionaryKeyProperties = null)
{
var compare = CreateDictionary(name, typeName, level, dictionaryProperties);
compare.IsDictionaryEntry = true;
compare.DictionaryKey = new KeyModel { TypeName = keyTypeName };
dictionaryKeyProperties?.Invoke(new DictionaryKeyDsl(compare));
source.ShouldMatchLineItem(compare);
}
public static void ShouldBeOpeningDictionaryDictionaryEntry(
this BodyDefinitionModel source, string name, string keyTypeName, string typeName, int level,
Action<DictionaryDsl> dictionaryProperties = null,
Action<DictionaryKeyDsl> dictionaryKeyProperties = null)
{
var compare = CreateDictionary(name, typeName, level, dictionaryProperties);
compare.IsOpening = true;
compare.IsDictionaryEntry = true;
compare.DictionaryKey = new KeyModel { TypeName = keyTypeName };
dictionaryKeyProperties?.Invoke(new DictionaryKeyDsl(compare));
source.ShouldMatchLineItem(compare);
}
public static void ShouldBeClosingDictionaryDictionaryEntry(
this BodyDefinitionModel source, string name, string typeName, int level,
Action<DictionaryDsl> dictionaryKeyProperties = null)
{
var compare = CreateDictionary(name, typeName, level, dictionaryKeyProperties);
compare.IsClosing = true;
compare.IsDictionaryEntry = true;
source.ShouldMatchLineItem(compare);
}
private static BodyDefinitionModel CreateDictionary(
string name, string typeName, int level,
Action<DictionaryDsl> properties)
{
var dictionaryType = new BodyDefinitionModel
{
Name = name,
TypeName = typeName,
IsDictionary = true,
Whitespace = BodyDescriptionService.Whitespace.Repeat(level)
};
properties?.Invoke(new DictionaryDsl(dictionaryType));
return dictionaryType;
}
public class DictionaryDsl
{
private readonly BodyDefinitionModel _body;
public DictionaryDsl(BodyDefinitionModel body) { _body = body; }
public DictionaryDsl Comments(string comments)
{
_body.Comments = comments; return this;
}
public DictionaryDsl Opening() { _body.IsOpening = true; return this; }
public DictionaryDsl Closing() { _body.IsClosing = true; return this; }
public DictionaryDsl First() { _body.IsFirst = true; return this; }
public DictionaryDsl Last() { _body.IsLast = true; return this; }
public OptionDsl Options(string name)
{
_body.Enumeration = _body.Enumeration ?? new Enumeration();
_body.Enumeration.Name = name;
return new OptionDsl(_body.Enumeration);
}
public DictionaryDsl TypeName(string typeName)
{
_body.TypeName = typeName; return this;
}
public DictionaryDsl LogicalName(string logicalName)
{
_body.LogicalName = logicalName; return this;
}
public DictionaryDsl Namespace(string @namespace)
{
_body.Namespace = @namespace; return this;
}
public DictionaryDsl FullNamespace(params string[] @namespace)
{
_body.FullNamespace = @namespace.ToList(); return this;
}
}
// Complex type assertions
public static void ShouldBeComplexType(this BodyDefinitionModel source,
string name, int level, Action<ComplexTypeDsl> properties)
{
source.ShouldBeComplexType(name, name, level, properties);
}
public static void ShouldBeComplexType(this BodyDefinitionModel source,
string name, string typeName, int level, Action<ComplexTypeDsl> properties)
{
source.ShouldMatchLineItem(CreateComplexType(name, typeName, level, properties));
}
public static void ShouldBeComplexTypeMember(this BodyDefinitionModel source,
string name, string typeName, int level,
Action<ComplexTypeDsl> complexTypeProperties = null,
Action<MemberDsl> memberProperties = null)
{
var compare = CreateComplexType(name, typeName, level, complexTypeProperties);
compare.IsMember = true;
memberProperties?.Invoke(new MemberDsl(compare));
source.ShouldMatchLineItem(compare);
}
public static void ShouldBeOpeningComplexTypeDictionaryEntry(this BodyDefinitionModel source,
string name, string keyTypeName, string valueTypeName, int level,
Action<ComplexTypeDsl> complexTypeProperties = null,
Action<DictionaryKeyDsl> dictionaryKeyProperties = null)
{
var compare = CreateComplexType(name, valueTypeName, level, complexTypeProperties);
compare.IsOpening = true;
compare.IsDictionaryEntry = true;
compare.DictionaryKey = new KeyModel { TypeName = keyTypeName };
dictionaryKeyProperties?.Invoke(new DictionaryKeyDsl(compare));
source.ShouldMatchLineItem(compare);
}
public static void ShouldBeClosingComplexTypeDictionaryEntry(
this BodyDefinitionModel source, string name, string typeName, int level,
Action<ComplexTypeDsl> complexTypeProperties = null)
{
var compare = CreateComplexType(name, typeName, level, complexTypeProperties);
compare.IsClosing = true;
compare.IsDictionaryEntry = true;
source.ShouldMatchLineItem(compare);
}
private static BodyDefinitionModel CreateComplexType(string name,
int level, Action<ComplexTypeDsl> properties = null)
{
return CreateComplexType(name, name, level, properties);
}
private static BodyDefinitionModel CreateComplexType(string name,
string typeName, int level, Action<ComplexTypeDsl> properties = null)
{
var complexType = new BodyDefinitionModel
{
Name = name,
TypeName = typeName,
IsComplexType = true,
Whitespace = BodyDescriptionService.Whitespace.Repeat(level)
};
properties?.Invoke(new ComplexTypeDsl(complexType));
return complexType;
}
public class ComplexTypeDsl
{
private readonly BodyDefinitionModel _body;
public ComplexTypeDsl(BodyDefinitionModel body) { _body = body; }
public ComplexTypeDsl Comments(string comments)
{
_body.Comments = comments; return this;
}
public ComplexTypeDsl Opening() { _body.IsOpening = true; return this; }
public ComplexTypeDsl Closing() { _body.IsClosing = true; return this; }
public ComplexTypeDsl First() { _body.IsFirst = true; return this; }
public ComplexTypeDsl Last() { _body.IsLast = true; return this; }
public ComplexTypeDsl LogicalName(string logicalName)
{
_body.LogicalName = logicalName; return this;
}
public ComplexTypeDsl Namespace(string @namespace)
{
_body.Namespace = @namespace; return this;
}
public ComplexTypeDsl FullNamespace(params string[] @namespace)
{
_body.FullNamespace = @namespace.ToList(); return this;
}
}
// Common assertion DSLs
public class DictionaryKeyDsl
{
private readonly KeyModel _key;
public DictionaryKeyDsl(BodyDefinitionModel body)
{
_key = body.DictionaryKey;
}
public DictionaryKeyDsl KeyComments(string comments)
{
_key.Comments = comments; return this;
}
public OptionDsl KeyOptions(string name)
{
_key.Enumeration = _key.Enumeration ?? new Enumeration();
_key.Enumeration.Name = name;
return new OptionDsl(_key.Enumeration);
}
}
public class MemberDsl
{
private readonly BodyDefinitionModel _body;
public MemberDsl(BodyDefinitionModel body) { _body = body; }
public MemberDsl Comments(string comments)
{
_body.Comments = comments; return this;
}
public MemberDsl SampleValue(string sampleValue)
{
_body.SampleValue = sampleValue; return this;
}
public MemberDsl Default(string value) { _body.DefaultValue = value; return this; }
public MemberDsl Required() { _body.Optional = false; return this; }
public MemberDsl Optional() { _body.Optional = true; return this; }
public MemberDsl IsLastMember() { _body.IsLastMember = true; return this; }
public MemberDsl HasMaxLength(int value) { _body.MaxLength = value; return this; }
public MemberDsl HasEncoding(string value) { _body.Encoding = value; return this; }
public MemberDsl IsDeprecated(string message = null)
{
_body.IsDeprecated = true;
_body.DeprecationMessage = message;
return this;
}
}
public class OptionDsl
{
private readonly Enumeration _options;
public OptionDsl(Enumeration options) { _options = options; }
public OptionDsl WithOption(string value)
{
return WithOption(new Option { Value = value });
}
public OptionDsl WithOption(string name, string value)
{
return WithOption(new Option { Name = name, Value = value });
}
public OptionDsl WithOptionAndComments(string value, string comments)
{
return WithOption(new Option { Value = value, Comments = comments });
}
public OptionDsl WithOptionAndComments(string name, string value, string comments)
{
return WithOption(new Option { Name = name, Value = value, Comments = comments });
}
private OptionDsl WithOption(Option option)
{
if (_options.Options == null) _options.Options = new List<Option>();
_options.Options.Add(option); return this;
}
}
// Common assertions
public static List<BodyDefinitionModel> ShouldBeIndexed(this List<BodyDefinitionModel> source)
{
Enumerable.Range(0, source.Count).ForEach(x => source[x].Index.ShouldEqual(x + 1));
return source;
}
private static void ShouldMatchLineItem(this BodyDefinitionModel source, BodyDefinitionModel compare)
{
source.Name.ShouldEqual(compare.Name);
source.Comments.ShouldEqual(compare.Comments);
source.LogicalName.ShouldEqual(compare.LogicalName);
source.Namespace.ShouldEqual(compare.Namespace);
source.FullNamespace.ShouldOnlyContain(compare.FullNamespace?.ToArray());
source.IsFirst.ShouldEqual(compare.IsFirst);
source.IsLast.ShouldEqual(compare.IsLast);
source.TypeName.ShouldEqual(compare.TypeName);
source.SampleValue.ShouldEqual(compare.SampleValue);
source.DefaultValue.ShouldEqual(compare.DefaultValue);
source.Optional.ShouldEqual(compare.Optional);
source.Nullable.ShouldEqual(compare.Nullable);
source.Whitespace.ShouldEqual(compare.Whitespace);
source.IsDeprecated.ShouldEqual(compare.IsDeprecated);
source.DeprecationMessage.ShouldEqual(compare.DeprecationMessage);
source.MaxLength.ShouldEqual(compare.MaxLength);
source.Encoding.ShouldEqual(compare.Encoding);
source.IsOpening.ShouldEqual(compare.IsOpening);
source.IsClosing.ShouldEqual(compare.IsClosing);
source.IsMember.ShouldEqual(compare.IsMember);
source.IsLastMember.ShouldEqual(compare.IsLastMember);
source.IsSimpleType.ShouldEqual(compare.IsSimpleType);
source.IsString.ShouldEqual(compare.IsString);
source.IsBoolean.ShouldEqual(compare.IsBoolean);
source.IsNumeric.ShouldEqual(compare.IsNumeric);
source.IsDateTime.ShouldEqual(compare.IsDateTime);
source.IsDuration.ShouldEqual(compare.IsDuration);
source.IsGuid.ShouldEqual(compare.IsGuid);
source.Enumeration.ShouldEqualOptions(compare.Enumeration);
source.IsComplexType.ShouldEqual(compare.IsComplexType);
source.IsArray.ShouldEqual(compare.IsArray);
source.IsDictionary.ShouldEqual(compare.IsDictionary);
source.IsDictionaryEntry.ShouldEqual(compare.IsDictionaryEntry);
if (compare.DictionaryKey == null) source.DictionaryKey.ShouldBeNull();
else
{
source.DictionaryKey.TypeName.ShouldEqual(compare.DictionaryKey.TypeName);
source.DictionaryKey.Comments.ShouldEqual(compare.DictionaryKey.Comments);
source.DictionaryKey.Enumeration.ShouldEqualOptions(compare.DictionaryKey.Enumeration);
}
}
private static void ShouldEqualOptions(this Enumeration source, Enumeration compare)
{
if (compare == null) source.ShouldBeNull();
else
{
source.Name.ShouldEqual(compare.Name);
source.Comments.ShouldEqual(compare.Comments);
source.Options.ShouldTotal(compare.Options.Count);
foreach (var option in source.Options.Zip(compare.Options,
(s, c) => new { Source = s, Compare = c }))
{
option.Source.Name.ShouldEqual(option.Compare.Name);
option.Source.Comments.ShouldEqual(option.Compare.Comments);
option.Source.Value.ShouldEqual(option.Compare.Value);
}
}
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Settings;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.TemplateWizard;
using Project = EnvDTE.Project;
using ProjectItem = EnvDTE.ProjectItem;
namespace Microsoft.PythonTools.ProjectWizards {
public sealed class CloudServiceWizard : IWizard {
private IWizard _wizard;
#if DEV14
private readonly bool _recommendUpgrade;
const string AzureToolsDownload = "http://go.microsoft.com/fwlink/?linkid=518003";
#elif DEV15_OR_LATER
#else
#error Unsupported VS version
#endif
const string DontShowUpgradeDialogAgainProperty = "SuppressUpgradeAzureTools";
#if DEV14
private static bool ShouldRecommendUpgrade(Assembly asm) {
var attr = asm.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)
.OfType<AssemblyFileVersionAttribute>()
.FirstOrDefault();
Version ver;
if (attr != null && Version.TryParse(attr.Version, out ver)) {
Debug.WriteLine(ver);
// 2.4 is where we added integration, so we should recommend it
// to people who don't have it.
return ver < new Version(2, 4);
}
return false;
}
#endif
public CloudServiceWizard() {
try {
// If we fail to find the wizard, we will redirect the user to
// the WebPI download.
var asm = Assembly.Load("Microsoft.VisualStudio.CloudService.Wizard,Version=1.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a");
#if DEV14
_recommendUpgrade = ShouldRecommendUpgrade(asm);
#endif
var type = asm.GetType("Microsoft.VisualStudio.CloudService.Wizard.CloudServiceWizard");
_wizard = type.InvokeMember(null, BindingFlags.CreateInstance, null, null, new object[0]) as IWizard;
} catch (ArgumentException) {
} catch (BadImageFormatException) {
} catch (IOException) {
} catch (MemberAccessException) {
}
}
public void BeforeOpeningFile(ProjectItem projectItem) {
if (_wizard != null) {
_wizard.BeforeOpeningFile(projectItem);
}
}
public void ProjectFinishedGenerating(Project project) {
if (_wizard != null) {
_wizard.ProjectFinishedGenerating(project);
}
}
public void ProjectItemFinishedGenerating(ProjectItem projectItem) {
if (_wizard != null) {
_wizard.ProjectItemFinishedGenerating(projectItem);
}
}
public void RunFinished() {
if (_wizard != null) {
_wizard.RunFinished();
}
}
public bool ShouldAddProjectItem(string filePath) {
if (_wizard != null) {
return _wizard.ShouldAddProjectItem(filePath);
}
return false;
}
#if DEV14
private void StartDownload(IServiceProvider provider) {
Process.Start(new ProcessStartInfo(AzureToolsDownload));
}
private void OfferUpgrade(IServiceProvider provider) {
if (!_recommendUpgrade) {
return;
}
var sm = SettingsManagerCreator.GetSettingsManager(provider);
var store = sm.GetReadOnlySettingsStore(SettingsScope.UserSettings);
if (!store.CollectionExists(PythonConstants.DontShowUpgradeDialogAgainCollection) ||
!store.GetBoolean(PythonConstants.DontShowUpgradeDialogAgainCollection, DontShowUpgradeDialogAgainProperty, false)) {
var dlg = new TaskDialog(provider) {
Title = Strings.ProductTitle,
MainInstruction = Strings.AzureToolsUpgradeRecommended,
Content = Strings.AzureToolsUpgradeInstructions,
AllowCancellation = true,
VerificationText = Strings.DontShowAgain
};
var download = new TaskDialogButton(Strings.DownloadAndInstall);
dlg.Buttons.Add(download);
var cont = new TaskDialogButton(Strings.ContinueWithoutAzureToolsUpgrade);
dlg.Buttons.Add(cont);
dlg.Buttons.Add(TaskDialogButton.Cancel);
var response = dlg.ShowModal();
if (dlg.SelectedVerified) {
var rwStore = sm.GetWritableSettingsStore(SettingsScope.UserSettings);
rwStore.CreateCollection(PythonConstants.DontShowUpgradeDialogAgainCollection);
rwStore.SetBoolean(PythonConstants.DontShowUpgradeDialogAgainCollection, DontShowUpgradeDialogAgainProperty, true);
}
if (response == download) {
Process.Start(new ProcessStartInfo(AzureToolsDownload));
throw new WizardCancelledException();
} else if (response == TaskDialogButton.Cancel) {
// User cancelled, so go back to the New Project dialog
throw new WizardBackoutException();
}
}
}
#else
private void StartDownload(IServiceProvider provider) {
var svc = (IVsTrackProjectRetargeting2)provider.GetService(typeof(SVsTrackProjectRetargeting));
if (svc != null) {
IVsProjectAcquisitionSetupDriver driver;
if (ErrorHandler.Succeeded(svc.GetSetupDriver(VSConstants.SetupDrivers.SetupDriver_VS, out driver)) &&
driver != null) {
var task = driver.Install("Microsoft.VisualStudio.Component.Azure.Waverton");
if (task != null) {
task.Start();
throw new WizardCancelledException();
}
}
}
}
private void OfferUpgrade(IServiceProvider provider) {
}
#endif
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams) {
var provider = WizardHelpers.GetProvider(automationObject);
if (_wizard == null) {
try {
Directory.Delete(replacementsDictionary["$destinationdirectory$"]);
Directory.Delete(replacementsDictionary["$solutiondirectory$"]);
} catch {
// If it fails (doesn't exist/contains files/read-only), let the directory stay.
}
var dlg = new TaskDialog(provider) {
Title = Strings.ProductTitle,
MainInstruction = Strings.AzureToolsRequired,
Content = Strings.AzureToolsInstallInstructions,
AllowCancellation = true
};
dlg.Buttons.Add(TaskDialogButton.Cancel);
var download = new TaskDialogButton(Strings.DownloadAndInstall);
dlg.Buttons.Insert(0, download);
if (dlg.ShowModal() == download) {
StartDownload(provider);
throw new WizardCancelledException();
}
// User cancelled, so go back to the New Project dialog
throw new WizardBackoutException();
}
OfferUpgrade(provider);
// Run the original wizard to get the right replacements
_wizard.RunStarted(automationObject, replacementsDictionary, runKind, customParams);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
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;
namespace CH18___Board_Game
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
// the one and only game board
GameBoard m_GameBoard = new GameBoard();
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
//// use a fixed frame rate of 30 frames per second
//IsFixedTimeStep = true;
//TargetElapsedTime = new TimeSpan(0, 0, 0, 0, 33);
// run at full speed
IsFixedTimeStep = false;
// set screen size
InitScreen();
base.Initialize();
}
// screen constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
// screen-related init tasks
public void InitScreen()
{
// back buffer
graphics.PreferredBackBufferHeight = SCREEN_HEIGHT;
graphics.PreferredBackBufferWidth = SCREEN_WIDTH;
graphics.PreferMultiSampling = false;
graphics.ApplyChanges();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
GameBoard.Texture = Content.Load<Texture2D>(@"media\game");
NumberSprite.Texture = Content.Load<Texture2D>(@"media\numbers");
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
double elapsed = gameTime.ElapsedGameTime.TotalSeconds;
m_PressDelay -= elapsed;
ProcessInput();
m_GameBoard.Update(elapsed);
base.Update(gameTime);
}
// process (human) player input
public void ProcessInput()
{
// should we even process input now? no if current player is CPU
bool process = m_GameBoard.CurrentPlayerType() == PlayerType.Human;
process |= m_GameBoard.State == GameState.GameOver;
if (process)
{
// grab device states
GamePadState pad1 = GamePad.GetState(PlayerIndex.One);
GamePadState pad2 = GamePad.GetState(PlayerIndex.Two);
KeyboardState key1 = Keyboard.GetState();
// if there's only one gamepad, share it
if (!pad2.IsConnected) pad2 = pad1;
// process input based on current player
switch (m_GameBoard.CurrentPlayer)
{
case Player.One:
ProcessInput(pad1, key1);
break;
case Player.Two:
ProcessInput(pad2, key1);
break;
}
}
}
// very simple way to keep from registering multiple button presses
private double m_PressDelay = 0;
private const double PRESS_DELAY = 0.25;
// actually process the input
private void ProcessInput(GamePadState pad, KeyboardState kbd)
{
bool pressed;
// move to previous valid move
pressed = pad.Triggers.Left > 0;
pressed |= pad.DPad.Left == ButtonState.Pressed;
pressed |= pad.ThumbSticks.Left.X < 0;
pressed |= kbd.IsKeyDown(Keys.Left);
if (pressed && m_PressDelay <= 0)
{
m_PressDelay = PRESS_DELAY;
m_GameBoard.PreviousValidMove();
}
// move to next valid move
pressed = pad.Triggers.Right > 0;
pressed |= pad.DPad.Right == ButtonState.Pressed;
pressed |= pad.ThumbSticks.Left.X > 0;
pressed |= kbd.IsKeyDown(Keys.Right);
if (pressed && m_PressDelay <= 0)
{
m_PressDelay = PRESS_DELAY;
m_GameBoard.NextValidMove();
}
// commit selection as your move
pressed = pad.Buttons.A == ButtonState.Pressed;
pressed |= kbd.IsKeyDown(Keys.Space);
if (pressed && m_PressDelay <= 0)
{
m_PressDelay = PRESS_DELAY;
m_GameBoard.MakeMove();
}
// start a new game
// only works when it's a human's turn so that AI threads
// (if any) have time to complete
pressed = pad.Buttons.Start == ButtonState.Pressed;
pressed |= kbd.IsKeyDown(Keys.Enter);
if (pressed && m_PressDelay <= 0)
{
m_PressDelay = PRESS_DELAY;
m_GameBoard = new GameBoard();
}
// pick previous player two type
pressed = pad.Buttons.LeftShoulder == ButtonState.Pressed;
pressed |= kbd.IsKeyDown(Keys.PageUp);
if (pressed && m_PressDelay <= 0)
{
m_PressDelay = PRESS_DELAY;
m_GameBoard.PreviousPlayerType();
}
// pick next player two type
pressed = pad.Buttons.RightShoulder == ButtonState.Pressed;
pressed |= kbd.IsKeyDown(Keys.PageDown);
if (pressed && m_PressDelay <= 0)
{
m_PressDelay = PRESS_DELAY;
m_GameBoard.NextPlayerType();
}
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
m_GameBoard.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Management.Automation.Internal;
#if !CORECLR
using System.Security.Permissions;
#else
// Use stub for SerializableAttribute, SecurityPermissionAttribute and ISerializable related types.
using Microsoft.PowerShell.CoreClr.Stubs;
#endif
namespace System.Management.Automation
{
/// <summary>
/// An exception that wraps all exceptions that are thrown by providers. This allows
/// callers of the provider APIs to be able to catch a single exception no matter
/// what any of the various providers may have thrown.
/// </summary>
[Serializable]
public class ProviderInvocationException : RuntimeException
{
#region Constructors
/// <summary>
/// Constructs a ProviderInvocationException
/// </summary>
public ProviderInvocationException() : base()
{
}
/// <summary>
/// Constructs a ProviderInvocationException using serialized data
/// </summary>
///
/// <param name="info">
/// serialization information
/// </param>
///
/// <param name="context">
/// streaming context
/// </param>
protected ProviderInvocationException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
/// <summary>
/// Constructs a ProviderInvocationException with a message
/// </summary>
///
/// <param name="message">
/// The message for the exception.
/// </param>
public ProviderInvocationException(string message)
: base(message)
{
_message = message;
}
/// <summary>
/// Constructs a ProviderInvocationException with provider information and an inner exception.
/// </summary>
///
/// <param name="provider">
/// Information about the provider to be used in formatting the message.
/// </param>
///
/// <param name="innerException">
/// The inner exception for this exception.
/// </param>
internal ProviderInvocationException(ProviderInfo provider, Exception innerException)
: base(RuntimeException.RetrieveMessage(innerException), innerException)
{
_message = base.Message;
_providerInfo = provider;
IContainsErrorRecord icer = innerException as IContainsErrorRecord;
if (null != icer && null != icer.ErrorRecord)
{
_errorRecord = new ErrorRecord(icer.ErrorRecord, innerException);
}
else
{
_errorRecord = new ErrorRecord(
innerException,
"ErrorRecordNotSpecified",
ErrorCategory.InvalidOperation,
null);
}
}
/// <summary>
/// Constructs a ProviderInvocationException with provider information and an
/// ErrorRecord.
/// </summary>
///
/// <param name="provider">
/// Information about the provider to be used in formatting the message.
/// </param>
///
/// <param name="errorRecord">
/// Detailed error information
/// </param>
internal ProviderInvocationException(ProviderInfo provider, ErrorRecord errorRecord)
: base(RuntimeException.RetrieveMessage(errorRecord),
RuntimeException.RetrieveException(errorRecord))
{
if (null == errorRecord)
{
throw new ArgumentNullException("errorRecord");
}
_message = base.Message;
_providerInfo = provider;
_errorRecord = errorRecord;
}
/// <summary>
/// Constructs a ProviderInvocationException with a message
/// and inner exception.
/// </summary>
///
/// <param name="message">
/// The message for the exception.
/// </param>
///
/// <param name="innerException">
/// The inner exception for this exception.
/// </param>
public ProviderInvocationException(string message, Exception innerException)
: base(message, innerException)
{
_message = message;
}
/// <summary>
/// Constructs a ProviderInvocationException
/// </summary>
///
/// <param name="errorId">
/// This string will be used to construct the FullyQualifiedErrorId,
/// which is a global identifier of the error condition. Pass a
/// non-empty string which is specific to this error condition in
/// this context.
/// </param>
///
/// <param name="resourceStr">
/// This string is the message template string.
/// </param>
///
/// <param name="provider">
/// The provider information used to format into the message.
/// </param>
///
/// <param name="path">
/// The path that was being processed when the exception occurred.
/// </param>
///
/// <param name="innerException">
/// The exception that was thrown by the provider.
/// </param>
///
internal ProviderInvocationException(
string errorId,
string resourceStr,
ProviderInfo provider,
string path,
Exception innerException)
: this(errorId, resourceStr, provider, path, innerException, true)
{
}
/// <summary>
/// Constructor to make it easy to wrap a provider exception
/// </summary>
///
/// <param name="errorId">
/// This string will be used to construct the FullyQualifiedErrorId,
/// which is a global identifier of the error condition. Pass a
/// non-empty string which is specific to this error condition in
/// this context.
/// </param>
///
/// <param name="resourceStr">
/// This is the message template string
/// </param>
///
/// <param name="provider">
/// The provider information used to format into the message.
/// </param>
///
/// <param name="path">
/// The path that was being processed when the exception occurred.
/// </param>
///
/// <param name="innerException">
/// The exception that was thrown by the provider.
/// </param>
///
/// <param name="useInnerExceptionMessage">
/// If true, the message from the inner exception will be used if the exception contains
/// an ErrorRecord. If false, the error message retrieved using the errorId will be used.
/// </param>
///
internal ProviderInvocationException(
string errorId,
string resourceStr,
ProviderInfo provider,
string path,
Exception innerException,
bool useInnerExceptionMessage)
: base(
RetrieveMessage(errorId, resourceStr, provider, path, innerException),
innerException)
{
_providerInfo = provider;
_message = base.Message;
Exception errorRecordException = null;
if (useInnerExceptionMessage)
{
errorRecordException = innerException;
}
else
{
errorRecordException = new ParentContainsErrorRecordException(this);
}
IContainsErrorRecord icer = innerException as IContainsErrorRecord;
if (null != icer && null != icer.ErrorRecord)
{
_errorRecord = new ErrorRecord(icer.ErrorRecord, errorRecordException);
}
else
{
_errorRecord = new ErrorRecord(
errorRecordException,
errorId,
ErrorCategory.InvalidOperation,
null);
}
}
#endregion Constructors
#region Properties
/// <summary>
/// Gets the provider information of the provider that threw an exception.
/// </summary>
public ProviderInfo ProviderInfo { get { return _providerInfo; } }
[NonSerialized]
internal ProviderInfo _providerInfo;
/// <summary>
/// Gets the error record.
/// </summary>
public override ErrorRecord ErrorRecord
{
get
{
if (null == _errorRecord)
{
_errorRecord = new ErrorRecord(
new ParentContainsErrorRecordException(this),
"ProviderInvocationException",
ErrorCategory.NotSpecified,
null);
}
return _errorRecord;
}
}
[NonSerialized]
private ErrorRecord _errorRecord;
#endregion Properties
#region Private/Internal
private static string RetrieveMessage(
string errorId,
string resourceStr,
ProviderInfo provider,
string path,
Exception innerException)
{
if (null == innerException)
{
Diagnostics.Assert(false,
"ProviderInvocationException.RetrieveMessage needs innerException");
return "";
}
if (String.IsNullOrEmpty(errorId))
{
Diagnostics.Assert(false,
"ProviderInvocationException.RetrieveMessage needs errorId");
return RuntimeException.RetrieveMessage(innerException);
}
if (null == provider)
{
Diagnostics.Assert(false,
"ProviderInvocationException.RetrieveMessage needs provider");
return RuntimeException.RetrieveMessage(innerException);
}
string format = resourceStr;
if (String.IsNullOrEmpty(format))
{
Diagnostics.Assert(false,
"ProviderInvocationException.RetrieveMessage bad errorId " + errorId);
return RuntimeException.RetrieveMessage(innerException);
}
string result = null;
if (path == null)
{
result =
String.Format(
System.Globalization.CultureInfo.CurrentCulture,
format,
provider.Name,
RuntimeException.RetrieveMessage(innerException));
}
else
{
result =
String.Format(
System.Globalization.CultureInfo.CurrentCulture,
format,
provider.Name,
path,
RuntimeException.RetrieveMessage(innerException));
}
return result;
}
/// <summary>
/// Gets the exception message
/// </summary>
public override string Message
{
get { return (String.IsNullOrEmpty(_message)) ? base.Message : _message; }
}
[NonSerialized]
private string _message /* = null */;
#endregion Private/Internal
}
/// <summary>
/// Categories of session state objects, used by SessionStateException
/// </summary>
public enum SessionStateCategory
{
/// <summary>
/// Used when an exception is thrown accessing a variable.
/// </summary>
Variable = 0,
/// <summary>
/// Used when an exception is thrown accessing an alias.
/// </summary>
Alias = 1,
/// <summary>
/// Used when an exception is thrown accessing a function.
/// </summary>
Function = 2,
/// <summary>
/// Used when an exception is thrown accessing a filter.
/// </summary>
Filter = 3,
/// <summary>
/// Used when an exception is thrown accessing a drive.
/// </summary>
Drive = 4,
/// <summary>
/// Used when an exception is thrown accessing a Cmdlet Provider.
/// </summary>
CmdletProvider = 5,
/// <summary>
/// Used when an exception is thrown manipulating the PowerShell language scopes.
/// </summary>
Scope = 6,
/// <summary>
/// Used when generically accessing any type of command...
/// </summary>
Command = 7,
/// <summary>
/// Other resources not covered by the previous categories...
/// </summary>
Resource = 8,
/// <summary>
/// Used when an exception is thrown accessing a cmdlet.
/// </summary>
Cmdlet = 9,
}
/// <summary>
/// SessionStateException represents an error working with
/// session state objects: variables, aliases, functions, filters,
/// drives, or providers.
/// </summary>
[Serializable]
public class SessionStateException : RuntimeException
{
#region ctor
/// <summary>
/// Constructs a SessionStateException
/// </summary>
///
/// <param name="itemName"> name of session state object </param>
/// <param name="sessionStateCategory"> category of session state object </param>
/// <param name="resourceStr">This string is the message template string.</param>
/// <param name="errorIdAndResourceId">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
/// <param name="errorCategory"> ErrorRecord.CategoryInfo.Category </param>
/// <param name="messageArgs">
/// Additional insertion strings used to construct the message.
/// Note that itemName is always the first insertion string.
/// </param>
internal SessionStateException(
string itemName,
SessionStateCategory sessionStateCategory,
string errorIdAndResourceId,
string resourceStr,
ErrorCategory errorCategory,
params object[] messageArgs)
: base(BuildMessage(itemName, resourceStr, messageArgs))
{
_itemName = itemName;
_sessionStateCategory = sessionStateCategory;
_errorId = errorIdAndResourceId;
_errorCategory = errorCategory;
}
/// <summary>
/// Constructs a SessionStateException
/// </summary>
public SessionStateException()
: base()
{
}
/// <summary>
/// Constructs a SessionStateException
/// </summary>
///
/// <param name="message">
/// The message used in the exception.
/// </param>
public SessionStateException(string message)
: base(message)
{
}
/// <summary>
/// Constructs a SessionStateException
/// </summary>
///
/// <param name="message">
/// The message used in the exception.
/// </param>
///
/// <param name="innerException">
/// The exception that caused the error.
/// </param>
public SessionStateException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Constructs a SessionStateException using serialized data.
/// </summary>
/// <param name="info"> serialization information </param>
/// <param name="context"> streaming context </param>
protected SessionStateException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
_sessionStateCategory = (SessionStateCategory)info.GetInt32("SessionStateCategory"); // CODEWORK test this
}
/// <summary>
/// Serializes the exception data.
/// </summary>
/// <param name="info"> serialization information </param>
/// <param name="context"> streaming context </param>
[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
{
throw new PSArgumentNullException("info");
}
base.GetObjectData(info, context);
// If there are simple fields, serialize them with info.AddValue
info.AddValue("SessionStateCategory", (Int32)_sessionStateCategory);
}
#endregion Serialization
#region Properties
/// <summary>
/// Gets the error record information for this exception.
/// </summary>
public override ErrorRecord ErrorRecord
{
get
{
if (null == _errorRecord)
{
_errorRecord = new ErrorRecord(
new ParentContainsErrorRecordException(this),
_errorId,
_errorCategory,
_itemName);
}
return _errorRecord;
}
}
private ErrorRecord _errorRecord;
/// <summary>
/// Gets the name of session state object the error occurred on.
/// </summary>
public string ItemName
{
get { return _itemName; }
}
private string _itemName = String.Empty;
/// <summary>
/// Gets the category of session state object the error occurred on.
/// </summary>
public SessionStateCategory SessionStateCategory
{
get { return _sessionStateCategory; }
}
private SessionStateCategory _sessionStateCategory = SessionStateCategory.Variable;
#endregion Properties
#region Private
private string _errorId = "SessionStateException";
private ErrorCategory _errorCategory = ErrorCategory.InvalidArgument;
private static string BuildMessage(
string itemName,
string resourceStr,
params object[] messageArgs)
{
object[] a;
if (null != messageArgs && 0 < messageArgs.Length)
{
a = new object[messageArgs.Length + 1];
a[0] = itemName;
messageArgs.CopyTo(a, 1);
}
else
{
a = new object[1];
a[0] = itemName;
}
return StringUtil.Format(resourceStr, a);
}
#endregion Private
} // SessionStateException
/// <summary>
/// SessionStateOverflowException occurs when the number of
/// session state objects of this type in this scope
/// exceeds the configured maximum.
/// </summary>
[Serializable]
public class SessionStateOverflowException : SessionStateException
{
#region ctor
/// <summary>
/// Constructs a SessionStateOverflowException
/// </summary>
/// <param name="itemName">
/// The name of the session state object the error occurred on.
/// </param>
///
/// <param name="sessionStateCategory">
/// The category of session state object.
/// </param>
///
/// <param name="errorIdAndResourceId">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
///
/// <param name="resourceStr">
/// This string is the message template string
/// </param>
///
/// <param name="messageArgs">
/// Additional insertion strings used to construct the message.
/// Note that itemName is always the first insertion string.
/// </param>
internal SessionStateOverflowException(
string itemName,
SessionStateCategory sessionStateCategory,
string errorIdAndResourceId,
string resourceStr,
params object[] messageArgs
)
: base(itemName, sessionStateCategory, errorIdAndResourceId, resourceStr,
ErrorCategory.InvalidOperation, messageArgs)
{
}
/// <summary>
/// Constructs a SessionStateOverflowException
/// </summary>
public SessionStateOverflowException()
: base()
{
}
/// <summary>
/// Constructs a SessionStateOverflowException with a message.
/// </summary>
/// <param name="message">
/// The message used by the exception.
/// </param>
public SessionStateOverflowException(string message) : base(message)
{
}
/// <summary>
/// Constructs a SessionStateOverflowException
/// </summary>
///
/// <param name="message">
/// The message the exception will use.
/// </param>
///
/// <param name="innerException">
/// The exception that caused the error.
/// </param>
public SessionStateOverflowException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Constructs a SessionStateOverflowException using serialized data.
/// </summary>
///
/// <param name="info"> serialization information </param>
/// <param name="context"> streaming context </param>
protected SessionStateOverflowException(SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion Serialization
} // SessionStateOverflowException
/// <summary>
/// SessionStateUnauthorizedAccessException occurs when
/// a change to a session state object cannot be completed
/// because the object is read-only or constant, or because
/// an object which is declared constant cannot be removed
/// or made non-constant.
/// </summary>
[Serializable]
public class SessionStateUnauthorizedAccessException : SessionStateException
{
#region ctor
/// <summary>
/// Constructs a SessionStateUnauthorizedAccessException
/// </summary>
///
/// <param name="itemName">
/// The name of the session state object the error occurred on.
/// </param>
///
/// <param name="sessionStateCategory">
/// The category of session state object.
/// </param>
///
/// <param name="errorIdAndResourceId">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
///
/// <param name="resourceStr">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
internal SessionStateUnauthorizedAccessException(
string itemName,
SessionStateCategory sessionStateCategory,
string errorIdAndResourceId,
string resourceStr
)
: base(itemName, sessionStateCategory,
errorIdAndResourceId, resourceStr, ErrorCategory.WriteError)
{
}
/// <summary>
/// Constructs a SessionStateUnauthorizedAccessException
/// </summary>
public SessionStateUnauthorizedAccessException()
: base()
{
}
/// <summary>
/// Constructs a SessionStateUnauthorizedAccessException
/// </summary>
/// <param name="message">
/// The message used by the exception.
/// </param>
public SessionStateUnauthorizedAccessException(string message)
: base(message)
{
}
/// <summary>
/// Constructs a SessionStateUnauthorizedAccessException
/// </summary>
/// <param name="message">
/// The message used by the exception.
/// </param>
///
/// <param name="innerException">
/// The exception that caused the error.
/// </param>
public SessionStateUnauthorizedAccessException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Constructs a SessionStateUnauthorizedAccessException using serialized data.
/// </summary>
///
/// <param name="info"> serialization information </param>
/// <param name="context"> streaming context </param>
protected SessionStateUnauthorizedAccessException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion Serialization
} // SessionStateUnauthorizedAccessException
/// <summary>
/// ProviderNotFoundException occurs when no provider can be found
/// with the specified name.
/// </summary>
[Serializable]
public class ProviderNotFoundException : SessionStateException
{
#region ctor
/// <summary>
/// Constructs a ProviderNotFoundException
/// </summary>
///
/// <param name="itemName">
/// The name of provider that could not be found.
/// </param>
///
/// <param name="sessionStateCategory">
/// The category of session state object
/// </param>
///
/// <param name="errorIdAndResourceId">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
///
/// <param name="resourceStr">
/// This string is the message template string
/// </param>
///
/// <param name="messageArgs">
/// Additional arguments to build the message from.
/// </param>
internal ProviderNotFoundException(
string itemName,
SessionStateCategory sessionStateCategory,
string errorIdAndResourceId,
string resourceStr,
params object[] messageArgs)
: base(
itemName,
sessionStateCategory,
errorIdAndResourceId,
resourceStr,
ErrorCategory.ObjectNotFound,
messageArgs)
{
}
/// <summary>
/// Constructs a ProviderNotFoundException
/// </summary>
public ProviderNotFoundException()
: base()
{
}
/// <summary>
/// Constructs a ProviderNotFoundException
/// </summary>
/// <param name="message">
/// The messaged used by the exception.
/// </param>
public ProviderNotFoundException(string message)
: base(message)
{
}
/// <summary>
/// Constructs a ProviderNotFoundException
/// </summary>
/// <param name="message">
/// The message used by the exception.
/// </param>
/// <param name="innerException">
/// The exception that caused the error.
/// </param>
public ProviderNotFoundException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Constructs a ProviderNotFoundException using serialized data.
/// </summary>
/// <param name="info"> serialization information </param>
/// <param name="context"> streaming context </param>
protected ProviderNotFoundException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion Serialization
} // ProviderNotFoundException
/// <summary>
/// ProviderNameAmbiguousException occurs when more than one provider exists
/// for a given name and the request did not contain the PSSnapin name qualifier.
/// </summary>
[Serializable]
public class ProviderNameAmbiguousException : ProviderNotFoundException
{
#region ctor
/// <summary>
/// Constructs a ProviderNameAmbiguousException
/// </summary>
///
/// <param name="providerName">
/// The name of provider that was ambiguous.
/// </param>
///
/// <param name="errorIdAndResourceId">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
///
/// <param name="resourceStr">
/// This string is the message template string
/// </param>
///
/// <param name="possibleMatches">
/// The provider information for the providers that match the specified
/// name.
/// </param>
///
/// <param name="messageArgs">
/// Additional arguments to build the message from.
/// </param>
internal ProviderNameAmbiguousException(
string providerName,
string errorIdAndResourceId,
string resourceStr,
Collection<ProviderInfo> possibleMatches,
params object[] messageArgs)
: base(
providerName,
SessionStateCategory.CmdletProvider,
errorIdAndResourceId,
resourceStr,
messageArgs)
{
_possibleMatches = new ReadOnlyCollection<ProviderInfo>(possibleMatches);
}
/// <summary>
/// Constructs a ProviderNameAmbiguousException
/// </summary>
public ProviderNameAmbiguousException()
: base()
{
}
/// <summary>
/// Constructs a ProviderNameAmbiguousException
/// </summary>
/// <param name="message">
/// The messaged used by the exception.
/// </param>
public ProviderNameAmbiguousException(string message)
: base(message)
{
}
/// <summary>
/// Constructs a ProviderNameAmbiguousException
/// </summary>
/// <param name="message">
/// The message used by the exception.
/// </param>
/// <param name="innerException">
/// The exception that caused the error.
/// </param>
public ProviderNameAmbiguousException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Constructs a ProviderNameAmbiguousException using serialized data.
/// </summary>
/// <param name="info"> serialization information </param>
/// <param name="context"> streaming context </param>
protected ProviderNameAmbiguousException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion Serialization
#region public properties
/// <summary>
/// Gets the information of the providers which might match the specified
/// provider name.
/// </summary>
public ReadOnlyCollection<ProviderInfo> PossibleMatches
{
get
{
return _possibleMatches;
}
}
private ReadOnlyCollection<ProviderInfo> _possibleMatches;
#endregion public properties
} // ProviderNameAmbiguousException
/// <summary>
/// DriveNotFoundException occurs when no drive can be found
/// with the specified name.
/// </summary>
[Serializable]
public class DriveNotFoundException : SessionStateException
{
#region ctor
/// <summary>
/// Constructs a DriveNotFoundException
/// </summary>
/// <param name="itemName">
/// The name of the drive that could not be found.
/// </param>
///
/// <param name="errorIdAndResourceId">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
///
/// <param name="resourceStr">
/// This string is the message template string
/// </param>
internal DriveNotFoundException(
string itemName,
string errorIdAndResourceId,
string resourceStr
)
: base(itemName, SessionStateCategory.Drive,
errorIdAndResourceId, resourceStr, ErrorCategory.ObjectNotFound)
{
}
/// <summary>
/// Constructs a DriveNotFoundException
/// </summary>
public DriveNotFoundException()
: base()
{
}
/// <summary>
/// Constructs a DriveNotFoundException
/// </summary>
/// <param name="message">
/// The message that will be used by the exception.
/// </param>
public DriveNotFoundException(string message)
: base(message)
{
}
/// <summary>
/// Constructs a DriveNotFoundException
/// </summary>
/// <param name="message">
/// The message that will be used by the exception.
/// </param>
///
/// <param name="innerException">
/// The exception that caused the error.
/// </param>
public DriveNotFoundException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Constructs a DriveNotFoundException using serialized data.
/// </summary>
/// <param name="info"> serialization information </param>
/// <param name="context"> streaming context </param>
protected DriveNotFoundException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion Serialization
} // DriveNotFoundException
/// <summary>
/// ItemNotFoundException occurs when the path contained no wildcard characters
/// and an item at that path could not be found.
/// </summary>
[Serializable]
public class ItemNotFoundException : SessionStateException
{
#region ctor
/// <summary>
/// Constructs a ItemNotFoundException
/// </summary>
/// <param name="path">
/// The path that was not found.
/// </param>
///
/// <param name="errorIdAndResourceId">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
///
/// <param name="resourceStr">
/// This string is the ErrorId passed to the ErrorRecord, and is also
/// the resourceId used to look up the message template string in
/// SessionStateStrings.txt.
/// </param>
internal ItemNotFoundException(
string path,
string errorIdAndResourceId,
string resourceStr
)
: base(path, SessionStateCategory.Drive,
errorIdAndResourceId, resourceStr, ErrorCategory.ObjectNotFound)
{
}
/// <summary>
/// Constructs a ItemNotFoundException
/// </summary>
public ItemNotFoundException()
: base()
{
}
/// <summary>
/// Constructs a ItemNotFoundException
/// </summary>
/// <param name="message">
/// The message used by the exception.
/// </param>
public ItemNotFoundException(string message)
: base(message)
{
}
/// <summary>
/// Constructs a ItemNotFoundException
/// </summary>
/// <param name="message">
/// The message used by the exception.
/// </param>
/// <param name="innerException">
/// The exception that caused the error.
/// </param>
public ItemNotFoundException(string message,
Exception innerException)
: base(message, innerException)
{
}
#endregion ctor
#region Serialization
/// <summary>
/// Constructs a ItemNotFoundException using serialized data.
/// </summary>
/// <param name="info"> serialization information </param>
/// <param name="context"> streaming context </param>
protected ItemNotFoundException(
SerializationInfo info,
StreamingContext context)
: base(info, context)
{
}
#endregion Serialization
} // ItemNotFoundException
} // namespace System.Management.Automation
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyFormData
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Formdata operations.
/// </summary>
public partial class Formdata : IServiceOperations<AutoRestSwaggerBATFormDataService>, IFormdata
{
/// <summary>
/// Initializes a new instance of the Formdata class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public Formdata(AutoRestSwaggerBATFormDataService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestSwaggerBATFormDataService
/// </summary>
public AutoRestSwaggerBATFormDataService Client { get; private set; }
/// <summary>
/// Upload file
/// </summary>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='fileName'>
/// File name to upload. Name has to be spelled exactly as written here.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.IO.Stream>> UploadFileWithHttpMessagesAsync(System.IO.Stream fileContent, string fileName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (fileContent == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fileContent");
}
if (fileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fileName");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fileContent", fileContent);
tracingParameters.Add("fileName", fileName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "UploadFile", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "formdata/stream/uploadfile").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
MultipartFormDataContent _multiPartContent = new MultipartFormDataContent();
if (fileContent != null)
{
StreamContent _fileContent = new StreamContent(fileContent);
_fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
System.IO.FileStream _fileContentAsFileStream = fileContent as System.IO.FileStream;
if (_fileContentAsFileStream != null)
{
ContentDispositionHeaderValue _contentDispositionHeaderValue = new ContentDispositionHeaderValue("form-data");
_contentDispositionHeaderValue.Name = "fileContent";
_contentDispositionHeaderValue.FileName = _fileContentAsFileStream.Name;
_fileContent.Headers.ContentDisposition = _contentDispositionHeaderValue;
}
_multiPartContent.Add(_fileContent, "fileContent");
}
if (fileName != null)
{
StringContent _fileName = new StringContent(fileName, Encoding.UTF8);
_multiPartContent.Add(_fileName, "fileName");
}
_httpRequest.Content = _multiPartContent;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<System.IO.Stream>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Upload file
/// </summary>
/// <param name='fileContent'>
/// File to upload.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<System.IO.Stream>> UploadFileViaBodyWithHttpMessagesAsync(System.IO.Stream fileContent, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (fileContent == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "fileContent");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("fileContent", fileContent);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "UploadFileViaBody", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "formdata/stream/uploadfile").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
StreamContent _fileStreamContent = new StreamContent(fileContent);
_httpRequest.Content = _fileStreamContent;
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<System.IO.Stream>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
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;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using Orleans.Concurrency;
using Orleans.Runtime;
using Orleans.Streams;
namespace Orleans.Providers.Streams.SimpleMessageStream
{
/// <summary>
/// Multiplexes messages to mutiple different producers in the same grain over one grain-extension interface.
///
/// On the silo, we have one extension per activation and this extesion multiplexes all streams on this activation
/// (different stream ids and different stream providers).
/// On the client, we have one extension per stream (we bind an extesion for every StreamProducer, therefore every stream has its own extension).
/// </summary>
[Serializable]
internal class SimpleMessageStreamProducerExtension : IStreamProducerExtension
{
private readonly Dictionary<StreamId, StreamConsumerExtensionCollection> remoteConsumers;
private readonly IStreamProviderRuntime providerRuntime;
private readonly bool fireAndForgetDelivery;
private readonly Logger logger;
internal SimpleMessageStreamProducerExtension(IStreamProviderRuntime providerRt, bool fireAndForget)
{
providerRuntime = providerRt;
fireAndForgetDelivery = fireAndForget;
remoteConsumers = new Dictionary<StreamId, StreamConsumerExtensionCollection>();
logger = providerRuntime.GetLogger(GetType().Name);
}
internal void AddStream(StreamId streamId)
{
StreamConsumerExtensionCollection obs;
// no need to lock on _remoteConsumers, since on the client we have one extension per stream (per StreamProducer)
// so this call is only made once, when StreamProducer is created.
if (remoteConsumers.TryGetValue(streamId, out obs)) return;
obs = new StreamConsumerExtensionCollection();
remoteConsumers.Add(streamId, obs);
}
internal void RemoveStream(StreamId streamId)
{
remoteConsumers.Remove(streamId);
}
internal void AddSubscribers(StreamId streamId, ICollection<PubSubSubscriptionState> newSubscribers)
{
if (logger.IsVerbose) logger.Verbose("{0} AddSubscribers {1} for stream {2}", providerRuntime.ExecutingEntityIdentity(), Utils.EnumerableToString(newSubscribers), streamId);
StreamConsumerExtensionCollection consumers;
if (remoteConsumers.TryGetValue(streamId, out consumers))
{
foreach (var newSubscriber in newSubscribers)
{
consumers.AddRemoteSubscriber(newSubscriber.SubscriptionId, newSubscriber.Consumer, newSubscriber.Filter);
}
}
else
{
// We got an item when we don't think we're the subscriber. This is a normal race condition.
// We can drop the item on the floor, or pass it to the rendezvous, or log a warning.
}
}
internal Task DeliverItem(StreamId streamId, object item)
{
StreamConsumerExtensionCollection consumers;
if (remoteConsumers.TryGetValue(streamId, out consumers))
{
// Note: This is the main hot code path,
// and the caller immediately does await on the Task
// returned from this method, so we can just direct return here
// without incurring overhead of additional await.
return consumers.DeliverItem(streamId, item, fireAndForgetDelivery);
}
else
{
// We got an item when we don't think we're the subscriber. This is a normal race condition.
// We can drop the item on the floor, or pass it to the rendezvous, or log a warning.
}
return TaskDone.Done;
}
internal Task CompleteStream(StreamId streamId)
{
StreamConsumerExtensionCollection consumers;
if (remoteConsumers.TryGetValue(streamId, out consumers))
{
return consumers.CompleteStream(streamId, fireAndForgetDelivery);
}
else
{
// We got an item when we don't think we're the subscriber. This is a normal race condition.
// We can drop the item on the floor, or pass it to the rendezvous, or log a warning.
}
return TaskDone.Done;
}
internal Task ErrorInStream(StreamId streamId, Exception exc)
{
StreamConsumerExtensionCollection consumers;
if (remoteConsumers.TryGetValue(streamId, out consumers))
{
return consumers.ErrorInStream(streamId, exc, fireAndForgetDelivery);
}
else
{
// We got an item when we don't think we're the subscriber. This is a normal race condition.
// We can drop the item on the floor, or pass it to the rendezvous, or log a warning.
}
return TaskDone.Done;
}
// Called by rendezvous when new remote subsriber subscribes to this stream.
public Task AddSubscriber(GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, StreamSequenceToken token, IStreamFilterPredicateWrapper filter)
{
if (logger.IsVerbose)
{
logger.Verbose("{0} AddSubscriber {1} for stream {2}", providerRuntime.ExecutingEntityIdentity(), streamConsumer, streamId);
}
StreamConsumerExtensionCollection consumers;
if (remoteConsumers.TryGetValue(streamId, out consumers))
{
consumers.AddRemoteSubscriber(subscriptionId, streamConsumer, filter);
}
else
{
// We got an item when we don't think we're the subscriber. This is a normal race condition.
// We can drop the item on the floor, or pass it to the rendezvous, or log a warning.
}
return TaskDone.Done;
}
public Task RemoveSubscriber(GuidId subscriptionId, StreamId streamId)
{
if (logger.IsVerbose)
{
logger.Verbose("{0} RemoveSubscription {1}", providerRuntime.ExecutingEntityIdentity(),
subscriptionId);
}
foreach (StreamConsumerExtensionCollection consumers in remoteConsumers.Values)
{
consumers.RemoveRemoteSubscriber(subscriptionId);
}
return TaskDone.Done;
}
[Serializable]
internal class StreamConsumerExtensionCollection
{
private readonly ConcurrentDictionary<GuidId, Tuple<IStreamConsumerExtension, IStreamFilterPredicateWrapper>> consumers;
internal StreamConsumerExtensionCollection()
{
consumers = new ConcurrentDictionary<GuidId, Tuple<IStreamConsumerExtension, IStreamFilterPredicateWrapper>>();
}
internal void AddRemoteSubscriber(GuidId subscriptionId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter)
{
consumers.TryAdd(subscriptionId, Tuple.Create(streamConsumer, filter));
}
internal void RemoveRemoteSubscriber(GuidId subscriptionId)
{
Tuple<IStreamConsumerExtension, IStreamFilterPredicateWrapper> ignore;
consumers.TryRemove(subscriptionId, out ignore);
if (consumers.Count == 0)
{
// Unsubscribe from PubSub?
}
}
internal Task DeliverItem(StreamId streamId, object item, bool fireAndForgetDelivery)
{
var tasks = fireAndForgetDelivery ? null : new List<Task>();
var immutableItem = new Immutable<object>(item);
foreach (KeyValuePair<GuidId, Tuple<IStreamConsumerExtension, IStreamFilterPredicateWrapper>> subscriptionKvp in consumers)
{
IStreamConsumerExtension remoteConsumer = subscriptionKvp.Value.Item1;
// Apply filter(s) to see if we should forward this item to this consumer
IStreamFilterPredicateWrapper filter = subscriptionKvp.Value.Item2;
if (filter != null)
{
if (!filter.ShouldReceive(streamId, filter.FilterData, item))
continue;
}
Task task = remoteConsumer.DeliverItem(subscriptionKvp.Key, immutableItem, null);
if (fireAndForgetDelivery) task.Ignore();
else tasks.Add(task);
}
// If there's no subscriber, presumably we just drop the item on the floor
return fireAndForgetDelivery ? TaskDone.Done : Task.WhenAll(tasks);
}
internal Task CompleteStream(StreamId streamId, bool fireAndForgetDelivery)
{
var tasks = fireAndForgetDelivery ? null : new List<Task>();
foreach (GuidId subscriptionId in consumers.Keys)
{
var data = consumers[subscriptionId];
IStreamConsumerExtension remoteConsumer = data.Item1;
Task task = remoteConsumer.CompleteStream(subscriptionId);
if (fireAndForgetDelivery) task.Ignore();
else tasks.Add(task);
}
// If there's no subscriber, presumably we just drop the item on the floor
return fireAndForgetDelivery ? TaskDone.Done : Task.WhenAll(tasks);
}
internal Task ErrorInStream(StreamId streamId, Exception exc, bool fireAndForgetDelivery)
{
var tasks = fireAndForgetDelivery ? null : new List<Task>();
foreach (GuidId subscriptionId in consumers.Keys)
{
var data = consumers[subscriptionId];
IStreamConsumerExtension remoteConsumer = data.Item1;
Task task = remoteConsumer.ErrorInStream(subscriptionId, exc);
if (fireAndForgetDelivery) task.Ignore();
else tasks.Add(task);
}
// If there's no subscriber, presumably we just drop the item on the floor
return fireAndForgetDelivery ? TaskDone.Done : Task.WhenAll(tasks);
}
}
}
}
| |
// 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.
using System.IO;
using System.Text;
using System.Diagnostics;
namespace System.Net.Mime
{
/// <summary>
/// This stream performs in-place decoding of quoted-printable
/// encoded streams. Encoding requires copying into a separate
/// buffer as the data being encoded will most likely grow.
/// Encoding and decoding is done transparently to the caller.
/// </summary>
internal class QEncodedStream : DelegatedStream, IEncodableStream
{
//folding takes up 3 characters "\r\n "
private const int SizeOfFoldingCRLF = 3;
private static readonly byte[] s_hexDecodeMap = new byte[]
{
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 0
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 1
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 2
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,255,255,255,255,255,255, // 3
255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 4
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 5
255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 6
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 7
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 8
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 9
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // A
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // B
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // C
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // D
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // E
255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // F
};
//bytes that correspond to the hex char representations in ASCII (0-9, A-F)
private static readonly byte[] s_hexEncodeMap = new byte[] { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70 };
private ReadStateInfo _readState;
private WriteStateInfoBase _writeState;
internal QEncodedStream(WriteStateInfoBase wsi) : base(new MemoryStream())
{
_writeState = wsi;
}
private ReadStateInfo ReadState => _readState ?? (_readState = new ReadStateInfo());
internal WriteStateInfoBase WriteState => _writeState;
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
WriteAsyncResult result = new WriteAsyncResult(this, buffer, offset, count, callback, state);
result.Write();
return result;
}
public override void Close()
{
FlushInternal();
base.Close();
}
public unsafe int DecodeBytes(byte[] buffer, int offset, int count)
{
fixed (byte* pBuffer = buffer)
{
byte* start = pBuffer + offset;
byte* source = start;
byte* dest = start;
byte* end = start + count;
// if the last read ended in a partially decoded
// sequence, pick up where we left off.
if (ReadState.IsEscaped)
{
// this will be -1 if the previous read ended
// with an escape character.
if (ReadState.Byte == -1)
{
// if we only read one byte from the underlying
// stream, we'll need to save the byte and
// ask for more.
if (count == 1)
{
ReadState.Byte = *source;
return 0;
}
// '=\r\n' means a soft (aka. invisible) CRLF sequence...
if (source[0] != '\r' || source[1] != '\n')
{
byte b1 = s_hexDecodeMap[source[0]];
byte b2 = s_hexDecodeMap[source[1]];
if (b1 == 255)
throw new FormatException(SR.Format(SR.InvalidHexDigit, b1));
if (b2 == 255)
throw new FormatException(SR.Format(SR.InvalidHexDigit, b2));
*dest++ = (byte)((b1 << 4) + b2);
}
source += 2;
}
else
{
// '=\r\n' means a soft (aka. invisible) CRLF sequence...
if (ReadState.Byte != '\r' || *source != '\n')
{
byte b1 = s_hexDecodeMap[ReadState.Byte];
byte b2 = s_hexDecodeMap[*source];
if (b1 == 255)
throw new FormatException(SR.Format(SR.InvalidHexDigit, b1));
if (b2 == 255)
throw new FormatException(SR.Format(SR.InvalidHexDigit, b2));
*dest++ = (byte)((b1 << 4) + b2);
}
source++;
}
// reset state for next read.
ReadState.IsEscaped = false;
ReadState.Byte = -1;
}
// Here's where most of the decoding takes place.
// We'll loop around until we've inspected all the
// bytes read.
while (source < end)
{
// if the source is not an escape character, then
// just copy as-is.
if (*source != '=')
{
if (*source == '_')
{
*dest++ = (byte)' ';
source++;
}
else
{
*dest++ = *source++;
}
}
else
{
// determine where we are relative to the end
// of the data. If we don't have enough data to
// decode the escape sequence, save off what we
// have and continue the decoding in the next
// read. Otherwise, decode the data and copy
// into dest.
switch (end - source)
{
case 2:
ReadState.Byte = source[1];
goto case 1;
case 1:
ReadState.IsEscaped = true;
goto EndWhile;
default:
if (source[1] != '\r' || source[2] != '\n')
{
byte b1 = s_hexDecodeMap[source[1]];
byte b2 = s_hexDecodeMap[source[2]];
if (b1 == 255)
throw new FormatException(SR.Format(SR.InvalidHexDigit, b1));
if (b2 == 255)
throw new FormatException(SR.Format(SR.InvalidHexDigit, b2));
*dest++ = (byte)((b1 << 4) + b2);
}
source += 3;
break;
}
}
}
EndWhile:
return (int)(dest - start);
}
}
public int EncodeBytes(byte[] buffer, int offset, int count)
{
// Add Encoding header, if any. e.g. =?encoding?b?
_writeState.AppendHeader();
// Scan one character at a time looking for chars that need to be encoded.
int cur = offset;
for (; cur < count + offset; cur++)
{
if ( // Fold if we're before a whitespace and encoding another character would be too long
((WriteState.CurrentLineLength + SizeOfFoldingCRLF + WriteState.FooterLength >= WriteState.MaxLineLength)
&& (buffer[cur] == ' ' || buffer[cur] == '\t' || buffer[cur] == '\r' || buffer[cur] == '\n'))
// Or just adding the footer would be too long.
|| (WriteState.CurrentLineLength + _writeState.FooterLength >= WriteState.MaxLineLength)
)
{
WriteState.AppendCRLF(true);
}
// We don't need to worry about RFC 2821 4.5.2 (encoding first dot on a line),
// it is done by the underlying 7BitStream
//always encode CRLF
if (buffer[cur] == '\r' && cur + 1 < count + offset && buffer[cur + 1] == '\n')
{
cur++;
//the encoding for CRLF is =0D=0A
WriteState.Append((byte)'=', (byte)'0', (byte)'D', (byte)'=', (byte)'0', (byte)'A');
}
else if (buffer[cur] == ' ')
{
//spaces should be escaped as either '_' or '=20' and
//we have chosen '_' for parity with other email client
//behavior
WriteState.Append((byte)'_');
}
// RFC 2047 Section 5 part 3 also allows for !*+-/ but these arn't required in headers.
// Conservatively encode anything but letters or digits.
else if (IsAsciiLetterOrDigit((char)buffer[cur]))
{
// Just a regular printable ascii char.
WriteState.Append(buffer[cur]);
}
else
{
//append an = to indicate an encoded character
WriteState.Append((byte)'=');
//shift 4 to get the first four bytes only and look up the hex digit
WriteState.Append(s_hexEncodeMap[buffer[cur] >> 4]);
//clear the first four bytes to get the last four and look up the hex digit
WriteState.Append(s_hexEncodeMap[buffer[cur] & 0xF]);
}
}
WriteState.AppendFooter();
return cur - offset;
}
private static bool IsAsciiLetterOrDigit(char character) =>
IsAsciiLetter(character) || (character >= '0' && character <= '9');
private static bool IsAsciiLetter(char character) =>
(character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z');
public Stream GetStream() => this;
public string GetEncodedString() => Encoding.ASCII.GetString(WriteState.Buffer, 0, WriteState.Length);
public override void EndWrite(IAsyncResult asyncResult) => WriteAsyncResult.End(asyncResult);
public override void Flush()
{
FlushInternal();
base.Flush();
}
private void FlushInternal()
{
if (_writeState != null && _writeState.Length > 0)
{
base.Write(WriteState.Buffer, 0, WriteState.Length);
WriteState.Reset();
}
}
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
int written = 0;
for (;;)
{
written += EncodeBytes(buffer, offset + written, count - written);
if (written < count)
{
FlushInternal();
}
else
{
break;
}
}
}
private sealed class ReadStateInfo
{
internal bool IsEscaped { get; set; }
internal short Byte { get; set; } = -1;
}
private class WriteAsyncResult : LazyAsyncResult
{
private static readonly AsyncCallback s_onWrite = OnWrite;
private readonly QEncodedStream _parent;
private readonly byte[] _buffer;
private readonly int _offset;
private readonly int _count;
private int _written;
internal WriteAsyncResult(QEncodedStream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state)
: base(null, state, callback)
{
_parent = parent;
_buffer = buffer;
_offset = offset;
_count = count;
}
private void CompleteWrite(IAsyncResult result)
{
_parent.BaseStream.EndWrite(result);
_parent.WriteState.Reset();
}
internal static void End(IAsyncResult result)
{
WriteAsyncResult thisPtr = (WriteAsyncResult)result;
thisPtr.InternalWaitForCompletion();
Debug.Assert(thisPtr._written == thisPtr._count);
}
private static void OnWrite(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState;
try
{
thisPtr.CompleteWrite(result);
thisPtr.Write();
}
catch (Exception e)
{
thisPtr.InvokeCallback(e);
}
}
}
internal void Write()
{
for (;;)
{
_written += _parent.EncodeBytes(_buffer, _offset + _written, _count - _written);
if (_written < _count)
{
IAsyncResult result = _parent.BaseStream.BeginWrite(_parent.WriteState.Buffer, 0, _parent.WriteState.Length, s_onWrite, this);
if (!result.CompletedSynchronously)
{
break;
}
CompleteWrite(result);
}
else
{
InvokeCallback();
break;
}
}
}
}
}
}
|
Subsets and Splits