context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.Windows.Forms;
namespace BlueOnion
{
public class MonthCalendarEx : Control
{
private Size months = new Size(1, 1);
private DateTime today = DateTime.Today;
private DateTime currentDate = DateTime.Today;
private DateTime firstMonth = DateTime.Today;
private DayOfWeek firstDayOfWeek = DayOfWeek.Sunday;
private Hashtable boldedDays;
private Hashtable coloredDays;
private bool showToday = true;
private bool showWeekNumbers;
private bool showTodayCircle = true;
private Color titleForeColor = SystemColors.ActiveCaptionText;
private Color titleBackColor = SystemColors.ActiveCaption;
private Color weekdayForeColor = SystemColors.ActiveCaption;
private Color weekdayBackColor = SystemColors.ActiveCaptionText;
private Color weekdayBarColor = SystemColors.WindowText;
private Color weeknumberForeColor = SystemColors.ActiveCaption;
private Color weeknumberBackColor = SystemColors.ActiveCaptionText;
private Color trailingForeColor = SystemColors.GrayText;
private Color highlightDayTextColor = Color.DarkRed;
private Color gridlinesColor = SystemColors.GrayText;
private SizeF cellSize;
private readonly SizeF cellPadding = new Size(0, 0);
private SizeF monthPadding = new Size(1, 1);
private SizeF border = new SizeF(0, 0);
private RectangleF titleRectangle;
private RectangleF weekdaysRectangle;
private RectangleF weekNumbersRectangle;
private RectangleF daysRectangle;
private RectangleF todayRectangle;
private RectangleF displayTodayRectangle;
private struct CalendarArea
{
public DateTime date;
public RectangleF days;
public int dayOffset;
}
private CalendarArea[] CalendarAreas;
private RectangleF[] MonthNameAreas;
private RectangleF[] YearAreas;
private ArrowButton previousButton;
private ArrowButton nextButton;
private ContextMenu monthMenu;
private ContextMenu yearMenu;
private readonly Container components = null;
public event DateRangeEventHandler DateChanged;
private enum Trailing
{
None = 0,
First,
Last,
Both
}
private bool gridlines;
// ---------------------------------------------------------------------
public MonthCalendarEx()
{
InitializeComponent();
OnFontChanged(EventArgs.Empty);
Controls.Add(previousButton);
Controls.Add(nextButton);
SetStyle(ControlStyles.ResizeRedraw, true);
foreach (var month in
CultureInfo.CurrentCulture.DateTimeFormat.MonthNames)
{
if (month.Length > 0)
{
monthMenu.MenuItems.Add(month,
OnSelectMonth);
}
}
UpdateYearMenu();
}
// ---------------------------------------------------------------------
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
if (monthMenu != null)
{
monthMenu.Dispose();
monthMenu = null;
}
if (monthMenu != null)
{
yearMenu.Dispose();
yearMenu = null;
}
}
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.previousButton = new BlueOnion.ArrowButton();
this.nextButton = new BlueOnion.ArrowButton();
this.monthMenu = new System.Windows.Forms.ContextMenu();
this.yearMenu = new System.Windows.Forms.ContextMenu();
//
// previousButton
//
this.previousButton.BackColor = System.Drawing.SystemColors.Control;
this.previousButton.Direction = BlueOnion.ArrowButton.ArrowButtonDirection.Left;
this.previousButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.previousButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte) (0)));
this.previousButton.ForeColor = System.Drawing.Color.White;
this.previousButton.Location = new System.Drawing.Point(17, 17);
this.previousButton.Name = "previousButton";
this.previousButton.Size = new System.Drawing.Size(23, 23);
this.previousButton.TabIndex = 0;
this.previousButton.TabStop = false;
this.previousButton.Click += new System.EventHandler(this.PreviousButton_Click);
//
// nextButton
//
this.nextButton.Direction = BlueOnion.ArrowButton.ArrowButtonDirection.Right;
this.nextButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.nextButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte) (0)));
this.nextButton.ForeColor = System.Drawing.Color.White;
this.nextButton.Location = new System.Drawing.Point(148, 17);
this.nextButton.Name = "nextButton";
this.nextButton.Size = new System.Drawing.Size(23, 23);
this.nextButton.TabIndex = 0;
this.nextButton.TabStop = false;
this.nextButton.Click += new System.EventHandler(this.NextButton_Click);
}
#endregion
// ---------------------------------------------------------------------
protected override void OnClick(EventArgs e)
{
var point = PointToClient(MousePosition);
if (displayTodayRectangle.Contains(point))
{
GoToToday();
base.OnClick(e);
return;
}
foreach (var test in MonthNameAreas)
{
if (test.Contains(point))
{
monthMenu.Show(this, point);
base.OnClick(e);
return;
}
}
foreach (var test in YearAreas)
{
if (test.Contains(point))
{
yearMenu.Show(this, point);
base.OnClick(e);
return;
}
}
base.OnClick(e);
}
// ---------------------------------------------------------------------
protected void OnSelectMonth(object sender, EventArgs e)
{
firstMonth = new DateTime(
firstMonth.Year, ((MenuItem) sender).Index + 1, 1);
DateChange();
}
// ---------------------------------------------------------------------
protected void OnSelectYear(object sender, EventArgs e)
{
firstMonth = new DateTime(
firstMonth.Year + ((MenuItem) sender).Index - 5,
firstMonth.Month, firstMonth.Day);
DateChange();
}
// ---------------------------------------------------------------------
protected virtual void OnDateChanged(DateRangeEventArgs e)
{
if (DateChanged != null)
{
DateChanged(this, e);
}
}
// ---------------------------------------------------------------------
protected override void OnFontChanged(EventArgs e)
{
MonthSize();
months = Months();
BuildRegions();
PositionButtons();
base.OnFontChanged(e);
}
// ---------------------------------------------------------------------
protected override void OnMouseWheel(MouseEventArgs e)
{
base.OnMouseWheel(e);
firstMonth = firstMonth.AddMonths((e.Delta < 0) ? 1 : -1);
DateChange();
}
// ---------------------------------------------------------------------
protected override void OnMouseMove(MouseEventArgs e)
{
if (displayTodayRectangle.Contains(e.X, e.Y))
{
Cursor = Cursors.Hand;
base.OnMouseMove(e);
return;
}
foreach (var area in MonthNameAreas)
{
if (area.Contains(e.X, e.Y))
{
Cursor = Cursors.Hand;
base.OnMouseMove(e);
return;
}
}
foreach (var area in YearAreas)
{
if (area.Contains(e.X, e.Y))
{
Cursor = Cursors.Hand;
base.OnMouseMove(e);
return;
}
}
Cursor = Cursors.Default;
base.OnMouseMove(e);
}
// ---------------------------------------------------------------------
protected override void OnPaint(PaintEventArgs pe)
{
var month = FirstOfMonth(firstMonth);
var coordinates = border.ToPointF();
Brush textBrush = new SolidBrush(ForeColor);
Brush backBrush = new SolidBrush(BackColor);
Brush titleTextBrush = new SolidBrush(TitleForeColor);
Brush titleBackBrush = new SolidBrush(TitleBackColor);
Brush weekdayTextBrush = new SolidBrush(WeekdayForeColor);
Brush weekdayBackBrush = new SolidBrush(WeekdayBackColor);
Brush trailingTextBrush = new SolidBrush(TrailingForeColor);
Brush highlightDayTextBrush = new SolidBrush(HighlightDayTextColor);
Brush weeknumberTextBrush = new SolidBrush(WeeknumberForeColor);
Brush weeknumberBackBrush = new SolidBrush(WeeknumberBackColor);
var boldFont = new Font(Font, FontStyle.Bold);
var divider = new Pen(WeekdayBarColor);
var weekdays = AbbreviatedDayNames();
var cellMiddle = cellSize.Width*0.5F;
var cellMiddles = new float[weekdays.Length];
for (var w = 0; w < weekdays.Length; ++w)
{
cellMiddles[w] = cellMiddle;
cellMiddle += cellSize.Width;
}
for (var y = 0; y < months.Height; ++y)
{
for (var x = 0; x < months.Width; ++x)
{
var drawTrailing = Trailing.None;
if (months.Width*months.Height == 1)
{
drawTrailing = Trailing.Both;
}
else if (y == 0 && x == 0)
{
drawTrailing = Trailing.First;
}
else if (y == (months.Height - 1) &&
x == (months.Width - 1))
{
drawTrailing = Trailing.Last;
}
DrawMonth(
pe.Graphics,
month,
coordinates,
weekdays,
boldFont,
textBrush,
backBrush,
titleTextBrush,
titleBackBrush,
weekdayTextBrush,
weekdayBackBrush,
trailingTextBrush,
highlightDayTextBrush,
weeknumberTextBrush,
weeknumberBackBrush,
drawTrailing,
divider,
cellMiddles);
coordinates.X += SingleMonthSize.Width;
month = month.AddMonths(1);
}
coordinates.X = border.Width;
coordinates.Y += SingleMonthSize.Height;
}
// Draw today string at bottom of calendar
if (ShowToday)
{
displayTodayRectangle = todayRectangle;
displayTodayRectangle.Offset(0,
(months.Height - 1)*SingleMonthSize.Height);
var todayFormat = new StringFormat();
todayFormat.Alignment = StringAlignment.Center;
todayFormat.LineAlignment = StringAlignment.Center;
pe.Graphics.DrawString(
"Today: " + TodayDate.ToShortDateString(),
boldFont, textBrush, displayTodayRectangle, todayFormat);
}
else
{
displayTodayRectangle = RectangleF.Empty;
}
// Dispose of resources
textBrush.Dispose();
backBrush.Dispose();
titleTextBrush.Dispose();
titleBackBrush.Dispose();
weekdayTextBrush.Dispose();
weekdayBackBrush.Dispose();
trailingTextBrush.Dispose();
highlightDayTextBrush.Dispose();
weeknumberTextBrush.Dispose();
weeknumberBackBrush.Dispose();
boldFont.Dispose();
divider.Dispose();
base.OnPaint(pe);
}
// ---------------------------------------------------------------------
protected override void OnKeyDown(KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.PageUp:
if (e.Control && e.Shift == false && e.Alt == false)
{
firstMonth = firstMonth.AddYears(1);
}
else
{
firstMonth = firstMonth.AddMonths(1);
}
DateChange();
break;
case Keys.PageDown:
if (e.Control && e.Shift == false && e.Alt == false)
{
firstMonth = firstMonth.AddYears(-1);
}
else
{
firstMonth = firstMonth.AddMonths(-1);
}
DateChange();
break;
case Keys.Home:
GoToToday();
break;
default:
break;
}
base.OnKeyDown(e);
}
// ---------------------------------------------------------------------
protected override void OnSizeChanged(EventArgs e)
{
// Figure out if hittest regions need to be rebuilt
var months = Months();
if (this.months != months || CalendarAreas == null)
{
this.months = months;
PositionButtons();
BuildRegions();
}
base.OnSizeChanged(e);
}
// ---------------------------------------------------------------------
public DateTime[] BoldedDates { get; set; }
// ---------------------------------------------------------------------
public DateTime[] ColoredDates { get; set; }
// ---------------------------------------------------------------------
public DayOfWeek FirstDayOfWeek
{
get { return firstDayOfWeek; }
set
{
if (FirstDayOfWeek != value)
{
firstDayOfWeek = value;
BuildRegions();
Invalidate();
}
}
}
// ---------------------------------------------------------------------
public SelectionRange GetDisplayRange()
{
var start = FirstOfMonth(firstMonth);
var end = start.AddMonths(months.Width*months.Height).AddDays(-1);
return new SelectionRange(start, end);
}
// ---------------------------------------------------------------------
public bool Gridlines
{
get { return gridlines; }
set
{
gridlines = value;
Invalidate();
}
}
// ---------------------------------------------------------------------
public HitTestInfoEx HitTest(Point point)
{
var totalMonths = months.Width*months.Height;
for (var m = 0; m < totalMonths; ++m)
{
if (CalendarAreas[m].days.Contains(point))
{
var x = (int) ((point.X - CalendarAreas[m].days.Left)/
cellSize.Width) + 1;
var y = (int) ((point.Y - CalendarAreas[m].days.Top)/
cellSize.Height);
var time = CalendarAreas[m].date.AddDays
((x + (y*7)) - CalendarAreas[m].dayOffset - 1);
if (time.Month != CalendarAreas[m].date.Month)
{
time = DateTime.MinValue;
}
return new HitTestInfoEx(point, time);
}
}
return new HitTestInfoEx(point, DateTime.MinValue);
}
// ---------------------------------------------------------------------
public int MaxSelectionCount
{
get { return 1; }
set { }
}
// ---------------------------------------------------------------------
public void SetDate(DateTime date)
{
currentDate = date;
}
// ---------------------------------------------------------------------
public bool ShowToday
{
get { return showToday; }
set
{
showToday = value;
Invalidate();
}
}
// ---------------------------------------------------------------------
public bool ShowTodayCircle
{
get { return showTodayCircle; }
set
{
showTodayCircle = value;
Invalidate();
}
}
// ---------------------------------------------------------------------
public bool ShowWeekNumbers
{
get { return showWeekNumbers; }
set
{
if (showWeekNumbers != value)
{
showWeekNumbers = value;
MonthSize();
BuildRegions();
PositionButtons();
Invalidate();
}
}
}
// ---------------------------------------------------------------------
[Browsable(false)]
public Size SingleMonthSize { get; private set; }
// ---------------------------------------------------------------------
public virtual Color TitleForeColor
{
get { return titleForeColor; }
set
{
titleForeColor = value;
Invalidate();
}
}
// ---------------------------------------------------------------------
public virtual Color TitleBackColor
{
get { return titleBackColor; }
set
{
titleBackColor = value;
previousButton.BackColor = value;
nextButton.BackColor = value;
Invalidate();
}
}
// ---------------------------------------------------------------------
public virtual Color WeekdayForeColor
{
get { return weekdayForeColor; }
set
{
weekdayForeColor = value;
Invalidate();
}
}
// ---------------------------------------------------------------------
public virtual Color WeekdayBackColor
{
get { return weekdayBackColor; }
set
{
weekdayBackColor = value;
Invalidate();
}
}
// ---------------------------------------------------------------------
public virtual Color WeekdayBarColor
{
get { return weekdayBarColor; }
set
{
weekdayBarColor = value;
Invalidate();
}
}
// ---------------------------------------------------------------------
public virtual Color WeeknumberForeColor
{
get { return weeknumberForeColor; }
set
{
weeknumberForeColor = value;
Invalidate();
}
}
// ---------------------------------------------------------------------
public virtual Color WeeknumberBackColor
{
get { return weeknumberBackColor; }
set
{
weeknumberBackColor = value;
Invalidate();
}
}
// ---------------------------------------------------------------------
public virtual Color TrailingForeColor
{
get { return trailingForeColor; }
set
{
trailingForeColor = value;
Invalidate();
}
}
// ---------------------------------------------------------------------
public virtual Color HighlightDayTextColor
{
get { return highlightDayTextColor; }
set
{
highlightDayTextColor = value;
Invalidate();
}
}
// ---------------------------------------------------------------------
public virtual Color GridlinesColor
{
get { return gridlinesColor; }
set
{
gridlinesColor = value;
Invalidate();
}
}
// ---------------------------------------------------------------------
[Browsable(false)]
public DateTime TodayDate
{
get { return today; }
set
{
today = value;
Invalidate();
}
}
// ---------------------------------------------------------------------
[Browsable(false)]
public int TodayHeight
{
get { return (int) todayRectangle.Height; }
}
// ---------------------------------------------------------------------
public void UpdateBoldedDates()
{
boldedDays = new Hashtable();
if (BoldedDates != null)
{
foreach (var date in BoldedDates)
{
if (boldedDays.Contains(date.Date) == false)
{
boldedDays.Add(date.Date, null);
}
}
}
coloredDays = new Hashtable();
if (ColoredDates != null)
{
foreach (var date in ColoredDates)
{
if (coloredDays.Contains(date.Date) == false)
{
coloredDays.Add(date.Date, null);
}
}
}
}
// ---------------------------------------------------------------------
private static string[] AbbreviatedDayNames()
{
return CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedDayNames;
}
// ---------------------------------------------------------------------
private void BuildRegions()
{
var totalMonths = months.Width*months.Height;
CalendarAreas = new CalendarArea[totalMonths];
MonthNameAreas = new RectangleF[totalMonths];
YearAreas = new RectangleF[totalMonths];
var g = CreateGraphics();
var titleFormat = new StringFormat();
titleFormat.Alignment = StringAlignment.Center;
titleFormat.LineAlignment = StringAlignment.Center;
var days = daysRectangle;
var m = 0;
for (var y = 0; y < months.Height; ++y)
{
for (var x = 0; x < months.Width; ++x, ++m)
{
var date = FirstOfMonth(firstMonth.AddMonths(m));
CalendarAreas[m].date = date;
CalendarAreas[m].dayOffset =
((int) CalendarAreas[m].date.DayOfWeek + 7 -
(int) FirstDayOfWeek)%7;
float xMonth = x*SingleMonthSize.Width;
float yMonth = y*SingleMonthSize.Height;
CalendarAreas[m].days = days;
CalendarAreas[m].days.Offset(xMonth, yMonth);
var titleSize = g.MeasureString(
date.ToString("MMMM, yyyy", CultureInfo.CurrentCulture),
Font, titleRectangle.Size, titleFormat);
var monthSize = g.MeasureString(
date.ToString("MMMM, ", CultureInfo.CurrentCulture),
Font);
MonthNameAreas[m] = titleRectangle;
MonthNameAreas[m].Inflate(
(titleSize.Width - titleRectangle.Width)/2,
(titleSize.Height - titleRectangle.Height)/2);
MonthNameAreas[m].Width = monthSize.Width;
MonthNameAreas[m].Offset(xMonth, yMonth);
YearAreas[m] = MonthNameAreas[m];
YearAreas[m].X += monthSize.Width;
YearAreas[m].Width = titleSize.Width - monthSize.Width;
}
}
g.Dispose();
}
// ---------------------------------------------------------------------
private void DrawMonth(
Graphics graphics,
DateTime month,
PointF start,
string[] weekdays,
Font boldFont,
Brush textBrush,
Brush backBrush,
Brush titleTextBrush,
Brush titleBackBrush,
Brush weekdayTextBrush,
Brush weekdayBackBrush,
Brush trailingTextBrush,
Brush highlightDayTextBrush,
Brush weeknumberTextBrush,
Brush weeknumberBackBrush,
Trailing drawTrailing,
Pen divider,
float[] cellMiddles)
{
DrawTitle(
graphics,
month.ToString("MMMM, yyyy", CultureInfo.CurrentCulture),
start,
titleRectangle,
boldFont,
titleTextBrush,
titleBackBrush);
DrawWeekNames(
graphics,
weekdays,
start,
weekdaysRectangle,
Font,
weekdayTextBrush,
weekdayBackBrush,
divider,
cellMiddles);
DrawDays(
graphics,
month,
start,
daysRectangle,
Font,
boldFont,
textBrush,
trailingTextBrush,
highlightDayTextBrush,
drawTrailing,
HighlightDayTextColor,
cellMiddles);
if (ShowWeekNumbers)
{
DrawWeekNumbers(
graphics,
month,
start,
weekNumbersRectangle,
Font,
weeknumberTextBrush,
weeknumberBackBrush,
divider);
}
}
// ---------------------------------------------------------------------
private void DrawTitle(Graphics graphics, string title, PointF start,
RectangleF rectangle, Font font, Brush textBrush, Brush backBrush)
{
rectangle.Offset(start);
graphics.FillRectangle(backBrush, rectangle);
var titleFormat = new StringFormat();
titleFormat.Alignment = StringAlignment.Center;
titleFormat.LineAlignment = StringAlignment.Center;
graphics.DrawString(title, font, textBrush, rectangle,
titleFormat);
}
// ---------------------------------------------------------------------
private void DrawWeekNames(
Graphics graphics,
string[] weekdays,
PointF start,
RectangleF rectangle,
Font font,
Brush textBrush,
Brush backBrush,
Pen divider,
float[] cellMiddles)
{
rectangle.Offset(start);
graphics.FillRectangle(backBrush, rectangle);
var weekdayFormat = new StringFormat();
weekdayFormat.Alignment = StringAlignment.Center;
for (var w = 0; w < weekdays.Length; ++w)
{
var dayOffset = (w + (int) FirstDayOfWeek)%7;
graphics.DrawString(weekdays[dayOffset], font, textBrush,
rectangle.X + cellMiddles[w], rectangle.Top, weekdayFormat);
}
var margin = cellSize.Width*0.14F;
var verticalOffset = rectangle.Bottom - 2;
graphics.DrawLine(divider, rectangle.X + margin,
verticalOffset, rectangle.Right - margin, verticalOffset);
}
// ---------------------------------------------------------------------
private void DrawDays(
Graphics graphics,
DateTime month,
PointF start,
RectangleF rectangle,
Font font,
Font boldFont,
Brush textBrush,
Brush trailingTextBrush,
Brush highlightDayTextBrush,
Trailing drawTrailing,
Color todayColor,
float[] cellMiddles)
{
rectangle.Offset(start);
var weekdayFormat = new StringFormat();
weekdayFormat.Alignment = StringAlignment.Center;
if (gridlines)
{
DrawGridLines(graphics, rectangle);
}
var daysInMonth = GetDaysInMonth(month.Year, month.Month);
var firstDayOfMonth = new DateTime(month.Year, month.Month, 1);
var verticalOffset = rectangle.Y;
var weeksDrawn = 0;
var dayOffset =
((int) firstDayOfMonth.DayOfWeek + 7 - (int) FirstDayOfWeek)%7;
if (drawTrailing == Trailing.First || drawTrailing == Trailing.Both)
{
// Gray days...
var previousMonth = month.AddMonths(-1);
var daysInPreviousMonth =
GetDaysInMonth(previousMonth.Year, previousMonth.Month);
for (var day = daysInPreviousMonth - dayOffset + 1; day <= daysInPreviousMonth; ++day)
{
graphics.DrawString(day.ToString(), font, trailingTextBrush,
rectangle.X + cellMiddles[dayOffset - 1 - (daysInPreviousMonth - day)],
verticalOffset, weekdayFormat);
}
}
// Regular days...
for (var day = 1; day <= daysInMonth; ++day)
{
var date = firstDayOfMonth.AddDays(day - 1);
if (showTodayCircle && date.Date == TodayDate.Date)
{
var width = cellSize.Width;
var todayPen = new Pen(todayColor);
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.DrawEllipse(todayPen,
rectangle.X + cellMiddles[dayOffset] - (width/2),
verticalOffset - 1,
width,
cellSize.Height);
todayPen.Dispose();
graphics.SmoothingMode = SmoothingMode.None;
}
var dayFont = font;
if (BoldedDates != null && BoldedDates != null &&
boldedDays.Contains(date))
{
dayFont = boldFont;
}
var dayBrush = textBrush;
if (ColoredDates != null && coloredDays != null &&
coloredDays.Contains(date))
{
dayBrush = highlightDayTextBrush;
}
graphics.DrawString(day.ToString(), dayFont, dayBrush,
rectangle.X + cellMiddles[dayOffset],
verticalOffset, weekdayFormat);
dayOffset += 1;
dayOffset %= 7;
if (dayOffset == 0)
{
verticalOffset += cellSize.Height;
weeksDrawn += 1;
}
}
// Gray days again...
if (drawTrailing == Trailing.Last || drawTrailing == Trailing.Both)
{
var nextMonth = month.AddMonths(-1);
var daysInNextMonth =
GetDaysInMonth(nextMonth.Year, nextMonth.Month);
for (var day = 1; day <= daysInNextMonth; ++day)
{
graphics.DrawString(day.ToString(), font, trailingTextBrush,
rectangle.X + cellMiddles[dayOffset],
verticalOffset, weekdayFormat);
dayOffset += 1;
dayOffset %= 7;
if (dayOffset == 0)
{
verticalOffset += cellSize.Height;
weeksDrawn += 1;
}
if (weeksDrawn > 5)
{
break;
}
}
}
}
// ---------------------------------------------------------------------
private void DrawGridLines(Graphics graphics, RectangleF rectangle)
{
var pen = new Pen(Color.Gray);
var offset = rectangle.Y + cellSize.Height - 1;
for (var i = 0; i < 5; ++i)
{
graphics.DrawLine(pen, rectangle.Left, offset,
rectangle.Right, offset);
offset += cellSize.Height;
}
offset = rectangle.Left + cellSize.Width - 1;
for (var i = 0; i < 6; ++i)
{
graphics.DrawLine(pen, offset, rectangle.Top,
offset, rectangle.Bottom - 1);
offset += cellSize.Width;
}
}
// ---------------------------------------------------------------------
private void DrawWeekNumbers(
Graphics graphics,
DateTime month,
PointF start,
RectangleF rectangle,
Font font,
Brush textBrush,
Brush backBrush,
Pen divider)
{
rectangle.Offset(start);
graphics.FillRectangle(backBrush, rectangle);
var weekdayFormat = new StringFormat();
weekdayFormat.Alignment = StringAlignment.Center;
var x = rectangle.X + rectangle.Width/2;
var y = rectangle.Top;
var firstDayOfMonth = new DateTime(month.Year, month.Month, 1);
var daysInMonth = GetDaysInMonth(month.Year, month.Month);
var dayOffset = ((int) firstDayOfMonth.DayOfWeek + 7 -
(int) FirstDayOfWeek)%7;
var date = firstDayOfMonth;
var weeks = (daysInMonth + dayOffset + 7)/7;
var ci = new CultureInfo("en-US");
for (var w = 0; w < weeks; ++w)
{
var weekOfYear = ci.Calendar.GetWeekOfYear(date,
CalendarWeekRule.FirstFourDayWeek,
FirstDayOfWeek);
graphics.DrawString(
weekOfYear.ToString(CultureInfo.CurrentCulture),
font, textBrush, x, y, weekdayFormat);
date = date.AddDays(7);
y += cellSize.Height;
}
graphics.DrawLine(divider,
rectangle.Right,
rectangle.Top,
rectangle.Right,
rectangle.Top + (weeks*cellSize.Height));
}
// ---------------------------------------------------------------------
private void MonthSize()
{
var g = CreateGraphics();
var point = new PointF(0, 0);
var stringFormat = StringFormat.GenericTypographic;
stringFormat.FormatFlags |= StringFormatFlags.MeasureTrailingSpaces;
// Width determined by longest label or number
cellSize = g.MeasureString("00 ", Font, point,
StringFormat.GenericTypographic);
foreach (var day in AbbreviatedDayNames())
{
var measured = g.MeasureString(day + " ", Font, point,
stringFormat);
if (measured.Width > cellSize.Width)
{
cellSize = measured;
}
}
cellSize.Height = Font.GetHeight(g);
cellSize.Height *= 1.2F;
g.Dispose();
cellSize += cellPadding;
var size = new SizeF(cellSize.Width*7, cellSize.Height*9.7F);
size += monthPadding;
size += monthPadding;
float weekNumbers = 0;
if (ShowWeekNumbers)
{
weekNumbers = cellSize.Width;
size.Width += weekNumbers;
}
// titleRectangle
titleRectangle = new RectangleF(
monthPadding.Width,
monthPadding.Height,
size.Width - (monthPadding.Width*2),
cellSize.Height*1.5F);
// weekdays
weekdaysRectangle = new RectangleF(
weekNumbers + monthPadding.Width,
(1.6f*cellSize.Height) + monthPadding.Height,
titleRectangle.Width - weekNumbers - monthPadding.Width,
cellSize.Height);
// days
daysRectangle = new RectangleF(
weekNumbers + monthPadding.Width,
(2.6f*cellSize.Height) + monthPadding.Height,
titleRectangle.Width, cellSize.Height*6);
// weeknumbers
weekNumbersRectangle = new RectangleF(
monthPadding.Width,
daysRectangle.Top,
cellSize.Width - 2, daysRectangle.Height);
// today
todayRectangle = new RectangleF(
monthPadding.Width,
daysRectangle.Bottom,
titleRectangle.Width,
cellSize.Height);
// correct for truncation
size += new SizeF(0.5F, 0.5F);
SingleMonthSize = size.ToSize();
}
// ---------------------------------------------------------------------
public static int GetDaysInMonth(int year, int month)
{
var calendar =
CultureInfo.CurrentCulture.DateTimeFormat.Calendar;
return calendar.GetDaysInMonth(year, month);
}
// ---------------------------------------------------------------------
private static DateTime FirstOfMonth(DateTime date)
{
return new DateTime(date.Year, date.Month, 1);
}
// ---------------------------------------------------------------------
private void PreviousButton_Click(object sender, EventArgs e)
{
firstMonth = firstMonth.AddMonths(-1);
DateChange();
Focus();
}
// ---------------------------------------------------------------------
private void NextButton_Click(object sender, EventArgs e)
{
firstMonth = firstMonth.AddMonths(1);
DateChange();
Focus();
}
// ---------------------------------------------------------------------
private void DateChange()
{
BuildRegions();
Invalidate();
UpdateYearMenu();
var e = new DateRangeEventArgs(firstMonth,
firstMonth);
OnDateChanged(e);
}
// ---------------------------------------------------------------------
private void UpdateYearMenu()
{
yearMenu.MenuItems.Clear();
for (var year = firstMonth.Year - 5;
year < firstMonth.Year + 5;
++year)
{
yearMenu.MenuItems.Add(
year.ToString(CultureInfo.CurrentCulture),
OnSelectYear);
}
}
// ---------------------------------------------------------------------
private Size Months()
{
var border = this.border.ToSize().Width;
var width = Math.Max(1, (Width + border)/
SingleMonthSize.Width);
return new Size(width,
Math.Max(1, Height/SingleMonthSize.Height));
}
// ---------------------------------------------------------------------
private void PositionButtons()
{
var width = (int) cellSize.Width;
var height = (int) cellSize.Height;
previousButton.Size = new Size(width/2, height);
nextButton.Size = previousButton.Size;
var margin = (int) (cellSize.Width*.20F);
var titleMiddle = titleRectangle.Height/2.0F;
var y = (int) (titleMiddle - (height*0.5F) + 0.5F);
previousButton.Location = new Point(margin, y);
nextButton.Location = new Point(
SingleMonthSize.Width*months.Width -
nextButton.Size.Width - margin, y);
previousButton.Font = Font;
nextButton.Font = Font;
}
// ---------------------------------------------------------------------
public void GoToToday()
{
firstMonth = DateTime.Today;
DateChange();
}
// ---------------------------------------------------------------------
public void GoToDate(DateTime date)
{
firstMonth = date;
DateChange();
}
// ---------------------------------------------------------------------
private static GraphicsPath RoundRect(float x, float y, float w, float h, float r)
{
var gp = new GraphicsPath();
var x2 = x + w;
var y2 = y + h;
PointF[] points =
{
new PointF(x + r, y),
new PointF(x2 - r, y),
new PointF(x2 - r, y + r),
new PointF(x2, y + r),
new PointF(x2, y2 - r),
new PointF(x2 - r, y2 - r),
new PointF(x2 - r, y2),
new PointF(x + r, y2),
new PointF(x + r, y2 - r),
new PointF(x, y2 - r),
new PointF(x, y + r),
new PointF(x + r, y + r),
new PointF(x + r, y)
};
gp.AddLines(points);
gp.CloseFigure();
return gp;
}
// =====================================================================
public class HitTestInfoEx
{
// -----------------------------------------------------------------
public HitTestInfoEx(Point test, DateTime date)
{
Point = test;
Time = date;
}
// -----------------------------------------------------------------
public DateTime Time { get; set; }
// -----------------------------------------------------------------
public Point Point { 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.
#if TESTHOOK
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Globalization;
namespace System.DirectoryServices.AccountManagement
{
public class TestHook
{
static public void TestADStoreKeys()
{
// GUID-based ADStoreKeys
Guid adGuid1 = Guid.NewGuid();
Guid adGuid2 = Guid.NewGuid();
ADStoreKey key1a = new ADStoreKey(adGuid1);
ADStoreKey key1b = new ADStoreKey(adGuid1);
ADStoreKey key2 = new ADStoreKey(adGuid2);
Debug.Assert(key1a.Equals(key1b));
Debug.Assert(!key1a.Equals(key2));
Debug.Assert(key1a.GetHashCode() == key1b.GetHashCode());
Debug.Assert(key1a.GetHashCode() != key2.GetHashCode());
// SID-based ADStoreKeys
string mach1 = "machine1";
string mach1a = "machine1";
string mach2 = "machine2";
byte[] sid1a = new byte[]{0x1, 0x2, 0x3};
byte[] sid1b = new byte[]{0x1, 0x2, 0x3};
byte[] sid2 = new byte[]{0x10, 0x20, 0x30};
ADStoreKey key3a = new ADStoreKey(mach1, sid1a);
ADStoreKey key3b = new ADStoreKey(mach1, sid1a);
ADStoreKey key3c = new ADStoreKey(mach1a, sid1b);
ADStoreKey key4 = new ADStoreKey(mach2, sid2);
ADStoreKey key5 = new ADStoreKey(mach1, sid2);
Debug.Assert(key3a.Equals(key3b));
Debug.Assert(key3a.Equals(key3c));
Debug.Assert(!key3a.Equals(key4));
Debug.Assert(!key3a.Equals(key5));
Debug.Assert(!key3a.Equals(key1a));
Debug.Assert(!key1a.Equals(key3a));
Debug.Assert(key3a.GetHashCode() != key4.GetHashCode());
// Shouldn't matter, since SAMStoreKey should make a copy of the byte[] sid
sid1b[1] = 0xf;
Debug.Assert(key3a.Equals(key3b));
Debug.Assert(key3a.Equals(key3c));
}
static public void TestSAMStoreKeys()
{
string mach1 = "machine1";
string mach1a = "machine1";
string mach2 = "machine2";
byte[] sid1a = new byte[]{0x1, 0x2, 0x3};
byte[] sid1b = new byte[]{0x1, 0x2, 0x3};
byte[] sid2 = new byte[]{0x10, 0x20, 0x30};
SAMStoreKey key1a = new SAMStoreKey(mach1, sid1a);
SAMStoreKey key1b = new SAMStoreKey(mach1, sid1a);
SAMStoreKey key1c = new SAMStoreKey(mach1a, sid1b);
SAMStoreKey key2 = new SAMStoreKey(mach2, sid2);
SAMStoreKey key3 = new SAMStoreKey(mach1, sid2);
Debug.Assert(key1a.Equals(key1b));
Debug.Assert(key1a.Equals(key1c));
Debug.Assert(!key1a.Equals(key2));
Debug.Assert(!key1a.Equals(key3));
Debug.Assert(key1a.GetHashCode() != key2.GetHashCode());
// Shouldn't matter, since SAMStoreKey should make a copy of the byte[] sid
sid1b[1] = 0xf;
Debug.Assert(key1a.Equals(key1b));
Debug.Assert(key1a.Equals(key1c));
}
//
// ValueCollection
//
static public PrincipalValueCollection<T> ValueCollectionConstruct<T>()
{
return new PrincipalValueCollection<T>();
}
static public void ValueCollectionLoad<T>(PrincipalValueCollection<T> trackList, List<T> initial)
{
trackList.Load(initial);
}
static public List<T> ValueCollectionInserted<T>(PrincipalValueCollection<T> trackList)
{
return trackList.Inserted;
}
static public List<T> ValueCollectionRemoved<T>(PrincipalValueCollection<T> trackList)
{
return trackList.Removed;
}
static public List<T> ValueCollectionChangedValues<T>(PrincipalValueCollection<T> trackList, out List<T> rightOut)
{
// We'd like to just return the List<Pair<T,T>>, but Pair<T,T> isn't a public class
List<T> left = new List<T>();
List<T> right = new List<T>();
List<Pair<T,T>> pairList = trackList.ChangedValues;
foreach (Pair<T,T> pair in pairList)
{
left.Add(pair.Left);
right.Add(pair.Right);
}
rightOut = right;
return left;
}
static public bool ValueCollectionChanged<T>(PrincipalValueCollection<T> trackList)
{
return trackList.Changed;
}
static public void ValueCollectionResetTracking<T>(PrincipalValueCollection<T> trackList)
{
trackList.ResetTracking();
}
//
// IdentityClaimCollection
//
static public IdentityClaimCollection ICCConstruct()
{
Group g = new Group();
return new IdentityClaimCollection(g);
}
static public IdentityClaimCollection ICCConstruct2()
{
Group g = new Group();
g.Context = PrincipalContext.Test;
return new IdentityClaimCollection(g);
}
static public IdentityClaimCollection ICCConstructAlt()
{
Group g = new Group();
g.Context = PrincipalContext.TestAltValidation;
return new IdentityClaimCollection(g);
}
static public IdentityClaimCollection ICCConstructNoTimeLimited()
{
Group g = new Group();
g.Context = PrincipalContext.TestNoTimeLimited;
return new IdentityClaimCollection(g);
}
static public void ICCLoad(IdentityClaimCollection trackList, List<IdentityClaim> initial)
{
trackList.Load(initial);
}
static public List<IdentityClaim> ICCInserted(IdentityClaimCollection trackList)
{
return trackList.Inserted;
}
static public List<IdentityClaim> ICCRemoved(IdentityClaimCollection trackList)
{
return trackList.Removed;
}
static public List<IdentityClaim> ICCChangedValues(IdentityClaimCollection trackList, out List<IdentityClaim> rightOut)
{
// We'd like to just return the List<Pair<T,T>>, but Pair<T,T> isn't a public class
List<IdentityClaim> left = new List<IdentityClaim>();
List<IdentityClaim> right = new List<IdentityClaim>();
List<Pair<IdentityClaim,IdentityClaim>> pairList = trackList.ChangedValues;
foreach (Pair<IdentityClaim,IdentityClaim> pair in pairList)
{
left.Add(pair.Left);
right.Add(pair.Right);
}
rightOut = right;
return left;
}
static public bool ICCChanged(IdentityClaimCollection trackList)
{
return trackList.Changed;
}
static public void ICCResetTracking(IdentityClaimCollection trackList)
{
trackList.ResetTracking();
}
//
// PrincipalCollection
//
static public Group MakeAGroup(string s)
{
Group g = new Group(PrincipalContext.Test);
g.DisplayName = s;
g.Key = new TestStoreKey(s);
return g;
}
static public PrincipalCollection MakePrincipalCollection()
{
BookmarkableResultSet rs = PrincipalContext.Test.QueryCtx.GetGroupMembership(null, false);
PrincipalCollection mc = new PrincipalCollection(rs, new Group());
return mc;
}
static public List<Principal> MCInserted(PrincipalCollection trackList)
{
return trackList.Inserted;
}
static public List<Principal> MCRemoved(PrincipalCollection trackList)
{
return trackList.Removed;
}
static public bool MCChanged(PrincipalCollection trackList)
{
return trackList.Changed;
}
static public void MCResetTracking(PrincipalCollection trackList)
{
trackList.ResetTracking();
}
//
// AuthenticablePrincipal
//
static public User APGetNoninsertedAP()
{
User u = new User(PrincipalContext.Test);
u.unpersisted = false;
return u;
}
static public void APInitNested(AuthenticablePrincipal ap)
{
ap.LoadValueIntoProperty(PropertyNames.PwdInfoCannotChangePassword, true);
ap.LoadValueIntoProperty(PropertyNames.AcctInfoBadLogonCount, 3);
}
static public void APLoadValue(AuthenticablePrincipal ap, string name, object value)
{
ap.LoadValueIntoProperty(name, value);
}
static public bool APGetChangeStatus(AuthenticablePrincipal ap, string name)
{
return ap.GetChangeStatusForProperty(name);
}
static public object APGetValue(AuthenticablePrincipal ap, string name)
{
return ap.GetValueForProperty(name);
}
static public void APResetChanges(AuthenticablePrincipal ap)
{
ap.ResetAllChangeStatus();
}
//
// PasswordInfo
//
static public PasswordInfo ExtractPI(AuthenticablePrincipal ap)
{
Type t = typeof(AuthenticablePrincipal);
return (PasswordInfo) t.InvokeMember(
"PasswordInfo",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty,
null,
ap,
new object[]{},
CultureInfo.InvariantCulture);
}
static public void PILoadValue(PasswordInfo pi, string name, object value)
{
pi.LoadValueIntoProperty(name, value);
}
static public bool PIGetChangeStatus(PasswordInfo pi, string name)
{
return pi.GetChangeStatusForProperty(name);
}
static public object PIGetValue(PasswordInfo pi, string name)
{
return pi.GetValueForProperty(name);
}
static public void PIResetChanges(PasswordInfo pi)
{
pi.ResetAllChangeStatus();
}
//
// AccountInfo
//
static public AccountInfo ExtractAI(AuthenticablePrincipal ap)
{
Type t = typeof(AuthenticablePrincipal);
return (AccountInfo) t.InvokeMember(
"AccountInfo",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty,
null,
ap,
new object[]{},
CultureInfo.InvariantCulture);
}
static public void AILoadValue(AccountInfo ai, string name, object value)
{
ai.LoadValueIntoProperty(name, value);
}
static public bool AIGetChangeStatus(AccountInfo ai, string name)
{
return ai.GetChangeStatusForProperty(name);
}
static public object AIGetValue(AccountInfo ai, string name)
{
return ai.GetValueForProperty(name);
}
static public void AIResetChanges(AccountInfo ai)
{
ai.ResetAllChangeStatus();
}
//
// User
//
static public void UserLoadValue(User u, string name, object value)
{
u.LoadValueIntoProperty(name, value);
}
static public bool UserGetChangeStatus(User u, string name)
{
return u.GetChangeStatusForProperty(name);
}
static public object UserGetValue(User u, string name)
{
return u.GetValueForProperty(name);
}
static public void UserResetChanges(User u)
{
u.ResetAllChangeStatus();
}
static public Group GroupGetNonInsertedGroup()
{
Group g = new Group(PrincipalContext.Test);
g.unpersisted = false;
return g;
}
//
// Computer
//
static public void ComputerLoadValue(Computer computer, string name, object value)
{
computer.LoadValueIntoProperty(name, value);
}
static public bool ComputerGetChangeStatus(Computer computer, string name)
{
return computer.GetChangeStatusForProperty(name);
}
static public object ComputerGetValue(Computer computer, string name)
{
return computer.GetValueForProperty(name);
}
static public void ComputerResetChanges(Computer computer)
{
computer.ResetAllChangeStatus();
}
//
// QBE
//
static public void BuildQbeFilter(Principal p)
{
PrincipalContext ctx = PrincipalContext.Test;
((TestStoreCtx)ctx.QueryCtx).CallBuildQbeFilterDescription(p);
}
}
}
#endif // TESTHOOK
| |
// 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.
/*****************************************************************************************************
Rules for Multiple Nested Parent, enforce following constraints
1) At all times, only 1(ONE) FK can be NON-Null in a row.
2) NULL FK values are not associated with PARENT(x), even if if PK is NULL in Parent
3) Enforce <rule 1> when
a) Any FK value is changed
b) A relation created that result in Multiple Nested Child
WriteXml
1) WriteXml will throw if <rule 1> is violated
2) if NON-Null FK has parentRow (boolean check) print as Nested, else it will get written as normal row
additional notes:
We decided to enforce the rule 1 just if Xml being persisted
******************************************************************************************************/
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Data.Common;
using System.Collections.Generic;
using System.Threading;
namespace System.Data
{
[DefaultProperty(nameof(RelationName))]
[TypeConverter(typeof(RelationshipConverter))]
public class DataRelation
{
// properties
private DataSet _dataSet = null;
internal PropertyCollection _extendedProperties = null;
internal string _relationName = string.Empty;
// state
private DataKey _childKey;
private DataKey _parentKey;
private UniqueConstraint _parentKeyConstraint = null;
private ForeignKeyConstraint _childKeyConstraint = null;
// Design time serialization
internal string[] _parentColumnNames = null;
internal string[] _childColumnNames = null;
internal string _parentTableName = null;
internal string _childTableName = null;
internal string _parentTableNamespace = null;
internal string _childTableNamespace = null;
/// <summary>
/// this stores whether the child element appears beneath the parent in the XML persised files.
/// </summary>
internal bool _nested = false;
/// <summary>
/// this stores whether the relationship should make sure that KeyConstraints and ForeignKeyConstraints
/// exist when added to the ConstraintsCollections of the table.
/// </summary>
internal bool _createConstraints;
private bool _checkMultipleNested = true;
private static int s_objectTypeCount; // Bid counter
private readonly int _objectID = Interlocked.Increment(ref s_objectTypeCount);
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.DataRelation'/> class using the specified name,
/// parent, and child columns.
/// </summary>
public DataRelation(string relationName, DataColumn parentColumn, DataColumn childColumn) :
this(relationName, parentColumn, childColumn, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.DataRelation'/> class using the specified name, parent, and child columns, and
/// value to create constraints.
/// </summary>
public DataRelation(string relationName, DataColumn parentColumn, DataColumn childColumn, bool createConstraints)
{
DataCommonEventSource.Log.Trace("<ds.DataRelation.DataRelation|API> {0}, relationName='{1}', parentColumn={2}, childColumn={3}, createConstraints={4}",
ObjectID, relationName, (parentColumn != null) ? parentColumn.ObjectID : 0, (childColumn != null) ? childColumn.ObjectID : 0,
createConstraints);
DataColumn[] parentColumns = new DataColumn[1];
parentColumns[0] = parentColumn;
DataColumn[] childColumns = new DataColumn[1];
childColumns[0] = childColumn;
Create(relationName, parentColumns, childColumns, createConstraints);
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.DataRelation'/> class using the specified name
/// and matched arrays of parent and child columns.
/// </summary>
public DataRelation(string relationName, DataColumn[] parentColumns, DataColumn[] childColumns) :
this(relationName, parentColumns, childColumns, true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref='System.Data.DataRelation'/> class using the specified name, matched arrays of parent
/// and child columns, and value to create constraints.
/// </summary>
public DataRelation(string relationName, DataColumn[] parentColumns, DataColumn[] childColumns, bool createConstraints)
{
Create(relationName, parentColumns, childColumns, createConstraints);
}
[Browsable(false)] // design-time ctor
public DataRelation(string relationName, string parentTableName, string childTableName, string[] parentColumnNames, string[] childColumnNames, bool nested)
{
_relationName = relationName;
_parentColumnNames = parentColumnNames;
_childColumnNames = childColumnNames;
_parentTableName = parentTableName;
_childTableName = childTableName;
_nested = nested;
}
[Browsable(false)] // design-time ctor
public DataRelation(string relationName, string parentTableName, string parentTableNamespace, string childTableName, string childTableNamespace, string[] parentColumnNames, string[] childColumnNames, bool nested)
{
_relationName = relationName;
_parentColumnNames = parentColumnNames;
_childColumnNames = childColumnNames;
_parentTableName = parentTableName;
_childTableName = childTableName;
_parentTableNamespace = parentTableNamespace;
_childTableNamespace = childTableNamespace;
_nested = nested;
}
/// <summary>
/// Gets the child columns of this relation.
/// </summary>
public virtual DataColumn[] ChildColumns
{
get
{
CheckStateForProperty();
return _childKey.ToArray();
}
}
internal DataColumn[] ChildColumnsReference
{
get
{
CheckStateForProperty();
return _childKey.ColumnsReference;
}
}
/// <summary>
/// The internal Key object for the child table.
/// </summary>
internal DataKey ChildKey
{
get
{
CheckStateForProperty();
return _childKey;
}
}
/// <summary>
/// Gets the child table of this relation.
/// </summary>
public virtual DataTable ChildTable
{
get
{
CheckStateForProperty();
return _childKey.Table;
}
}
/// <summary>
/// Gets the <see cref='System.Data.DataSet'/> to which the relations' collection belongs to.
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
public virtual DataSet DataSet
{
get
{
CheckStateForProperty();
return _dataSet;
}
}
internal string[] ParentColumnNames => _parentKey.GetColumnNames();
internal string[] ChildColumnNames => _childKey.GetColumnNames();
private static bool IsKeyNull(object[] values)
{
for (int i = 0; i < values.Length; i++)
{
if (!DataStorage.IsObjectNull(values[i]))
{
return false;
}
}
return true;
}
/// <summary>
/// Gets the child rows for the parent row across the relation using the version given
/// </summary>
internal static DataRow[] GetChildRows(DataKey parentKey, DataKey childKey, DataRow parentRow, DataRowVersion version)
{
object[] values = parentRow.GetKeyValues(parentKey, version);
if (IsKeyNull(values))
{
return childKey.Table.NewRowArray(0);
}
Index index = childKey.GetSortIndex((version == DataRowVersion.Original) ? DataViewRowState.OriginalRows : DataViewRowState.CurrentRows);
return index.GetRows(values);
}
/// <summary>
/// Gets the parent rows for the given child row across the relation using the version given
/// </summary>
internal static DataRow[] GetParentRows(DataKey parentKey, DataKey childKey, DataRow childRow, DataRowVersion version)
{
object[] values = childRow.GetKeyValues(childKey, version);
if (IsKeyNull(values))
{
return parentKey.Table.NewRowArray(0);
}
Index index = parentKey.GetSortIndex((version == DataRowVersion.Original) ? DataViewRowState.OriginalRows : DataViewRowState.CurrentRows);
return index.GetRows(values);
}
internal static DataRow GetParentRow(DataKey parentKey, DataKey childKey, DataRow childRow, DataRowVersion version)
{
if (!childRow.HasVersion((version == DataRowVersion.Original) ? DataRowVersion.Original : DataRowVersion.Current))
{
if (childRow._tempRecord == -1)
{
return null;
}
}
object[] values = childRow.GetKeyValues(childKey, version);
if (IsKeyNull(values))
{
return null;
}
Index index = parentKey.GetSortIndex((version == DataRowVersion.Original) ? DataViewRowState.OriginalRows : DataViewRowState.CurrentRows);
Range range = index.FindRecords(values);
if (range.IsNull)
{
return null;
}
if (range.Count > 1)
{
throw ExceptionBuilder.MultipleParents();
}
return parentKey.Table._recordManager[index.GetRecord(range.Min)];
}
/// <summary>
/// Internally sets the DataSet pointer.
/// </summary>
internal void SetDataSet(DataSet dataSet)
{
if (_dataSet != dataSet)
{
_dataSet = dataSet;
}
}
internal void SetParentRowRecords(DataRow childRow, DataRow parentRow)
{
object[] parentKeyValues = parentRow.GetKeyValues(ParentKey);
if (childRow._tempRecord != -1)
{
ChildTable._recordManager.SetKeyValues(childRow._tempRecord, ChildKey, parentKeyValues);
}
if (childRow._newRecord != -1)
{
ChildTable._recordManager.SetKeyValues(childRow._newRecord, ChildKey, parentKeyValues);
}
if (childRow._oldRecord != -1)
{
ChildTable._recordManager.SetKeyValues(childRow._oldRecord, ChildKey, parentKeyValues);
}
}
/// <summary>
/// Gets the parent columns of this relation.
/// </summary>
public virtual DataColumn[] ParentColumns
{
get
{
CheckStateForProperty();
return _parentKey.ToArray();
}
}
internal DataColumn[] ParentColumnsReference => _parentKey.ColumnsReference;
/// <summary>
/// The internal constraint object for the parent table.
/// </summary>
internal DataKey ParentKey
{
get
{
CheckStateForProperty();
return _parentKey;
}
}
/// <summary>
/// Gets the parent table of this relation.
/// </summary>
public virtual DataTable ParentTable
{
get
{
CheckStateForProperty();
return _parentKey.Table;
}
}
/// <summary>
/// Gets or sets the name used to look up this relation in the parent
/// data set's <see cref='System.Data.DataRelationCollection'/>.
/// </summary>
[DefaultValue("")]
public virtual string RelationName
{
get
{
CheckStateForProperty();
return _relationName;
}
set
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataRelation.set_RelationName|API> {0}, '{1}'", ObjectID, value);
try
{
if (value == null)
{
value = string.Empty;
}
CultureInfo locale = (_dataSet != null ? _dataSet.Locale : CultureInfo.CurrentCulture);
if (string.Compare(_relationName, value, true, locale) != 0)
{
if (_dataSet != null)
{
if (value.Length == 0)
{
throw ExceptionBuilder.NoRelationName();
}
_dataSet.Relations.RegisterName(value);
if (_relationName.Length != 0)
{
_dataSet.Relations.UnregisterName(_relationName);
}
}
_relationName = value;
((DataRelationCollection.DataTableRelationCollection)(ParentTable.ChildRelations)).OnRelationPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this));
((DataRelationCollection.DataTableRelationCollection)(ChildTable.ParentRelations)).OnRelationPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this));
}
else if (string.Compare(_relationName, value, false, locale) != 0)
{
_relationName = value;
((DataRelationCollection.DataTableRelationCollection)(ParentTable.ChildRelations)).OnRelationPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this));
((DataRelationCollection.DataTableRelationCollection)(ChildTable.ParentRelations)).OnRelationPropertyChanged(new CollectionChangeEventArgs(CollectionChangeAction.Refresh, this));
}
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
}
internal void CheckNamespaceValidityForNestedRelations(string ns)
{
foreach (DataRelation rel in ChildTable.ParentRelations)
{
if (rel == this || rel.Nested)
{
if (rel.ParentTable.Namespace != ns)
{
throw ExceptionBuilder.InValidNestedRelation(ChildTable.TableName);
}
}
}
}
internal void CheckNestedRelations()
{
DataCommonEventSource.Log.Trace("<ds.DataRelation.CheckNestedRelations|INFO> {0}", ObjectID);
Debug.Assert(DataSet == null || !_nested, "this relation supposed to be not in dataset or not nested");
// 1. There is no other relation (R) that has this.ChildTable as R.ChildTable
// This is not valid for Whidbey anymore so the code has been removed
// 2. There is no loop in nested relations
#if DEBUG
int numTables = ParentTable.DataSet.Tables.Count;
#endif
DataTable dt = ParentTable;
if (ChildTable == ParentTable)
{
if (string.Compare(ChildTable.TableName, ChildTable.DataSet.DataSetName, true, ChildTable.DataSet.Locale) == 0)
throw ExceptionBuilder.SelfnestedDatasetConflictingName(ChildTable.TableName);
return; //allow self join tables.
}
List<DataTable> list = new List<DataTable>();
list.Add(ChildTable);
// We have already checked for nested relaion UP
for (int i = 0; i < list.Count; ++i)
{
DataRelation[] relations = list[i].NestedParentRelations;
foreach (DataRelation rel in relations)
{
if (rel.ParentTable == ChildTable && rel.ChildTable != ChildTable)
{
throw ExceptionBuilder.LoopInNestedRelations(ChildTable.TableName);
}
if (!list.Contains(rel.ParentTable))
{
// check for self nested
list.Add(rel.ParentTable);
}
}
}
}
/********************
The Namespace of a table nested inside multiple parents can be
1. Explicitly specified
2. Inherited from Parent Table
3. Empty (Form = unqualified case)
However, Schema does not allow (3) to be a global element and multiple nested child has to be a global element.
Therefore we'll reduce case (3) to (2) if all parents have same namespace else throw.
********************/
/// <summary>
/// Gets or sets a value indicating whether relations are nested.
/// </summary>
[DefaultValue(false)]
public virtual bool Nested
{
get
{
CheckStateForProperty();
return _nested;
}
set
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataRelation.set_Nested|API> {0}, {1}", ObjectID, value);
try
{
if (_nested != value)
{
if (_dataSet != null)
{
if (value)
{
if (ChildTable.IsNamespaceInherited())
{ // if not added to collection, don't do this check
CheckNamespaceValidityForNestedRelations(ParentTable.Namespace);
}
Debug.Assert(ChildTable != null, "On a DataSet, but not on Table. Bad state");
ForeignKeyConstraint constraint = ChildTable.Constraints.FindForeignKeyConstraint(ChildKey.ColumnsReference, ParentKey.ColumnsReference);
if (constraint != null)
{
constraint.CheckConstraint();
}
ValidateMultipleNestedRelations();
}
}
if (!value && (_parentKey.ColumnsReference[0].ColumnMapping == MappingType.Hidden))
{
throw ExceptionBuilder.RelationNestedReadOnly();
}
if (value)
{
ParentTable.Columns.RegisterColumnName(ChildTable.TableName, null);
}
else
{
ParentTable.Columns.UnregisterName(ChildTable.TableName);
}
RaisePropertyChanging(nameof(Nested));
if (value)
{
CheckNestedRelations();
if (DataSet != null)
if (ParentTable == ChildTable)
{
foreach (DataRow row in ChildTable.Rows)
{
row.CheckForLoops(this);
}
if (ChildTable.DataSet != null && (string.Compare(ChildTable.TableName, ChildTable.DataSet.DataSetName, true, ChildTable.DataSet.Locale) == 0))
{
throw ExceptionBuilder.DatasetConflictingName(_dataSet.DataSetName);
}
ChildTable._fNestedInDataset = false;
}
else
{
foreach (DataRow row in ChildTable.Rows)
{
row.GetParentRow(this);
}
}
ParentTable.ElementColumnCount++;
}
else
{
ParentTable.ElementColumnCount--;
}
_nested = value;
ChildTable.CacheNestedParent();
if (value)
{
if (string.IsNullOrEmpty(ChildTable.Namespace) && ((ChildTable.NestedParentsCount > 1) ||
((ChildTable.NestedParentsCount > 0) && !(ChildTable.DataSet.Relations.Contains(RelationName)))))
{
string parentNs = null;
foreach (DataRelation rel in ChildTable.ParentRelations)
{
if (rel.Nested)
{
if (null == parentNs)
{
parentNs = rel.ParentTable.Namespace;
}
else
{
if (string.Compare(parentNs, rel.ParentTable.Namespace, StringComparison.Ordinal) != 0)
{
_nested = false;
throw ExceptionBuilder.InvalidParentNamespaceinNestedRelation(ChildTable.TableName);
}
}
}
}
// if not already in memory , form == unqualified
if (CheckMultipleNested && ChildTable._tableNamespace != null && ChildTable._tableNamespace.Length == 0)
{
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
ChildTable._tableNamespace = null; // if we dont throw, then let it inherit the Namespace
}
}
}
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
}
/// <summary>
/// Gets the constraint which ensures values in a column are unique.
/// </summary>
public virtual UniqueConstraint ParentKeyConstraint
{
get
{
CheckStateForProperty();
return _parentKeyConstraint;
}
}
internal void SetParentKeyConstraint(UniqueConstraint value)
{
Debug.Assert(_parentKeyConstraint == null || value == null, "ParentKeyConstraint should not have been set already.");
_parentKeyConstraint = value;
}
/// <summary>
/// Gets the <see cref='System.Data.ForeignKeyConstraint'/> for the relation.
/// </summary>
public virtual ForeignKeyConstraint ChildKeyConstraint
{
get
{
CheckStateForProperty();
return _childKeyConstraint;
}
}
/// <summary>
/// Gets the collection of custom user information.
/// </summary>
[Browsable(false)]
public PropertyCollection ExtendedProperties => _extendedProperties ?? (_extendedProperties = new PropertyCollection());
internal bool CheckMultipleNested
{
get { return _checkMultipleNested; }
set { _checkMultipleNested = value; }
}
internal void SetChildKeyConstraint(ForeignKeyConstraint value)
{
Debug.Assert(_childKeyConstraint == null || value == null, "ChildKeyConstraint should not have been set already.");
_childKeyConstraint = value;
}
internal event PropertyChangedEventHandler PropertyChanging;
// If we're not in a dataSet relations collection, we need to verify on every property get that we're
// still a good relation object.
internal void CheckState()
{
if (_dataSet == null)
{
_parentKey.CheckState();
_childKey.CheckState();
if (_parentKey.Table.DataSet != _childKey.Table.DataSet)
{
throw ExceptionBuilder.RelationDataSetMismatch();
}
if (_childKey.ColumnsEqual(_parentKey))
{
throw ExceptionBuilder.KeyColumnsIdentical();
}
for (int i = 0; i < _parentKey.ColumnsReference.Length; i++)
{
if ((_parentKey.ColumnsReference[i].DataType != _childKey.ColumnsReference[i].DataType) ||
((_parentKey.ColumnsReference[i].DataType == typeof(DateTime)) &&
(_parentKey.ColumnsReference[i].DateTimeMode != _childKey.ColumnsReference[i].DateTimeMode) &&
((_parentKey.ColumnsReference[i].DateTimeMode & _childKey.ColumnsReference[i].DateTimeMode) != DataSetDateTime.Unspecified)))
{
// allow unspecified and unspecifiedlocal
throw ExceptionBuilder.ColumnsTypeMismatch();
}
}
}
}
/// <summary>
/// Checks to ensure the DataRelation is a valid object, even if it doesn't
/// belong to a <see cref='System.Data.DataSet'/>.
/// </summary>
protected void CheckStateForProperty()
{
try
{
CheckState();
}
catch (Exception e) when (ADP.IsCatchableExceptionType(e))
{
throw ExceptionBuilder.BadObjectPropertyAccess(e.Message);
}
}
private void Create(string relationName, DataColumn[] parentColumns, DataColumn[] childColumns, bool createConstraints)
{
long logScopeId = DataCommonEventSource.Log.EnterScope("<ds.DataRelation.Create|INFO> {0}, relationName='{1}', createConstraints={2}", ObjectID, relationName, createConstraints);
try
{
_parentKey = new DataKey(parentColumns, true);
_childKey = new DataKey(childColumns, true);
if (parentColumns.Length != childColumns.Length)
{
throw ExceptionBuilder.KeyLengthMismatch();
}
for (int i = 0; i < parentColumns.Length; i++)
{
if ((parentColumns[i].Table.DataSet == null) || (childColumns[i].Table.DataSet == null))
{
throw ExceptionBuilder.ParentOrChildColumnsDoNotHaveDataSet();
}
}
CheckState();
_relationName = (relationName == null ? "" : relationName);
_createConstraints = createConstraints;
}
finally
{
DataCommonEventSource.Log.ExitScope(logScopeId);
}
}
internal DataRelation Clone(DataSet destination)
{
DataCommonEventSource.Log.Trace("<ds.DataRelation.Clone|INFO> {0}, destination={1}", ObjectID, (destination != null) ? destination.ObjectID : 0);
DataTable parent = destination.Tables[ParentTable.TableName, ParentTable.Namespace];
DataTable child = destination.Tables[ChildTable.TableName, ChildTable.Namespace];
int keyLength = _parentKey.ColumnsReference.Length;
DataColumn[] parentColumns = new DataColumn[keyLength];
DataColumn[] childColumns = new DataColumn[keyLength];
for (int i = 0; i < keyLength; i++)
{
parentColumns[i] = parent.Columns[ParentKey.ColumnsReference[i].ColumnName];
childColumns[i] = child.Columns[ChildKey.ColumnsReference[i].ColumnName];
}
DataRelation clone = new DataRelation(_relationName, parentColumns, childColumns, false);
clone.CheckMultipleNested = false; // disable the check in clone as it is already created
clone.Nested = Nested;
clone.CheckMultipleNested = true; // enable the check
// ...Extended Properties
if (_extendedProperties != null)
{
foreach (object key in _extendedProperties.Keys)
{
clone.ExtendedProperties[key] = _extendedProperties[key];
}
}
return clone;
}
protected internal void OnPropertyChanging(PropertyChangedEventArgs pcevent)
{
if (PropertyChanging != null)
{
DataCommonEventSource.Log.Trace("<ds.DataRelation.OnPropertyChanging|INFO> {0}", ObjectID);
PropertyChanging(this, pcevent);
}
}
protected internal void RaisePropertyChanging(string name)
{
OnPropertyChanging(new PropertyChangedEventArgs(name));
}
/// <summary>
/// </summary>
public override string ToString() => RelationName;
internal void ValidateMultipleNestedRelations()
{
// find all nested relations that this child table has
// if this relation is the only relation it has, then fine,
// otherwise check if all relations are created from XSD, without using Key/KeyRef
// check all keys to see autogenerated
if (!Nested || !CheckMultipleNested) // no need for this verification
{
return;
}
if (0 < ChildTable.NestedParentRelations.Length)
{
DataColumn[] childCols = ChildColumns;
if (childCols.Length != 1 || !IsAutoGenerated(childCols[0]))
{
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
if (!XmlTreeGen.AutoGenerated(this))
{
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
foreach (Constraint cs in ChildTable.Constraints)
{
if (cs is ForeignKeyConstraint)
{
ForeignKeyConstraint fk = (ForeignKeyConstraint)cs;
if (!XmlTreeGen.AutoGenerated(fk, true))
{
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
}
else
{
UniqueConstraint unique = (UniqueConstraint)cs;
if (!XmlTreeGen.AutoGenerated(unique))
{
throw ExceptionBuilder.TableCantBeNestedInTwoTables(ChildTable.TableName);
}
}
}
}
}
private bool IsAutoGenerated(DataColumn col)
{
if (col.ColumnMapping != MappingType.Hidden)
{
return false;
}
if (col.DataType != typeof(int))
{
return false;
}
string generatedname = col.Table.TableName + "_Id";
if ((col.ColumnName == generatedname) || (col.ColumnName == generatedname + "_0"))
{
return true;
}
generatedname = ParentColumnsReference[0].Table.TableName + "_Id";
if ((col.ColumnName == generatedname) || (col.ColumnName == generatedname + "_0"))
{
return true;
}
return false;
}
internal int ObjectID => _objectID;
}
}
| |
// 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;
public struct VT
{
public decimal[,] decimal2darr;
public decimal[, ,] decimal3darr;
public decimal[,] decimal2darr_b;
public decimal[, ,] decimal3darr_b;
}
public class CL
{
public decimal[,] decimal2darr = { { 0, -1 }, { 0, 0 } };
public decimal[, ,] decimal3darr = { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } };
public decimal[,] decimal2darr_b = { { 0, 1 }, { 0, 0 } };
public decimal[, ,] decimal3darr_b = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
}
public class decimalMDArrTest
{
static decimal[,] decimal2darr = { { 0, -1 }, { 0, 0 } };
static decimal[, ,] decimal3darr = { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } };
static decimal[,] decimal2darr_b = { { 0, 1 }, { 0, 0 } };
static decimal[, ,] decimal3darr_b = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
static decimal[][,] ja1 = new decimal[2][,];
static decimal[][, ,] ja2 = new decimal[2][, ,];
static decimal[][,] ja1_b = new decimal[2][,];
static decimal[][, ,] ja2_b = new decimal[2][, ,];
public static int Main()
{
bool pass = true;
VT vt1;
vt1.decimal2darr = new decimal[,] { { 0, -1 }, { 0, 0 } };
vt1.decimal3darr = new decimal[,,] { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } };
vt1.decimal2darr_b = new decimal[,] { { 0, 1 }, { 0, 0 } };
vt1.decimal3darr_b = new decimal[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
CL cl1 = new CL();
ja1[0] = new decimal[,] { { 0, -1 }, { 0, 0 } };
ja2[1] = new decimal[,,] { { { 0, 0 } }, { { 0, -1 } }, { { 0, 0 } } };
ja1_b[0] = new decimal[,] { { 0, 1 }, { 0, 0 } };
ja2_b[1] = new decimal[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } };
decimal result = -1;
// 2D
if (result != decimal2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("2darr[0, 1] is: {0}", decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != vt1.decimal2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("vt1.decimal2darr[0, 1] is: {0}", vt1.decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != cl1.decimal2darr[0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("cl1.decimal2darr[0, 1] is: {0}", cl1.decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != ja1[0][0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (result != decimal3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("decimal3darr[1,0,1] is: {0}", decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != vt1.decimal3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("vt1.decimal3darr[1,0,1] is: {0}", vt1.decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != cl1.decimal3darr[1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("cl1.decimal3darr[1,0,1] is: {0}", cl1.decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (result != ja2[1][1, 0, 1])
{
Console.WriteLine("ERROR:");
Console.WriteLine("result is: {0}", result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//DecimalToByte tests
byte Byte_result = 1;
// 2D
if (Byte_result != Convert.ToByte(decimal2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("2darr[0, 1] is: {0}", decimal2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(vt1.decimal2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("vt1.decimal2darr_b[0, 1] is: {0}", vt1.decimal2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(cl1.decimal2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("cl1.decimal2darr_b[0, 1] is: {0}", cl1.decimal2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Byte_result != Convert.ToByte(decimal3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("decimal3darr_b[1,0,1] is: {0}", decimal3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(vt1.decimal3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("vt1.decimal3darr_b[1,0,1] is: {0}", vt1.decimal3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(cl1.decimal3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("cl1.decimal3darr_b[1,0,1] is: {0}", cl1.decimal3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Byte_result != Convert.ToByte(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Byte_result is: {0}", Byte_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//DecimalToDouble
double double_result = -1;
// 2D
if (double_result != Convert.ToDouble(decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("double_result is: {0}", double_result);
Console.WriteLine("2darr[0, 1] is: {0}", decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (double_result != Convert.ToDouble(vt1.decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("double_result is: {0}", double_result);
Console.WriteLine("vt1.decimal2darr[0, 1] is: {0}", vt1.decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (double_result != Convert.ToDouble(cl1.decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("double_result is: {0}", double_result);
Console.WriteLine("cl1.decimal2darr[0, 1] is: {0}", cl1.decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (double_result != Convert.ToDouble(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("double_result is: {0}", double_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (double_result != Convert.ToDouble(decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("double_result is: {0}", double_result);
Console.WriteLine("decimal3darr[1,0,1] is: {0}", decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (double_result != Convert.ToDouble(vt1.decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("double_result is: {0}", double_result);
Console.WriteLine("vt1.decimal3darr[1,0,1] is: {0}", vt1.decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (double_result != Convert.ToDouble(cl1.decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("double_result is: {0}", double_result);
Console.WriteLine("cl1.decimal3darr[1,0,1] is: {0}", cl1.decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (double_result != Convert.ToDouble(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("double_result is: {0}", double_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//DeimalToSingle
Single Single_result = -1;
// 2D
if (Single_result != Convert.ToSingle(decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("2darr[0, 1] is: {0}", decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(vt1.decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("vt1.decimal2darr[0, 1] is: {0}", vt1.decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(cl1.decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("cl1.decimal2darr[0, 1] is: {0}", cl1.decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Single_result != Convert.ToSingle(decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("decimal3darr[1,0,1] is: {0}", decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(vt1.decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("vt1.decimal3darr[1,0,1] is: {0}", vt1.decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(cl1.decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("cl1.decimal3darr[1,0,1] is: {0}", cl1.decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Single_result != Convert.ToSingle(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Single_result is: {0}", Single_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//DecimalToInt32 tests
int Int32_result = -1;
// 2D
if (Int32_result != Convert.ToInt32(decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("2darr[0, 1] is: {0}", decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(vt1.decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("vt1.decimal2darr[0, 1] is: {0}", vt1.decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(cl1.decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("cl1.decimal2darr[0, 1] is: {0}", cl1.decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Int32_result != Convert.ToInt32(decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("decimal3darr[1,0,1] is: {0}", decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(vt1.decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("vt1.decimal3darr[1,0,1] is: {0}", vt1.decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(cl1.decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("cl1.decimal3darr[1,0,1] is: {0}", cl1.decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int32_result != Convert.ToInt32(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int32_result is: {0}", Int32_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//DecimalToInt64 tests
long Int64_result = -1;
// 2D
if (Int64_result != Convert.ToInt64(decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("2darr[0, 1] is: {0}", decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(vt1.decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("vt1.decimal2darr[0, 1] is: {0}", vt1.decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(cl1.decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("cl1.decimal2darr[0, 1] is: {0}", cl1.decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Int64_result != Convert.ToInt64(decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("decimal3darr[1,0,1] is: {0}", decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(vt1.decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("vt1.decimal3darr[1,0,1] is: {0}", vt1.decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(cl1.decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("cl1.decimal3darr[1,0,1] is: {0}", cl1.decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int64_result != Convert.ToInt64(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int64_result is: {0}", Int64_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//DecimalToSByte tests
sbyte SByte_result = -1;
// 2D
if (SByte_result != Convert.ToSByte(decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("2darr[0, 1] is: {0}", decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(vt1.decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("vt1.decimal2darr[0, 1] is: {0}", vt1.decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(cl1.decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("cl1.decimal2darr[0, 1] is: {0}", cl1.decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (SByte_result != Convert.ToSByte(decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("decimal3darr[1,0,1] is: {0}", decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(vt1.decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("vt1.decimal3darr[1,0,1] is: {0}", vt1.decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(cl1.decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("cl1.decimal3darr[1,0,1] is: {0}", cl1.decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (SByte_result != Convert.ToSByte(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("SByte_result is: {0}", SByte_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//DecimalToInt16 tests
short Int16_result = -1;
// 2D
if (Int16_result != Convert.ToInt16(decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("2darr[0, 1] is: {0}", decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(vt1.decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("vt1.decimal2darr[0, 1] is: {0}", vt1.decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(cl1.decimal2darr[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("cl1.decimal2darr[0, 1] is: {0}", cl1.decimal2darr[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(ja1[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (Int16_result != Convert.ToInt16(decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("decimal3darr[1,0,1] is: {0}", decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(vt1.decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("vt1.decimal3darr[1,0,1] is: {0}", vt1.decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(cl1.decimal3darr[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("cl1.decimal3darr[1,0,1] is: {0}", cl1.decimal3darr[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (Int16_result != Convert.ToInt16(ja2[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("Int16_result is: {0}", Int16_result);
Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//DecimalToUInt32 tests
uint UInt32_result = 1;
// 2D
if (UInt32_result != Convert.ToUInt32(decimal2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("2darr[0, 1] is: {0}", decimal2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(vt1.decimal2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("vt1.decimal2darr_b[0, 1] is: {0}", vt1.decimal2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(cl1.decimal2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("cl1.decimal2darr_b[0, 1] is: {0}", cl1.decimal2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (UInt32_result != Convert.ToUInt32(decimal3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("decimal3darr_b[1,0,1] is: {0}", decimal3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(vt1.decimal3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("vt1.decimal3darr_b[1,0,1] is: {0}", vt1.decimal3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(cl1.decimal3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("cl1.decimal3darr_b[1,0,1] is: {0}", cl1.decimal3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt32_result != Convert.ToUInt32(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt32_result is: {0}", UInt32_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//DecimalToUInt64 tests
ulong UInt64_result = 1;
// 2D
if (UInt64_result != Convert.ToUInt64(decimal2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("2darr[0, 1] is: {0}", decimal2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(vt1.decimal2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("vt1.decimal2darr_b[0, 1] is: {0}", vt1.decimal2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(cl1.decimal2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("cl1.decimal2darr_b[0, 1] is: {0}", cl1.decimal2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (UInt64_result != Convert.ToUInt64(decimal3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("decimal3darr_b[1,0,1] is: {0}", decimal3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(vt1.decimal3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("vt1.decimal3darr_b[1,0,1] is: {0}", vt1.decimal3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(cl1.decimal3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("cl1.decimal3darr_b[1,0,1] is: {0}", cl1.decimal3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt64_result != Convert.ToUInt64(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt64_result is: {0}", UInt64_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
//DecimalToUInt16 tests
ushort UInt16_result = 1;
// 2D
if (UInt16_result != Convert.ToUInt16(decimal2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("2darr[0, 1] is: {0}", decimal2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(vt1.decimal2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("vt1.decimal2darr_b[0, 1] is: {0}", vt1.decimal2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(cl1.decimal2darr_b[0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("cl1.decimal2darr_b[0, 1] is: {0}", cl1.decimal2darr_b[0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(ja1_b[0][0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
// 3D
if (UInt16_result != Convert.ToUInt16(decimal3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("decimal3darr_b[1,0,1] is: {0}", decimal3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(vt1.decimal3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("vt1.decimal3darr_b[1,0,1] is: {0}", vt1.decimal3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(cl1.decimal3darr_b[1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("cl1.decimal3darr_b[1,0,1] is: {0}", cl1.decimal3darr_b[1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (UInt16_result != Convert.ToUInt16(ja2_b[1][1, 0, 1]))
{
Console.WriteLine("ERROR:");
Console.WriteLine("UInt16_result is: {0}", UInt16_result);
Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]);
Console.WriteLine("and they are NOT equal !");
Console.WriteLine();
pass = false;
}
if (!pass)
{
Console.WriteLine("FAILED");
return 1;
}
else
{
Console.WriteLine("PASSED");
return 100;
}
}
};
| |
// 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 UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using UnityEditorInternal;
namespace Fungus.EditorUtils
{
[CustomEditor (typeof(Command), true)]
public class CommandEditor : Editor
{
#region statics
public static Command selectedCommand;
public static bool SelectedCommandDataStale { get; set; }
public static CommandInfoAttribute GetCommandInfo(System.Type commandType)
{
CommandInfoAttribute retval = null;
object[] attributes = commandType.GetCustomAttributes(typeof(CommandInfoAttribute), false);
foreach (object obj in attributes)
{
CommandInfoAttribute commandInfoAttr = obj as CommandInfoAttribute;
if (commandInfoAttr != null)
{
if (retval == null)
retval = commandInfoAttr;
else if (retval.Priority < commandInfoAttr.Priority)
retval = commandInfoAttr;
}
}
return retval;
}
#endregion statics
private Dictionary<string, ReorderableList> reorderableLists;
public virtual void OnEnable()
{
if (NullTargetCheck()) // Check for an orphaned editor instance
return;
reorderableLists = new Dictionary<string, ReorderableList>();
}
public virtual void DrawCommandInspectorGUI()
{
Command t = target as Command;
if (t == null)
{
return;
}
var flowchart = (Flowchart)t.GetFlowchart();
if (flowchart == null)
{
return;
}
CommandInfoAttribute commandInfoAttr = CommandEditor.GetCommandInfo(t.GetType());
if (commandInfoAttr == null)
{
return;
}
GUILayout.BeginVertical(GUI.skin.box);
if (t.enabled)
{
if (flowchart.ColorCommands)
{
GUI.backgroundColor = t.GetButtonColor();
}
else
{
GUI.backgroundColor = Color.white;
}
}
else
{
GUI.backgroundColor = Color.grey;
}
GUILayout.BeginHorizontal(GUI.skin.button);
string commandName = commandInfoAttr.CommandName;
GUILayout.Label(commandName, GUILayout.MinWidth(80), GUILayout.ExpandWidth(true));
GUILayout.FlexibleSpace();
GUILayout.Label(new GUIContent("(" + t.ItemId + ")"));
GUILayout.Space(10);
GUI.backgroundColor = Color.white;
bool enabled = t.enabled;
enabled = GUILayout.Toggle(enabled, new GUIContent());
if (t.enabled != enabled)
{
Undo.RecordObject(t, "Set Enabled");
t.enabled = enabled;
}
GUILayout.EndHorizontal();
GUI.backgroundColor = Color.white;
EditorGUILayout.Separator();
EditorGUI.BeginChangeCheck();
DrawCommandGUI();
if(EditorGUI.EndChangeCheck())
{
SelectedCommandDataStale = true;
}
EditorGUILayout.Separator();
if (t.ErrorMessage.Length > 0)
{
GUIStyle style = new GUIStyle(GUI.skin.label);
style.normal.textColor = new Color(1,0,0);
EditorGUILayout.LabelField(new GUIContent("Error: " + t.ErrorMessage), style);
}
GUILayout.EndVertical();
// Display help text
CommandInfoAttribute infoAttr = CommandEditor.GetCommandInfo(t.GetType());
if (infoAttr != null)
{
EditorGUILayout.HelpBox(infoAttr.HelpText, MessageType.Info, true);
}
}
public virtual void DrawCommandGUI()
{
Command t = target as Command;
// Code below was copied from here
// http://answers.unity3d.com/questions/550829/how-to-add-a-script-field-in-custom-inspector.html
// Users should not be able to change the MonoScript for the command using the usual Script field.
// Doing so could cause block.commandList to contain null entries.
// To avoid this we manually display all properties, except for m_Script.
serializedObject.Update();
SerializedProperty iterator = serializedObject.GetIterator();
bool enterChildren = true;
while (iterator.NextVisible(enterChildren))
{
enterChildren = false;
if (iterator.name == "m_Script")
{
continue;
}
if (!t.IsPropertyVisible(iterator.name))
{
continue;
}
if (iterator.isArray &&
t.IsReorderableArray(iterator.name))
{
ReorderableList reordList = null;
reorderableLists.TryGetValue(iterator.displayName, out reordList);
if(reordList == null)
{
var locSerProp = iterator.Copy();
//create and insert
reordList = new ReorderableList(serializedObject, locSerProp, true, false, true, true)
{
drawHeaderCallback = (Rect rect) =>
{
EditorGUI.LabelField(rect, locSerProp.displayName);
},
drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
{
EditorGUI.PropertyField(rect, locSerProp.GetArrayElementAtIndex(index));
},
elementHeightCallback = (int index) =>
{
return EditorGUI.GetPropertyHeight(locSerProp.GetArrayElementAtIndex(index), null, true);// + EditorGUIUtility.singleLineHeight;
}
};
reorderableLists.Add(iterator.displayName, reordList);
}
reordList.DoLayoutList();
}
else
{
EditorGUILayout.PropertyField(iterator, true, new GUILayoutOption[0]);
}
}
serializedObject.ApplyModifiedProperties();
}
public static void ObjectField<T>(SerializedProperty property, GUIContent label, GUIContent nullLabel, List<T> objectList) where T : Object
{
if (property == null)
{
return;
}
List<GUIContent> objectNames = new List<GUIContent>();
T selectedObject = property.objectReferenceValue as T;
int selectedIndex = -1; // Invalid index
// First option in list is <None>
objectNames.Add(nullLabel);
if (selectedObject == null)
{
selectedIndex = 0;
}
for (int i = 0; i < objectList.Count; ++i)
{
if (objectList[i] == null) continue;
objectNames.Add(new GUIContent(objectList[i].name));
if (selectedObject == objectList[i])
{
selectedIndex = i + 1;
}
}
T result;
selectedIndex = EditorGUILayout.Popup(label, selectedIndex, objectNames.ToArray());
if (selectedIndex == -1)
{
// Currently selected object is not in list, but nothing else was selected so no change.
return;
}
else if (selectedIndex == 0)
{
result = null; // Null option
}
else
{
result = objectList[selectedIndex - 1];
}
property.objectReferenceValue = result;
}
// When modifying custom editor code you can occasionally end up with orphaned editor instances.
// When this happens, you'll get a null exception error every time the scene serializes / deserialized.
// Once this situation occurs, the only way to fix it is to restart the Unity editor.
//
// As a workaround, this function detects if this command editor is an orphan and deletes it.
// To use it, just call this function at the top of the OnEnable() method in your custom editor.
protected virtual bool NullTargetCheck()
{
try
{
// The serializedObject accessor create a new SerializedObject if needed.
// However, this will fail with a null exception if the target object no longer exists.
#pragma warning disable 0219
SerializedObject so = serializedObject;
}
catch (System.NullReferenceException)
{
DestroyImmediate(this);
return true;
}
return false;
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Web;
using System.Text;
using System.Xml;
using SMTD = System.ServiceModel.Diagnostics.Application.TD;
using WebTD = System.ServiceModel.Web.Diagnostics.Application.TD;
class JsonMessageEncoderFactory : MessageEncoderFactory
{
static readonly TextMessageEncoderFactory.ContentEncoding[] ApplicationJsonContentEncoding = GetContentEncodingMap(JsonGlobals.applicationJsonMediaType);
JsonMessageEncoder messageEncoder;
public JsonMessageEncoderFactory(Encoding writeEncoding, int maxReadPoolSize, int maxWritePoolSize, XmlDictionaryReaderQuotas quotas, bool crossDomainScriptAccessEnabled)
{
messageEncoder = new JsonMessageEncoder(writeEncoding, maxReadPoolSize, maxWritePoolSize, quotas, crossDomainScriptAccessEnabled);
}
public override MessageEncoder Encoder
{
get { return messageEncoder; }
}
public override MessageVersion MessageVersion
{
get { return messageEncoder.MessageVersion; }
}
internal static string GetContentType(WebMessageEncodingBindingElement encodingElement)
{
if (encodingElement == null)
{
return WebMessageEncoderFactory.GetContentType(JsonGlobals.applicationJsonMediaType, TextEncoderDefaults.Encoding);
}
else
{
return WebMessageEncoderFactory.GetContentType(JsonGlobals.applicationJsonMediaType, encodingElement.WriteEncoding);
}
}
static TextMessageEncoderFactory.ContentEncoding[] GetContentEncodingMap(string mediaType)
{
Encoding[] readEncodings = TextMessageEncoderFactory.GetSupportedEncodings();
TextMessageEncoderFactory.ContentEncoding[] map = new TextMessageEncoderFactory.ContentEncoding[readEncodings.Length];
for (int i = 0; i < readEncodings.Length; i++)
{
TextMessageEncoderFactory.ContentEncoding contentEncoding = new TextMessageEncoderFactory.ContentEncoding();
contentEncoding.contentType = WebMessageEncoderFactory.GetContentType(mediaType, readEncodings[i]);
contentEncoding.encoding = readEncodings[i];
map[i] = contentEncoding;
}
return map;
}
class JsonMessageEncoder : MessageEncoder
{
const int maxPooledXmlReadersPerMessage = 2;
// Double-checked locking pattern requires volatile for read/write synchronization
volatile SynchronizedPool<JsonBufferedMessageData> bufferedReaderPool;
volatile SynchronizedPool<JsonBufferedMessageWriter> bufferedWriterPool;
string contentType;
int maxReadPoolSize;
int maxWritePoolSize;
OnXmlDictionaryReaderClose onStreamedReaderClose;
XmlDictionaryReaderQuotas readerQuotas;
XmlDictionaryReaderQuotas bufferedReadReaderQuotas;
// Double-checked locking pattern requires volatile for read/write synchronization
volatile SynchronizedPool<RecycledMessageState> recycledStatePool;
volatile SynchronizedPool<XmlDictionaryReader> streamedReaderPool;
volatile SynchronizedPool<XmlDictionaryWriter> streamedWriterPool;
object thisLock;
Encoding writeEncoding;
bool crossDomainScriptAccessEnabled;
byte[] encodedClosingFunctionCall;
public JsonMessageEncoder(Encoding writeEncoding, int maxReadPoolSize, int maxWritePoolSize, XmlDictionaryReaderQuotas quotas, bool crossDomainScriptAccessEnabled)
{
if (writeEncoding == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writeEncoding");
}
thisLock = new object();
TextEncoderDefaults.ValidateEncoding(writeEncoding);
this.writeEncoding = writeEncoding;
this.maxReadPoolSize = maxReadPoolSize;
this.maxWritePoolSize = maxWritePoolSize;
this.readerQuotas = new XmlDictionaryReaderQuotas();
this.onStreamedReaderClose = new OnXmlDictionaryReaderClose(ReturnStreamedReader);
quotas.CopyTo(this.readerQuotas);
this.bufferedReadReaderQuotas = EncoderHelpers.GetBufferedReadQuotas(this.readerQuotas);
this.contentType = WebMessageEncoderFactory.GetContentType(JsonGlobals.applicationJsonMediaType, writeEncoding);
this.crossDomainScriptAccessEnabled = crossDomainScriptAccessEnabled;
this.encodedClosingFunctionCall = this.writeEncoding.GetBytes(");");
}
public override string ContentType
{
get { return contentType; }
}
public override string MediaType
{
get { return JsonGlobals.applicationJsonMediaType; }
}
public override MessageVersion MessageVersion
{
get { return MessageVersion.None; }
}
SynchronizedPool<RecycledMessageState> RecycledStatePool
{
get
{
if (recycledStatePool == null)
{
lock (ThisLock)
{
if (recycledStatePool == null)
{
recycledStatePool = new SynchronizedPool<RecycledMessageState>(maxReadPoolSize);
}
}
}
return recycledStatePool;
}
}
object ThisLock
{
get { return thisLock; }
}
public override bool IsContentTypeSupported(string contentType)
{
if (contentType == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contentType");
}
return IsJsonContentType(contentType);
}
public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
{
if (bufferManager == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bufferManager"));
}
if (WebTD.JsonMessageDecodingStartIsEnabled())
{
WebTD.JsonMessageDecodingStart();
}
Message message;
JsonBufferedMessageData messageData = TakeBufferedReader();
messageData.Encoding = TextMessageEncoderFactory.GetEncodingFromContentType(contentType, JsonMessageEncoderFactory.ApplicationJsonContentEncoding);
messageData.Open(buffer, bufferManager);
RecycledMessageState messageState = messageData.TakeMessageState();
if (messageState == null)
{
messageState = new RecycledMessageState();
}
message = new BufferedMessage(messageData, messageState);
message.Properties.Encoder = this;
if (SMTD.MessageReadByEncoderIsEnabled() && buffer != null)
{
SMTD.MessageReadByEncoder(
EventTraceActivityHelper.TryExtractActivity(message, true),
buffer.Count,
this);
}
if (MessageLogger.LogMessagesAtTransportLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive);
}
return message;
}
public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)
{
if (stream == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("stream"));
}
if (WebTD.JsonMessageDecodingStartIsEnabled())
{
WebTD.JsonMessageDecodingStart();
}
XmlReader reader = TakeStreamedReader(stream, TextMessageEncoderFactory.GetEncodingFromContentType(contentType, JsonMessageEncoderFactory.ApplicationJsonContentEncoding));
Message message = Message.CreateMessage(reader, maxSizeOfHeaders, MessageVersion.None);
message.Properties.Encoder = this;
if (SMTD.StreamedMessageReadByEncoderIsEnabled())
{
SMTD.StreamedMessageReadByEncoder(EventTraceActivityHelper.TryExtractActivity(message, true));
}
if (MessageLogger.LogMessagesAtTransportLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive);
}
return message;
}
public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
}
if (bufferManager == null)
{
throw TraceUtility.ThrowHelperError(new ArgumentNullException("bufferManager"), message);
}
if (maxMessageSize < 0)
{
throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxMessageSize", maxMessageSize,
SR2.GetString(SR2.ValueMustBeNonNegative)), message);
}
if (messageOffset < 0 || messageOffset > maxMessageSize)
{
throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("messageOffset", messageOffset,
SR2.GetString(SR2.JsonValueMustBeInRange, 0, maxMessageSize)), message);
}
EventTraceActivity eventTraceActivity = null;
if (WebTD.JsonMessageEncodingStartIsEnabled())
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
WebTD.JsonMessageEncodingStart(eventTraceActivity);
}
ThrowIfMismatchedMessageVersion(message);
message.Properties.Encoder = this;
JsonBufferedMessageWriter messageWriter = TakeBufferedWriter();
JavascriptCallbackResponseMessageProperty javascriptResponseMessageProperty;
if (message.Properties.TryGetValue<JavascriptCallbackResponseMessageProperty>(JavascriptCallbackResponseMessageProperty.Name, out javascriptResponseMessageProperty) &&
javascriptResponseMessageProperty != null)
{
if (this.crossDomainScriptAccessEnabled)
{
messageWriter.SetJavascriptCallbackProperty(javascriptResponseMessageProperty);
}
else
{
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR2.JavascriptCallbackNotEnabled), message);
}
}
ArraySegment<byte> messageData = messageWriter.WriteMessage(message, bufferManager, messageOffset, maxMessageSize);
ReturnMessageWriter(messageWriter);
if (SMTD.MessageWrittenByEncoderIsEnabled() && messageData != null)
{
SMTD.MessageWrittenByEncoder(
eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message),
messageData.Count,
this);
}
if (MessageLogger.LogMessagesAtTransportLevel)
{
XmlDictionaryReader xmlDictionaryReader = JsonReaderWriterFactory.CreateJsonReader(
messageData.Array, messageData.Offset, messageData.Count, null, XmlDictionaryReaderQuotas.Max, null);
MessageLogger.LogMessage(ref message, xmlDictionaryReader, MessageLoggingSource.TransportSend);
}
return messageData;
}
public override void WriteMessage(Message message, Stream stream)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
}
if (stream == null)
{
throw TraceUtility.ThrowHelperError(new ArgumentNullException("stream"), message);
}
ThrowIfMismatchedMessageVersion(message);
EventTraceActivity eventTraceActivity = null;
if (WebTD.JsonMessageEncodingStartIsEnabled())
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
WebTD.JsonMessageEncodingStart(eventTraceActivity);
}
message.Properties.Encoder = this;
XmlDictionaryWriter xmlWriter = TakeStreamedWriter(stream);
JavascriptCallbackResponseMessageProperty javascriptResponseMessageProperty;
if (message.Properties.TryGetValue<JavascriptCallbackResponseMessageProperty>(JavascriptCallbackResponseMessageProperty.Name, out javascriptResponseMessageProperty)
&& javascriptResponseMessageProperty != null
&& !String.IsNullOrEmpty(javascriptResponseMessageProperty.CallbackFunctionName))
{
if (!this.crossDomainScriptAccessEnabled)
{
throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR2.JavascriptCallbackNotEnabled), message);
}
byte[] buffer = this.writeEncoding.GetBytes(String.Format(CultureInfo.InvariantCulture, "{0}(", javascriptResponseMessageProperty.CallbackFunctionName));
stream.Write(buffer, 0, buffer.Length);
}
xmlWriter.WriteStartDocument();
message.WriteMessage(xmlWriter);
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
ReturnStreamedWriter(xmlWriter);
if (javascriptResponseMessageProperty != null
&& !String.IsNullOrEmpty(javascriptResponseMessageProperty.CallbackFunctionName))
{
if (javascriptResponseMessageProperty.StatusCode != null && (int)javascriptResponseMessageProperty.StatusCode != 200)
{
byte[] buffer = this.writeEncoding.GetBytes(String.Format(CultureInfo.InvariantCulture, ",{0}", (int)javascriptResponseMessageProperty.StatusCode));
stream.Write(buffer, 0, buffer.Length);
}
stream.Write(this.encodedClosingFunctionCall, 0, this.encodedClosingFunctionCall.Length);
}
if (SMTD.StreamedMessageWrittenByEncoderIsEnabled())
{
SMTD.StreamedMessageWrittenByEncoder(
eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message));
}
if (MessageLogger.LogMessagesAtTransportLevel)
{
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportSend);
}
}
internal override bool IsCharSetSupported(string charSet)
{
Encoding tmp;
return TextEncoderDefaults.TryGetEncoding(charSet, out tmp);
}
bool IsJsonContentType(string contentType)
{
return IsContentTypeSupported(contentType, JsonGlobals.applicationJsonMediaType, JsonGlobals.applicationJsonMediaType) || IsContentTypeSupported(contentType, JsonGlobals.textJsonMediaType, JsonGlobals.textJsonMediaType);
}
void ReturnBufferedData(JsonBufferedMessageData messageData)
{
bufferedReaderPool.Return(messageData);
}
void ReturnMessageWriter(JsonBufferedMessageWriter messageWriter)
{
bufferedWriterPool.Return(messageWriter);
}
void ReturnStreamedReader(XmlDictionaryReader xmlReader)
{
streamedReaderPool.Return(xmlReader);
}
void ReturnStreamedWriter(XmlWriter xmlWriter)
{
xmlWriter.Close();
streamedWriterPool.Return((XmlDictionaryWriter)xmlWriter);
}
JsonBufferedMessageData TakeBufferedReader()
{
if (bufferedReaderPool == null)
{
lock (ThisLock)
{
if (bufferedReaderPool == null)
{
bufferedReaderPool = new SynchronizedPool<JsonBufferedMessageData>(maxReadPoolSize);
}
}
}
JsonBufferedMessageData messageData = bufferedReaderPool.Take();
if (messageData == null)
{
messageData = new JsonBufferedMessageData(this, maxPooledXmlReadersPerMessage);
}
return messageData;
}
JsonBufferedMessageWriter TakeBufferedWriter()
{
if (bufferedWriterPool == null)
{
lock (ThisLock)
{
if (bufferedWriterPool == null)
{
bufferedWriterPool = new SynchronizedPool<JsonBufferedMessageWriter>(maxWritePoolSize);
}
}
}
JsonBufferedMessageWriter messageWriter = bufferedWriterPool.Take();
if (messageWriter == null)
{
messageWriter = new JsonBufferedMessageWriter(this);
}
return messageWriter;
}
XmlDictionaryReader TakeStreamedReader(Stream stream, Encoding enc)
{
if (streamedReaderPool == null)
{
lock (ThisLock)
{
if (streamedReaderPool == null)
{
streamedReaderPool = new SynchronizedPool<XmlDictionaryReader>(maxReadPoolSize);
}
}
}
XmlDictionaryReader xmlReader = streamedReaderPool.Take();
if (xmlReader == null)
{
xmlReader = JsonReaderWriterFactory.CreateJsonReader(stream, enc, this.readerQuotas, this.onStreamedReaderClose);
}
else
{
((IXmlJsonReaderInitializer)xmlReader).SetInput(stream, enc, this.readerQuotas, this.onStreamedReaderClose);
}
return xmlReader;
}
XmlDictionaryWriter TakeStreamedWriter(Stream stream)
{
if (streamedWriterPool == null)
{
lock (ThisLock)
{
if (streamedWriterPool == null)
{
streamedWriterPool = new SynchronizedPool<XmlDictionaryWriter>(maxWritePoolSize);
}
}
}
XmlDictionaryWriter xmlWriter = streamedWriterPool.Take();
if (xmlWriter == null)
{
xmlWriter = JsonReaderWriterFactory.CreateJsonWriter(stream, this.writeEncoding, false);
}
else
{
((IXmlJsonWriterInitializer)xmlWriter).SetOutput(stream, this.writeEncoding, false);
}
return xmlWriter;
}
class JsonBufferedMessageData : BufferedMessageData
{
Encoding encoding;
JsonMessageEncoder messageEncoder;
OnXmlDictionaryReaderClose onClose;
Pool<XmlDictionaryReader> readerPool;
public JsonBufferedMessageData(JsonMessageEncoder messageEncoder, int maxReaderPoolSize)
: base(messageEncoder.RecycledStatePool)
{
this.messageEncoder = messageEncoder;
readerPool = new Pool<XmlDictionaryReader>(maxReaderPoolSize);
onClose = new OnXmlDictionaryReaderClose(OnXmlReaderClosed);
}
public override MessageEncoder MessageEncoder
{
get { return messageEncoder; }
}
public override XmlDictionaryReaderQuotas Quotas
{
get { return messageEncoder.bufferedReadReaderQuotas; }
}
internal Encoding Encoding
{
set
{
this.encoding = value;
}
}
protected override void OnClosed()
{
messageEncoder.ReturnBufferedData(this);
}
protected override void ReturnXmlReader(XmlDictionaryReader xmlReader)
{
if (xmlReader != null)
{
readerPool.Return(xmlReader);
}
}
protected override XmlDictionaryReader TakeXmlReader()
{
ArraySegment<byte> buffer = this.Buffer;
XmlDictionaryReader xmlReader = readerPool.Take();
if (xmlReader == null)
{
xmlReader = JsonReaderWriterFactory.CreateJsonReader(buffer.Array, buffer.Offset, buffer.Count, this.encoding, this.Quotas, onClose);
}
else
{
((IXmlJsonReaderInitializer)xmlReader).SetInput(buffer.Array, buffer.Offset, buffer.Count, this.encoding, this.Quotas, onClose);
}
return xmlReader;
}
}
class JsonBufferedMessageWriter : BufferedMessageWriter
{
JsonMessageEncoder messageEncoder;
XmlDictionaryWriter returnedWriter;
JavascriptXmlWriterWrapper javascriptWrapper;
public JsonBufferedMessageWriter(JsonMessageEncoder messageEncoder)
{
this.messageEncoder = messageEncoder;
}
public void SetJavascriptCallbackProperty(JavascriptCallbackResponseMessageProperty javascriptResponseMessageProperty)
{
if (this.javascriptWrapper == null)
{
this.javascriptWrapper = new JavascriptXmlWriterWrapper(this.messageEncoder.writeEncoding)
{
JavascriptResponseMessageProperty = javascriptResponseMessageProperty
};
}
else
{
this.javascriptWrapper.JavascriptResponseMessageProperty = javascriptResponseMessageProperty;
}
}
protected override void OnWriteEndMessage(XmlDictionaryWriter writer)
{
writer.WriteEndDocument();
}
protected override void OnWriteStartMessage(XmlDictionaryWriter writer)
{
writer.WriteStartDocument();
}
protected override void ReturnXmlWriter(XmlDictionaryWriter writer)
{
writer.Close();
if (writer is JavascriptXmlWriterWrapper)
{
if (this.javascriptWrapper == null)
{
this.javascriptWrapper = (JavascriptXmlWriterWrapper)writer;
this.javascriptWrapper.JavascriptResponseMessageProperty = null;
writer = this.javascriptWrapper.XmlJsonWriter;
}
}
if (this.returnedWriter == null)
{
this.returnedWriter = writer;
}
}
protected override XmlDictionaryWriter TakeXmlWriter(Stream stream)
{
XmlDictionaryWriter writer = null;
if (this.returnedWriter == null)
{
writer = JsonReaderWriterFactory.CreateJsonWriter(stream, messageEncoder.writeEncoding, false);
}
else
{
writer = this.returnedWriter;
((IXmlJsonWriterInitializer)writer).SetOutput(stream, messageEncoder.writeEncoding, false);
this.returnedWriter = null;
}
if (this.javascriptWrapper != null && this.javascriptWrapper.JavascriptResponseMessageProperty != null)
{
this.javascriptWrapper.SetOutput(stream, writer);
writer = this.javascriptWrapper;
this.javascriptWrapper = null;
}
return writer;
}
}
}
}
}
| |
// 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 0.12.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.MirrorPrimitives
{
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>
/// Some cool documentation.
/// </summary>
public partial class SwaggerDataTypesClient : ServiceClient<SwaggerDataTypesClient>, ISwaggerDataTypesClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the SwaggerDataTypesClient class.
/// </summary>
public SwaggerDataTypesClient() : base()
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerDataTypesClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SwaggerDataTypesClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerDataTypesClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SwaggerDataTypesClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerDataTypesClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SwaggerDataTypesClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new Uri("http://localhost:3000/");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
}
/// <summary>
/// Product Types
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Product>> GetProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "GetProduct", tracingParameters);
}
// Construct URL
var baseUrl = this.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("GET");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (responseCode != null)
{
if (httpRequest.Headers.Contains("response-code"))
{
httpRequest.Headers.Remove("response-code");
}
httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode);
}
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 = JsonConvert.SerializeObject(product, this.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<Product>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Product>(responseContent, this.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Product Types
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Product>> PutProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PutProduct", tracingParameters);
}
// Construct URL
var baseUrl = this.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PUT");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (responseCode != null)
{
if (httpRequest.Headers.Contains("response-code"))
{
httpRequest.Headers.Remove("response-code");
}
httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode);
}
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 = JsonConvert.SerializeObject(product, this.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<Product>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Product>(responseContent, this.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Product Types
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Product>> PostProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PostProduct", tracingParameters);
}
// Construct URL
var baseUrl = this.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("POST");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (responseCode != null)
{
if (httpRequest.Headers.Contains("response-code"))
{
httpRequest.Headers.Remove("response-code");
}
httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode);
}
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 = JsonConvert.SerializeObject(product, this.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<Product>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Product>(responseContent, this.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <summary>
/// Product Types
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<HttpOperationResponse<Product>> PatchProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "PatchProduct", tracingParameters);
}
// Construct URL
var baseUrl = this.BaseUri.AbsoluteUri;
var url = new Uri(new Uri(baseUrl + (baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString();
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("PATCH");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (responseCode != null)
{
if (httpRequest.Headers.Contains("response-code"))
{
httpRequest.Headers.Remove("response-code");
}
httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode);
}
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 = JsonConvert.SerializeObject(product, this.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<Product>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Product>(responseContent, this.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Diagnostics;
using System.IO.Pipelines;
using System.Net.Http;
using System.Net.Http.QPack;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http3
{
internal abstract partial class Http3Stream : HttpProtocol, IHttp3Stream, IHttpHeadersHandler, IThreadPoolWorkItem
{
private static ReadOnlySpan<byte> AuthorityBytes => new byte[10] { (byte)':', (byte)'a', (byte)'u', (byte)'t', (byte)'h', (byte)'o', (byte)'r', (byte)'i', (byte)'t', (byte)'y' };
private static ReadOnlySpan<byte> MethodBytes => new byte[7] { (byte)':', (byte)'m', (byte)'e', (byte)'t', (byte)'h', (byte)'o', (byte)'d' };
private static ReadOnlySpan<byte> PathBytes => new byte[5] { (byte)':', (byte)'p', (byte)'a', (byte)'t', (byte)'h' };
private static ReadOnlySpan<byte> SchemeBytes => new byte[7] { (byte)':', (byte)'s', (byte)'c', (byte)'h', (byte)'e', (byte)'m', (byte)'e' };
private static ReadOnlySpan<byte> StatusBytes => new byte[7] { (byte)':', (byte)'s', (byte)'t', (byte)'a', (byte)'t', (byte)'u', (byte)'s' };
private static ReadOnlySpan<byte> ConnectionBytes => new byte[10] { (byte)'c', (byte)'o', (byte)'n', (byte)'n', (byte)'e', (byte)'c', (byte)'t', (byte)'i', (byte)'o', (byte)'n' };
private static ReadOnlySpan<byte> TeBytes => new byte[2] { (byte)'t', (byte)'e' };
private static ReadOnlySpan<byte> TrailersBytes => new byte[8] { (byte)'t', (byte)'r', (byte)'a', (byte)'i', (byte)'l', (byte)'e', (byte)'r', (byte)'s' };
private static ReadOnlySpan<byte> ConnectBytes => new byte[7] { (byte)'C', (byte)'O', (byte)'N', (byte)'N', (byte)'E', (byte)'C', (byte)'T' };
private const PseudoHeaderFields _mandatoryRequestPseudoHeaderFields =
PseudoHeaderFields.Method | PseudoHeaderFields.Path | PseudoHeaderFields.Scheme;
private Http3FrameWriter _frameWriter = default!;
private Http3OutputProducer _http3Output = default!;
private Http3StreamContext _context = default!;
private IProtocolErrorCodeFeature _errorCodeFeature = default!;
private IStreamIdFeature _streamIdFeature = default!;
private IStreamAbortFeature _streamAbortFeature = default!;
private int _isClosed;
private readonly Http3RawFrame _incomingFrame = new Http3RawFrame();
protected RequestHeaderParsingState _requestHeaderParsingState;
private PseudoHeaderFields _parsedPseudoHeaderFields;
private int _totalParsedHeaderSize;
private bool _isMethodConnect;
// TODO: Change to resetable ValueTask source
private TaskCompletionSource? _appCompleted;
private StreamCompletionFlags _completionState;
private readonly object _completionLock = new object();
public bool EndStreamReceived => (_completionState & StreamCompletionFlags.EndStreamReceived) == StreamCompletionFlags.EndStreamReceived;
private bool IsAborted => (_completionState & StreamCompletionFlags.Aborted) == StreamCompletionFlags.Aborted;
private bool IsCompleted => (_completionState & StreamCompletionFlags.Completed) == StreamCompletionFlags.Completed;
public Pipe RequestBodyPipe { get; private set; } = default!;
public long? InputRemaining { get; internal set; }
public QPackDecoder QPackDecoder { get; private set; } = default!;
public PipeReader Input => _context.Transport.Input;
public ISystemClock SystemClock => _context.ServiceContext.SystemClock;
public KestrelServerLimits Limits => _context.ServiceContext.ServerOptions.Limits;
public long StreamId => _streamIdFeature.StreamId;
public long StreamTimeoutTicks { get; set; }
public bool IsReceivingHeader => _appCompleted == null; // TCS is assigned once headers are received
public bool IsDraining => _appCompleted?.Task.IsCompleted ?? false; // Draining starts once app is complete
public bool IsRequestStream => true;
public void Initialize(Http3StreamContext context)
{
base.Initialize(context);
InputRemaining = null;
_context = context;
_errorCodeFeature = _context.ConnectionFeatures.Get<IProtocolErrorCodeFeature>()!;
_streamIdFeature = _context.ConnectionFeatures.Get<IStreamIdFeature>()!;
_streamAbortFeature = _context.ConnectionFeatures.Get<IStreamAbortFeature>()!;
_appCompleted = null;
_isClosed = 0;
_requestHeaderParsingState = default;
_parsedPseudoHeaderFields = default;
_totalParsedHeaderSize = 0;
_isMethodConnect = false;
_completionState = default;
StreamTimeoutTicks = 0;
if (_frameWriter == null)
{
_frameWriter = new Http3FrameWriter(
context.StreamContext,
context.TimeoutControl,
context.ServiceContext.ServerOptions.Limits.MinResponseDataRate,
context.MemoryPool,
context.ServiceContext.Log,
_streamIdFeature,
context.ClientPeerSettings,
this);
_http3Output = new Http3OutputProducer(
_frameWriter,
context.MemoryPool,
this,
context.ServiceContext.Log);
Output = _http3Output;
RequestBodyPipe = CreateRequestBodyPipe(64 * 1024); // windowSize?
QPackDecoder = new QPackDecoder(_context.ServiceContext.ServerOptions.Limits.Http3.MaxRequestHeaderFieldSize);
}
else
{
_http3Output.StreamReset();
RequestBodyPipe.Reset();
QPackDecoder.Reset();
}
_frameWriter.Reset(context.Transport.Output, context.ConnectionId);
}
public void InitializeWithExistingContext(IDuplexPipe transport)
{
_context.Transport = transport;
Initialize(_context);
}
public void Abort(ConnectionAbortedException abortReason, Http3ErrorCode errorCode)
{
AbortCore(abortReason, errorCode);
}
private void AbortCore(Exception exception, Http3ErrorCode errorCode)
{
lock (_completionLock)
{
if (IsCompleted)
{
return;
}
var (oldState, newState) = ApplyCompletionFlag(StreamCompletionFlags.Aborted);
if (oldState == newState)
{
return;
}
if (!(exception is ConnectionAbortedException abortReason))
{
abortReason = new ConnectionAbortedException(exception.Message, exception);
}
Log.Http3StreamAbort(TraceIdentifier, errorCode, abortReason);
// Call _http3Output.Stop() prior to poisoning the request body stream or pipe to
// ensure that an app that completes early due to the abort doesn't result in header frames being sent.
_http3Output.Stop();
CancelRequestAbortedToken();
// Unblock the request body.
PoisonBody(exception);
RequestBodyPipe.Writer.Complete(exception);
// Abort framewriter and underlying transport after stopping output.
_errorCodeFeature.Error = (long)errorCode;
_frameWriter.Abort(abortReason);
}
}
protected override void OnErrorAfterResponseStarted()
{
// We can no longer change the response, send a Reset instead.
var abortReason = new ConnectionAbortedException(CoreStrings.Http3StreamErrorAfterHeaders);
Abort(abortReason, Http3ErrorCode.InternalError);
}
public void OnHeadersComplete(bool endStream)
{
OnHeadersComplete();
}
public void OnStaticIndexedHeader(int index)
{
var knownHeader = H3StaticTable.GetHeaderFieldAt(index);
OnHeader(knownHeader.Name, knownHeader.Value);
}
public void OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value)
{
var knownHeader = H3StaticTable.GetHeaderFieldAt(index);
OnHeader(knownHeader.Name, value);
}
public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) => OnHeader(name, value, checkForNewlineChars : true);
public override void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value, bool checkForNewlineChars)
{
// https://tools.ietf.org/html/rfc7540#section-6.5.2
// "The value is based on the uncompressed size of header fields, including the length of the name and value in octets plus an overhead of 32 octets for each header field.";
_totalParsedHeaderSize += HeaderField.RfcOverhead + name.Length + value.Length;
if (_totalParsedHeaderSize > _context.ServiceContext.ServerOptions.Limits.MaxRequestHeadersTotalSize)
{
throw new Http3StreamErrorException(CoreStrings.BadRequest_HeadersExceedMaxTotalSize, Http3ErrorCode.RequestRejected);
}
ValidateHeader(name, value);
try
{
if (_requestHeaderParsingState == RequestHeaderParsingState.Trailers)
{
OnTrailer(name, value);
}
else
{
// Throws BadRequest for header count limit breaches.
// Throws InvalidOperation for bad encoding.
base.OnHeader(name, value, checkForNewlineChars);
}
}
catch (Microsoft.AspNetCore.Http.BadHttpRequestException bre)
{
throw new Http3StreamErrorException(bre.Message, Http3ErrorCode.MessageError);
}
catch (InvalidOperationException)
{
throw new Http3StreamErrorException(CoreStrings.BadRequest_MalformedRequestInvalidHeaders, Http3ErrorCode.MessageError);
}
}
private void ValidateHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
{
// http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.1
/*
Intermediaries that process HTTP requests or responses
(i.e., any intermediary not acting as a tunnel) MUST NOT forward a
malformed request or response. Malformed requests or responses that
are detected MUST be treated as a stream error of type H3_MESSAGE_ERROR.
For malformed requests, a server MAY send an HTTP response prior to
closing or resetting the stream. Clients MUST NOT accept a malformed
response. Note that these requirements are intended to protect
against several types of common attacks against HTTP; they are
deliberately strict because being permissive can expose
implementations to these vulnerabilities.*/
if (IsPseudoHeaderField(name, out var headerField))
{
if (_requestHeaderParsingState == RequestHeaderParsingState.Headers)
{
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1.1.1-4
// All pseudo-header fields MUST appear in the header block before regular header fields.
// Any request or response that contains a pseudo-header field that appears in a header
// block after a regular header field MUST be treated as malformed.
throw new Http3StreamErrorException(CoreStrings.HttpErrorPseudoHeaderFieldAfterRegularHeaders, Http3ErrorCode.MessageError);
}
if (_requestHeaderParsingState == RequestHeaderParsingState.Trailers)
{
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1.1.1-3
// Pseudo-header fields MUST NOT appear in trailers.
throw new Http3StreamErrorException(CoreStrings.HttpErrorTrailersContainPseudoHeaderField, Http3ErrorCode.MessageError);
}
_requestHeaderParsingState = RequestHeaderParsingState.PseudoHeaderFields;
if (headerField == PseudoHeaderFields.Unknown)
{
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1.1.1-3
// Endpoints MUST treat a request or response that contains undefined or invalid pseudo-header
// fields as malformed.
throw new Http3StreamErrorException(CoreStrings.HttpErrorUnknownPseudoHeaderField, Http3ErrorCode.MessageError);
}
if (headerField == PseudoHeaderFields.Status)
{
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1.1.1-3
// Pseudo-header fields defined for requests MUST NOT appear in responses; pseudo-header fields
// defined for responses MUST NOT appear in requests.
throw new Http3StreamErrorException(CoreStrings.HttpErrorResponsePseudoHeaderField, Http3ErrorCode.MessageError);
}
if ((_parsedPseudoHeaderFields & headerField) == headerField)
{
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1.1.1-7
// All HTTP/3 requests MUST include exactly one valid value for the :method, :scheme, and :path pseudo-header fields
throw new Http3StreamErrorException(CoreStrings.HttpErrorDuplicatePseudoHeaderField, Http3ErrorCode.MessageError);
}
if (headerField == PseudoHeaderFields.Method)
{
_isMethodConnect = value.SequenceEqual(ConnectBytes);
}
_parsedPseudoHeaderFields |= headerField;
}
else if (_requestHeaderParsingState != RequestHeaderParsingState.Trailers)
{
_requestHeaderParsingState = RequestHeaderParsingState.Headers;
}
if (IsConnectionSpecificHeaderField(name, value))
{
throw new Http3StreamErrorException(CoreStrings.HttpErrorConnectionSpecificHeaderField, Http3ErrorCode.MessageError);
}
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1.1-3
// A request or response containing uppercase header field names MUST be treated as malformed.
for (var i = 0; i < name.Length; i++)
{
if (name[i] >= 65 && name[i] <= 90)
{
if (_requestHeaderParsingState == RequestHeaderParsingState.Trailers)
{
throw new Http3StreamErrorException(CoreStrings.HttpErrorTrailerNameUppercase, Http3ErrorCode.MessageError);
}
else
{
throw new Http3StreamErrorException(CoreStrings.HttpErrorHeaderNameUppercase, Http3ErrorCode.MessageError);
}
}
}
}
private static bool IsPseudoHeaderField(ReadOnlySpan<byte> name, out PseudoHeaderFields headerField)
{
headerField = PseudoHeaderFields.None;
if (name.IsEmpty || name[0] != (byte)':')
{
return false;
}
if (name.SequenceEqual(PathBytes))
{
headerField = PseudoHeaderFields.Path;
}
else if (name.SequenceEqual(MethodBytes))
{
headerField = PseudoHeaderFields.Method;
}
else if (name.SequenceEqual(SchemeBytes))
{
headerField = PseudoHeaderFields.Scheme;
}
else if (name.SequenceEqual(StatusBytes))
{
headerField = PseudoHeaderFields.Status;
}
else if (name.SequenceEqual(AuthorityBytes))
{
headerField = PseudoHeaderFields.Authority;
}
else
{
headerField = PseudoHeaderFields.Unknown;
}
return true;
}
private static bool IsConnectionSpecificHeaderField(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
{
return name.SequenceEqual(ConnectionBytes) || (name.SequenceEqual(TeBytes) && !value.SequenceEqual(TrailersBytes));
}
protected override void OnRequestProcessingEnded()
{
CompleteStream(errored: false);
}
private void CompleteStream(bool errored)
{
if (!EndStreamReceived)
{
if (!errored)
{
Log.RequestBodyNotEntirelyRead(ConnectionIdFeature, TraceIdentifier);
}
var (oldState, newState) = ApplyCompletionFlag(StreamCompletionFlags.AbortedRead);
if (oldState != newState)
{
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1-15
// When the server does not need to receive the remainder of the request, it MAY abort reading
// the request stream, send a complete response, and cleanly close the sending part of the stream.
// The error code H3_NO_ERROR SHOULD be used when requesting that the client stop sending on the
// request stream.
_streamAbortFeature.AbortRead((long)Http3ErrorCode.NoError, new ConnectionAbortedException("The application completed without reading the entire request body."));
RequestBodyPipe.Writer.Complete();
}
TryClose();
}
// Stream will be pooled after app completed.
// Wait to signal app completed after any potential aborts on the stream.
Debug.Assert(_appCompleted != null);
_appCompleted.SetResult();
}
private bool TryClose()
{
if (Interlocked.Exchange(ref _isClosed, 1) == 0)
{
// Wake ProcessRequestAsync loop so that it can exit.
Input.CancelPendingRead();
return true;
}
return false;
}
public async Task ProcessRequestAsync<TContext>(IHttpApplication<TContext> application) where TContext : notnull
{
Exception? error = null;
try
{
while (_isClosed == 0)
{
var result = await Input.ReadAsync();
var readableBuffer = result.Buffer;
var consumed = readableBuffer.Start;
var examined = readableBuffer.End;
try
{
if (!readableBuffer.IsEmpty)
{
while (Http3FrameReader.TryReadFrame(ref readableBuffer, _incomingFrame, out var framePayload))
{
Log.Http3FrameReceived(ConnectionId, _streamIdFeature.StreamId, _incomingFrame);
consumed = examined = framePayload.End;
await ProcessHttp3Stream(application, framePayload, result.IsCompleted && readableBuffer.IsEmpty);
}
}
if (result.IsCompleted)
{
await OnEndStreamReceived();
return;
}
}
finally
{
Input.AdvanceTo(consumed, examined);
}
}
}
catch (Http3StreamErrorException ex)
{
error = ex;
Abort(new ConnectionAbortedException(ex.Message, ex), ex.ErrorCode);
}
catch (Http3ConnectionErrorException ex)
{
error = ex;
_errorCodeFeature.Error = (long)ex.ErrorCode;
_context.StreamLifetimeHandler.OnStreamConnectionError(ex);
}
catch (ConnectionAbortedException ex)
{
error = ex;
}
catch (ConnectionResetException ex)
{
error = ex;
var resolvedErrorCode = _errorCodeFeature.Error >= 0 ? _errorCodeFeature.Error : 0;
AbortCore(new IOException(CoreStrings.HttpStreamResetByClient, ex), (Http3ErrorCode)resolvedErrorCode);
}
catch (Exception ex)
{
error = ex;
Log.LogWarning(0, ex, "Stream threw an unexpected exception.");
}
finally
{
var streamError = error as ConnectionAbortedException
?? new ConnectionAbortedException("The stream has completed.", error!);
await Input.CompleteAsync();
var appCompleted = _appCompleted?.Task ?? Task.CompletedTask;
if (!appCompleted.IsCompletedSuccessfully)
{
// At this point in the stream's read-side is complete. However, with HTTP/3
// the write-side of the stream can still be aborted by the client on request
// aborted.
//
// To get notification of request aborted we register to connection closed
// token. It will notify this type that the client has aborted the request
// and Kestrel will complete pipes and cancel the RequestAborted token.
//
// Only subscribe to this event after the stream's read-side is complete to
// avoid interactions between reading that is in-progress and an abort.
// This means while reading, read-side abort will handle getting abort notifications.
//
// We don't need to hang on to the CancellationTokenRegistration from register.
// The CTS is cleaned up in StreamContext.DisposeAsync.
//
// TODO: Consider a better way to provide this notification. For perf we want to
// make the ConnectionClosed CTS pay-for-play, and change this event to use
// something that is more lightweight than a CTS.
_context.StreamContext.ConnectionClosed.Register(static s =>
{
var stream = (Http3Stream)s!;
if (!stream.IsCompleted)
{
// An error code value other than -1 indicates a value was set and the request didn't gracefully complete.
var errorCode = stream._errorCodeFeature.Error;
if (errorCode >= 0)
{
stream.AbortCore(new IOException(CoreStrings.HttpStreamResetByClient), (Http3ErrorCode)errorCode);
}
}
}, this);
// Make sure application func is completed before completing writer.
await appCompleted;
}
try
{
await _frameWriter.CompleteAsync();
}
catch
{
Abort(streamError, Http3ErrorCode.ProtocolError);
throw;
}
finally
{
// Drain transports and dispose.
await _context.StreamContext.DisposeAsync();
// Tells the connection to remove the stream from its active collection.
ApplyCompletionFlag(StreamCompletionFlags.Completed);
_context.StreamLifetimeHandler.OnStreamCompleted(this);
// TODO this is a hack for .NET 6 pooling.
//
// Pooling needs to happen after transports have been drained and stream
// has been completed and is no longer active. All of this logic can't
// be placed in ConnectionContext.DisposeAsync. Instead, QuicStreamContext
// has pooling happen in QuicStreamContext.Dispose.
//
// ConnectionContext only implements IDisposableAsync by default. Only
// QuicStreamContext should pass this check.
if (_context.StreamContext is IDisposable disposableStream)
{
disposableStream.Dispose();
}
}
}
}
private ValueTask OnEndStreamReceived()
{
ApplyCompletionFlag(StreamCompletionFlags.EndStreamReceived);
if (_requestHeaderParsingState == RequestHeaderParsingState.Ready)
{
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1-14
// Request stream ended without headers received. Unable to provide response.
throw new Http3StreamErrorException(CoreStrings.Http3StreamErrorRequestEndedNoHeaders, Http3ErrorCode.RequestIncomplete);
}
if (InputRemaining.HasValue)
{
// https://tools.ietf.org/html/rfc7540#section-8.1.2.6
if (InputRemaining.Value != 0)
{
throw new Http3StreamErrorException(CoreStrings.Http3StreamErrorLessDataThanLength, Http3ErrorCode.ProtocolError);
}
}
OnTrailersComplete();
return RequestBodyPipe.Writer.CompleteAsync();
}
private Task ProcessHttp3Stream<TContext>(IHttpApplication<TContext> application, in ReadOnlySequence<byte> payload, bool isCompleted) where TContext : notnull
{
switch (_incomingFrame.Type)
{
case Http3FrameType.Data:
return ProcessDataFrameAsync(payload);
case Http3FrameType.Headers:
return ProcessHeadersFrameAsync(application, payload, isCompleted);
case Http3FrameType.Settings:
case Http3FrameType.CancelPush:
case Http3FrameType.GoAway:
case Http3FrameType.MaxPushId:
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-7.2.4
// These frames need to be on a control stream
throw new Http3ConnectionErrorException(CoreStrings.FormatHttp3ErrorUnsupportedFrameOnRequestStream(_incomingFrame.FormattedType), Http3ErrorCode.UnexpectedFrame);
case Http3FrameType.PushPromise:
// The server should never receive push promise
throw new Http3ConnectionErrorException(CoreStrings.FormatHttp3ErrorUnsupportedFrameOnServer(_incomingFrame.FormattedType), Http3ErrorCode.UnexpectedFrame);
default:
return ProcessUnknownFrameAsync();
}
}
private static Task ProcessUnknownFrameAsync()
{
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-9
// Unknown frames must be explicitly ignored.
return Task.CompletedTask;
}
private async Task ProcessHeadersFrameAsync<TContext>(IHttpApplication<TContext> application, ReadOnlySequence<byte> payload, bool isCompleted) where TContext : notnull
{
// HEADERS frame after trailing headers is invalid.
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1
if (_requestHeaderParsingState == RequestHeaderParsingState.Trailers)
{
throw new Http3ConnectionErrorException(CoreStrings.FormatHttp3StreamErrorFrameReceivedAfterTrailers(Http3Formatting.ToFormattedType(Http3FrameType.Headers)), Http3ErrorCode.UnexpectedFrame);
}
if (_requestHeaderParsingState == RequestHeaderParsingState.Headers)
{
_requestHeaderParsingState = RequestHeaderParsingState.Trailers;
}
try
{
QPackDecoder.Decode(payload, handler: this);
QPackDecoder.Reset();
}
catch (QPackDecodingException ex)
{
Log.QPackDecodingError(ConnectionId, StreamId, ex);
throw new Http3StreamErrorException(ex.Message, Http3ErrorCode.InternalError);
}
switch (_requestHeaderParsingState)
{
case RequestHeaderParsingState.Ready:
case RequestHeaderParsingState.PseudoHeaderFields:
_requestHeaderParsingState = RequestHeaderParsingState.Headers;
break;
case RequestHeaderParsingState.Headers:
break;
case RequestHeaderParsingState.Trailers:
return;
default:
Debug.Fail("Unexpected header parsing state.");
break;
}
InputRemaining = HttpRequestHeaders.ContentLength;
// If the stream is complete after receiving the headers then run OnEndStreamReceived.
// If there is a bad content length then this will throw before the request delegate is called.
if (isCompleted)
{
await OnEndStreamReceived();
}
if (!_isMethodConnect && (_parsedPseudoHeaderFields & _mandatoryRequestPseudoHeaderFields) != _mandatoryRequestPseudoHeaderFields)
{
// All HTTP/3 requests MUST include exactly one valid value for the :method, :scheme, and :path pseudo-header
// fields, unless it is a CONNECT request. An HTTP request that omits mandatory pseudo-header
// fields is malformed.
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1.1.1
throw new Http3StreamErrorException(CoreStrings.HttpErrorMissingMandatoryPseudoHeaderFields, Http3ErrorCode.MessageError);
}
_appCompleted = new TaskCompletionSource();
StreamTimeoutTicks = default;
_context.StreamLifetimeHandler.OnStreamHeaderReceived(this);
ThreadPool.UnsafeQueueUserWorkItem(this, preferLocal: false);
}
private Task ProcessDataFrameAsync(in ReadOnlySequence<byte> payload)
{
// DATA frame before headers is invalid.
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1
if (_requestHeaderParsingState == RequestHeaderParsingState.Ready)
{
throw new Http3ConnectionErrorException(CoreStrings.Http3StreamErrorDataReceivedBeforeHeaders, Http3ErrorCode.UnexpectedFrame);
}
// DATA frame after trailing headers is invalid.
// https://quicwg.org/base-drafts/draft-ietf-quic-http.html#section-4.1
if (_requestHeaderParsingState == RequestHeaderParsingState.Trailers)
{
var message = CoreStrings.FormatHttp3StreamErrorFrameReceivedAfterTrailers(Http3Formatting.ToFormattedType(Http3FrameType.Data));
throw new Http3ConnectionErrorException(message, Http3ErrorCode.UnexpectedFrame);
}
if (InputRemaining.HasValue)
{
// https://tools.ietf.org/html/rfc7540#section-8.1.2.6
if (payload.Length > InputRemaining.Value)
{
throw new Http3StreamErrorException(CoreStrings.Http3StreamErrorMoreDataThanLength, Http3ErrorCode.ProtocolError);
}
InputRemaining -= payload.Length;
}
foreach (var segment in payload)
{
RequestBodyPipe.Writer.Write(segment.Span);
}
// TODO this can be better.
return RequestBodyPipe.Writer.FlushAsync().AsTask();
}
protected override void OnReset()
{
_keepAlive = true;
_connectionAborted = false;
_userTrailers = null;
// Reset Http3 Features
_currentIHttpMinRequestBodyDataRateFeature = this;
_currentIHttpResponseTrailersFeature = this;
_currentIHttpResetFeature = this;
}
protected override void ApplicationAbort() => ApplicationAbort(new ConnectionAbortedException(CoreStrings.ConnectionAbortedByApplication), Http3ErrorCode.InternalError);
private void ApplicationAbort(ConnectionAbortedException abortReason, Http3ErrorCode error)
{
Abort(abortReason, error);
}
protected override string CreateRequestId()
{
return _context.StreamContext.ConnectionId;
}
protected override MessageBody CreateMessageBody()
=> Http3MessageBody.For(this);
protected override bool TryParseRequest(ReadResult result, out bool endConnection)
{
endConnection = !TryValidatePseudoHeaders();
return true;
}
private bool TryValidatePseudoHeaders()
{
_httpVersion = Http.HttpVersion.Http3;
if (!TryValidateMethod())
{
return false;
}
if (!TryValidateAuthorityAndHost(out var hostText))
{
return false;
}
// CONNECT - :scheme and :path must be excluded
if (Method == Http.HttpMethod.Connect)
{
if (!string.IsNullOrEmpty(RequestHeaders[HeaderNames.Scheme]) || !string.IsNullOrEmpty(RequestHeaders[HeaderNames.Path]))
{
Abort(new ConnectionAbortedException(CoreStrings.Http3ErrorConnectMustNotSendSchemeOrPath), Http3ErrorCode.ProtocolError);
return false;
}
RawTarget = hostText;
return true;
}
// :scheme https://tools.ietf.org/html/rfc7540#section-8.1.2.3
// ":scheme" is not restricted to "http" and "https" schemed URIs. A
// proxy or gateway can translate requests for non - HTTP schemes,
// enabling the use of HTTP to interact with non - HTTP services.
var headerScheme = HttpRequestHeaders.HeaderScheme.ToString();
HttpRequestHeaders.HeaderScheme = default; // Suppress pseduo headers from the public headers collection.
if (!ReferenceEquals(headerScheme, Scheme) &&
!string.Equals(headerScheme, Scheme, StringComparison.OrdinalIgnoreCase))
{
if (!ServerOptions.AllowAlternateSchemes || !Uri.CheckSchemeName(headerScheme))
{
var str = CoreStrings.FormatHttp3StreamErrorSchemeMismatch(headerScheme, Scheme);
Abort(new ConnectionAbortedException(str), Http3ErrorCode.ProtocolError);
return false;
}
Scheme = headerScheme;
}
// :path (and query) - Required
// Must start with / except may be * for OPTIONS
var path = HttpRequestHeaders.HeaderPath.ToString();
HttpRequestHeaders.HeaderPath = default; // Suppress pseduo headers from the public headers collection.
RawTarget = path;
// OPTIONS - https://tools.ietf.org/html/rfc7540#section-8.1.2.3
// This pseudo-header field MUST NOT be empty for "http" or "https"
// URIs; "http" or "https" URIs that do not contain a path component
// MUST include a value of '/'. The exception to this rule is an
// OPTIONS request for an "http" or "https" URI that does not include
// a path component; these MUST include a ":path" pseudo-header field
// with a value of '*'.
if (Method == Http.HttpMethod.Options && path.Length == 1 && path[0] == '*')
{
// * is stored in RawTarget only since HttpRequest expects Path to be empty or start with a /.
Path = string.Empty;
QueryString = string.Empty;
return true;
}
// Approximate MaxRequestLineSize by totaling the required pseudo header field lengths.
var requestLineLength = _methodText!.Length + Scheme!.Length + hostText.Length + path.Length;
if (requestLineLength > ServerOptions.Limits.MaxRequestLineSize)
{
Abort(new ConnectionAbortedException(CoreStrings.BadRequest_RequestLineTooLong), Http3ErrorCode.RequestRejected);
return false;
}
var queryIndex = path.IndexOf('?');
QueryString = queryIndex == -1 ? string.Empty : path.Substring(queryIndex);
var pathSegment = queryIndex == -1 ? path.AsSpan() : path.AsSpan(0, queryIndex);
return TryValidatePath(pathSegment);
}
private bool TryValidateMethod()
{
// :method
_methodText = HttpRequestHeaders.HeaderMethod.ToString();
HttpRequestHeaders.HeaderMethod = default; // Suppress pseduo headers from the public headers collection.
Method = HttpUtilities.GetKnownMethod(_methodText);
if (Method == Http.HttpMethod.None)
{
Abort(new ConnectionAbortedException(CoreStrings.FormatHttp3ErrorMethodInvalid(_methodText)), Http3ErrorCode.ProtocolError);
return false;
}
if (Method == Http.HttpMethod.Custom)
{
if (HttpCharacters.IndexOfInvalidTokenChar(_methodText) >= 0)
{
Abort(new ConnectionAbortedException(CoreStrings.FormatHttp3ErrorMethodInvalid(_methodText)), Http3ErrorCode.ProtocolError);
return false;
}
}
return true;
}
private bool TryValidateAuthorityAndHost(out string hostText)
{
// :authority (optional)
// Prefer this over Host
var authority = HttpRequestHeaders.HeaderAuthority;
HttpRequestHeaders.HeaderAuthority = default; // Suppress pseduo headers from the public headers collection.
var host = HttpRequestHeaders.HeaderHost;
if (!StringValues.IsNullOrEmpty(authority))
{
// https://tools.ietf.org/html/rfc7540#section-8.1.2.3
// Clients that generate HTTP/2 requests directly SHOULD use the ":authority"
// pseudo - header field instead of the Host header field.
// An intermediary that converts an HTTP/2 request to HTTP/1.1 MUST
// create a Host header field if one is not present in a request by
// copying the value of the ":authority" pseudo - header field.
// We take this one step further, we don't want mismatched :authority
// and Host headers, replace Host if :authority is defined. The application
// will operate on the Host header.
HttpRequestHeaders.HeaderHost = authority;
host = authority;
}
// https://tools.ietf.org/html/rfc7230#section-5.4
// A server MUST respond with a 400 (Bad Request) status code to any
// HTTP/1.1 request message that lacks a Host header field and to any
// request message that contains more than one Host header field or a
// Host header field with an invalid field-value.
hostText = host.ToString();
if (host.Count > 1 || !HttpUtilities.IsHostHeaderValid(hostText))
{
// RST replaces 400
Abort(new ConnectionAbortedException(CoreStrings.FormatBadRequest_InvalidHostHeader_Detail(hostText)), Http3ErrorCode.ProtocolError);
return false;
}
return true;
}
[SkipLocalsInit]
private bool TryValidatePath(ReadOnlySpan<char> pathSegment)
{
// Must start with a leading slash
if (pathSegment.IsEmpty || pathSegment[0] != '/')
{
Abort(new ConnectionAbortedException(CoreStrings.FormatHttp3StreamErrorPathInvalid(RawTarget)), Http3ErrorCode.ProtocolError);
return false;
}
var pathEncoded = pathSegment.Contains('%');
// Compare with Http1Connection.OnOriginFormTarget
// URIs are always encoded/escaped to ASCII https://tools.ietf.org/html/rfc3986#page-11
// Multibyte Internationalized Resource Identifiers (IRIs) are first converted to utf8;
// then encoded/escaped to ASCII https://www.ietf.org/rfc/rfc3987.txt "Mapping of IRIs to URIs"
try
{
const int MaxPathBufferStackAllocSize = 256;
// The decoder operates only on raw bytes
Span<byte> pathBuffer = pathSegment.Length <= MaxPathBufferStackAllocSize
// A constant size plus slice generates better code
// https://github.com/dotnet/aspnetcore/pull/19273#discussion_r383159929
? stackalloc byte[MaxPathBufferStackAllocSize].Slice(0, pathSegment.Length)
// TODO - Consider pool here for less than 4096
// https://github.com/dotnet/aspnetcore/pull/19273#discussion_r383604184
: new byte[pathSegment.Length];
for (var i = 0; i < pathSegment.Length; i++)
{
var ch = pathSegment[i];
// The header parser should already be checking this
Debug.Assert(32 < ch && ch < 127);
pathBuffer[i] = (byte)ch;
}
Path = PathNormalizer.DecodePath(pathBuffer, pathEncoded, RawTarget!, QueryString!.Length);
return true;
}
catch (InvalidOperationException)
{
Abort(new ConnectionAbortedException(CoreStrings.FormatHttp3StreamErrorPathInvalid(RawTarget)), Http3ErrorCode.ProtocolError);
return false;
}
}
private Pipe CreateRequestBodyPipe(uint windowSize)
=> new Pipe(new PipeOptions
(
pool: _context.MemoryPool,
readerScheduler: ServiceContext.Scheduler,
writerScheduler: PipeScheduler.Inline,
// Never pause within the window range. Flow control will prevent more data from being added.
// See the assert in OnDataAsync.
pauseWriterThreshold: windowSize + 1,
resumeWriterThreshold: windowSize + 1,
useSynchronizationContext: false,
minimumSegmentSize: _context.MemoryPool.GetMinimumSegmentSize()
));
private (StreamCompletionFlags OldState, StreamCompletionFlags NewState) ApplyCompletionFlag(StreamCompletionFlags completionState)
{
lock (_completionLock)
{
var oldCompletionState = _completionState;
_completionState |= completionState;
return (oldCompletionState, _completionState);
}
}
/// <summary>
/// Used to kick off the request processing loop by derived classes.
/// </summary>
public abstract void Execute();
protected enum RequestHeaderParsingState
{
Ready,
PseudoHeaderFields,
Headers,
Trailers
}
[Flags]
private enum PseudoHeaderFields
{
None = 0x0,
Authority = 0x1,
Method = 0x2,
Path = 0x4,
Scheme = 0x8,
Status = 0x10,
Unknown = 0x40000000
}
[Flags]
private enum StreamCompletionFlags
{
None = 0,
EndStreamReceived = 1,
AbortedRead = 2,
Aborted = 4,
Completed = 8,
}
private static class GracefulCloseInitiator
{
public const int None = 0;
public const int Server = 1;
public const int Client = 2;
}
}
}
| |
#region --- License ---
/*
Copyright (c) 2006 - 2008 The Open Toolkit library.
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
using System;
using System.Runtime.InteropServices;
namespace Duality
{
/// <summary>
/// Represents a 3x3 matrix containing 3D rotation and scale.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct Matrix3 : IEquatable<Matrix3>
{
#region Fields
/// <summary>
/// First row of the matrix.
/// </summary>
public Vector3 Row0;
/// <summary>
/// Second row of the matrix.
/// </summary>
public Vector3 Row1;
/// <summary>
/// Third row of the matrix.
/// </summary>
public Vector3 Row2;
/// <summary>
/// The identity matrix.
/// </summary>
public static readonly Matrix3 Identity = new Matrix3(Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ);
/// <summary>
/// The zero matrix.
/// </summary>
public static readonly Matrix3 Zero = new Matrix3(Vector3.Zero, Vector3.Zero, Vector3.Zero);
#endregion
#region Constructors
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="row0">Top row of the matrix</param>
/// <param name="row1">Second row of the matrix</param>
/// <param name="row2">Bottom row of the matrix</param>
public Matrix3(Vector3 row0, Vector3 row1, Vector3 row2)
{
Row0 = row0;
Row1 = row1;
Row2 = row2;
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="m00">First item of the first row of the matrix.</param>
/// <param name="m01">Second item of the first row of the matrix.</param>
/// <param name="m02">Third item of the first row of the matrix.</param>
/// <param name="m10">First item of the second row of the matrix.</param>
/// <param name="m11">Second item of the second row of the matrix.</param>
/// <param name="m12">Third item of the second row of the matrix.</param>
/// <param name="m20">First item of the third row of the matrix.</param>
/// <param name="m21">Second item of the third row of the matrix.</param>
/// <param name="m22">Third item of the third row of the matrix.</param>
public Matrix3(
float m00, float m01, float m02,
float m10, float m11, float m12,
float m20, float m21, float m22)
{
Row0 = new Vector3(m00, m01, m02);
Row1 = new Vector3(m10, m11, m12);
Row2 = new Vector3(m20, m21, m22);
}
/// <summary>
/// Constructs a new instance.
/// </summary>
/// <param name="matrix">A Matrix4 to take the upper-left 3x3 from.</param>
public Matrix3(Matrix4 matrix)
{
Row0 = matrix.Row0.Xyz;
Row1 = matrix.Row1.Xyz;
Row2 = matrix.Row2.Xyz;
}
#endregion
#region Public Members
#region Properties
/// <summary>
/// Gets the determinant of this matrix.
/// </summary>
public float Determinant
{
get
{
float m11 = Row0.X, m12 = Row0.Y, m13 = Row0.Z,
m21 = Row1.X, m22 = Row1.Y, m23 = Row1.Z,
m31 = Row2.X, m32 = Row2.Y, m33 = Row2.Z;
return m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32
- m13 * m22 * m31 - m11 * m23 * m32 - m12 * m21 * m33;
}
}
/// <summary>
/// Gets the first column of this matrix.
/// </summary>
public Vector3 Column0
{
get { return new Vector3(Row0.X, Row1.X, Row2.X); }
}
/// <summary>
/// Gets the second column of this matrix.
/// </summary>
public Vector3 Column1
{
get { return new Vector3(Row0.Y, Row1.Y, Row2.Y); }
}
/// <summary>
/// Gets the third column of this matrix.
/// </summary>
public Vector3 Column2
{
get { return new Vector3(Row0.Z, Row1.Z, Row2.Z); }
}
/// <summary>
/// Gets or sets the value at row 1, column 1 of this instance.
/// </summary>
public float M11 { get { return Row0.X; } set { Row0.X = value; } }
/// <summary>
/// Gets or sets the value at row 1, column 2 of this instance.
/// </summary>
public float M12 { get { return Row0.Y; } set { Row0.Y = value; } }
/// <summary>
/// Gets or sets the value at row 1, column 3 of this instance.
/// </summary>
public float M13 { get { return Row0.Z; } set { Row0.Z = value; } }
/// <summary>
/// Gets or sets the value at row 2, column 1 of this instance.
/// </summary>
public float M21 { get { return Row1.X; } set { Row1.X = value; } }
/// <summary>
/// Gets or sets the value at row 2, column 2 of this instance.
/// </summary>
public float M22 { get { return Row1.Y; } set { Row1.Y = value; } }
/// <summary>
/// Gets or sets the value at row 2, column 3 of this instance.
/// </summary>
public float M23 { get { return Row1.Z; } set { Row1.Z = value; } }
/// <summary>
/// Gets or sets the value at row 3, column 1 of this instance.
/// </summary>
public float M31 { get { return Row2.X; } set { Row2.X = value; } }
/// <summary>
/// Gets or sets the value at row 3, column 2 of this instance.
/// </summary>
public float M32 { get { return Row2.Y; } set { Row2.Y = value; } }
/// <summary>
/// Gets or sets the value at row 3, column 3 of this instance.
/// </summary>
public float M33 { get { return Row2.Z; } set { Row2.Z = value; } }
/// <summary>
/// Gets or sets the values along the main diagonal of the matrix.
/// </summary>
public Vector3 Diagonal
{
get
{
return new Vector3(Row0.X, Row1.Y, Row2.Z);
}
set
{
Row0.X = value.X;
Row1.Y = value.Y;
Row2.Z = value.Z;
}
}
/// <summary>
/// Gets the trace of the matrix, the sum of the values along the diagonal.
/// </summary>
public float Trace { get { return Row0.X + Row1.Y + Row2.Z; } }
#endregion
#region Indexers
/// <summary>
/// Gets or sets the value at a specified row and column.
/// </summary>
public float this[int rowIndex, int columnIndex]
{
get
{
if (rowIndex == 0) return Row0[columnIndex];
else if (rowIndex == 1) return Row1[columnIndex];
else if (rowIndex == 2) return Row2[columnIndex];
throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
set
{
if (rowIndex == 0) Row0[columnIndex] = value;
else if (rowIndex == 1) Row1[columnIndex] = value;
else if (rowIndex == 2) Row2[columnIndex] = value;
else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")");
}
}
#endregion
#region Instance
#region public void Invert()
/// <summary>
/// Converts this instance into its inverse.
/// </summary>
public void Invert()
{
this = Matrix3.Invert(this);
}
#endregion
#region public void Transpose()
/// <summary>
/// Converts this instance into its transpose.
/// </summary>
public void Transpose()
{
this = Matrix3.Transpose(this);
}
#endregion
/// <summary>
/// Returns a normalised copy of this instance.
/// </summary>
public Matrix3 Normalized()
{
Matrix3 m = this;
m.Normalize();
return m;
}
/// <summary>
/// Divides each element in the Matrix by the <see cref="Determinant"/>.
/// </summary>
public void Normalize()
{
var determinant = this.Determinant;
Row0 /= determinant;
Row1 /= determinant;
Row2 /= determinant;
}
/// <summary>
/// Returns an inverted copy of this instance.
/// </summary>
public Matrix3 Inverted()
{
Matrix3 m = this;
if (m.Determinant != 0)
m.Invert();
return m;
}
/// <summary>
/// Returns a copy of this Matrix3 without scale.
/// </summary>
public Matrix3 ClearScale()
{
Matrix3 m = this;
m.Row0 = m.Row0.Normalized;
m.Row1 = m.Row1.Normalized;
m.Row2 = m.Row2.Normalized;
return m;
}
/// <summary>
/// Returns a copy of this Matrix3 without rotation.
/// </summary>
public Matrix3 ClearRotation()
{
Matrix3 m = this;
m.Row0 = new Vector3(m.Row0.Length, 0, 0);
m.Row1 = new Vector3(0, m.Row1.Length, 0);
m.Row2 = new Vector3(0, 0, m.Row2.Length);
return m;
}
/// <summary>
/// Returns the scale component of this instance.
/// </summary>
public Vector3 ExtractScale() { return new Vector3(Row0.Length, Row1.Length, Row2.Length); }
/// <summary>
/// Returns the rotation component of this instance. Quite slow.
/// </summary>
/// <param name="row_normalise">Whether the method should row-normalise (i.e. remove scale from) the Matrix. Pass false if you know it's already normalised.</param>
public Quaternion ExtractRotation(bool row_normalise = true)
{
var row0 = Row0;
var row1 = Row1;
var row2 = Row2;
if (row_normalise)
{
row0 = row0.Normalized;
row1 = row1.Normalized;
row2 = row2.Normalized;
}
// code below adapted from Blender
Quaternion q = new Quaternion();
double trace = 0.25 * (row0[0] + row1[1] + row2[2] + 1.0);
if (trace > 0)
{
double sq = Math.Sqrt(trace);
q.W = (float)sq;
sq = 1.0 / (4.0 * sq);
q.X = (float)((row1[2] - row2[1]) * sq);
q.Y = (float)((row2[0] - row0[2]) * sq);
q.Z = (float)((row0[1] - row1[0]) * sq);
}
else if (row0[0] > row1[1] && row0[0] > row2[2])
{
double sq = 2.0 * Math.Sqrt(1.0 + row0[0] - row1[1] - row2[2]);
q.X = (float)(0.25 * sq);
sq = 1.0 / sq;
q.W = (float)((row2[1] - row1[2]) * sq);
q.Y = (float)((row1[0] + row0[1]) * sq);
q.Z = (float)((row2[0] + row0[2]) * sq);
}
else if (row1[1] > row2[2])
{
double sq = 2.0 * Math.Sqrt(1.0 + row1[1] - row0[0] - row2[2]);
q.Y = (float)(0.25 * sq);
sq = 1.0 / sq;
q.W = (float)((row2[0] - row0[2]) * sq);
q.X = (float)((row1[0] + row0[1]) * sq);
q.Z = (float)((row2[1] + row1[2]) * sq);
}
else
{
double sq = 2.0 * Math.Sqrt(1.0 + row2[2] - row0[0] - row1[1]);
q.Z = (float)(0.25 * sq);
sq = 1.0 / sq;
q.W = (float)((row1[0] - row0[1]) * sq);
q.X = (float)((row2[0] + row0[2]) * sq);
q.Y = (float)((row2[1] + row1[2]) * sq);
}
q.Normalize();
return q;
}
#endregion
#region Static
#region CreateFromAxisAngle
/// <summary>
/// Build a rotation matrix from the specified axis/angle rotation.
/// </summary>
/// <param name="axis">The axis to rotate about.</param>
/// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param>
/// <param name="result">A matrix instance.</param>
public static void CreateFromAxisAngle(Vector3 axis, float angle, out Matrix3 result)
{
//normalize and create a local copy of the vector.
axis.Normalize();
float axisX = axis.X, axisY = axis.Y, axisZ = axis.Z;
//calculate angles
float cos = (float)System.Math.Cos(-angle);
float sin = (float)System.Math.Sin(-angle);
float t = 1.0f - cos;
//do the conversion math once
float tXX = t * axisX * axisX,
tXY = t * axisX * axisY,
tXZ = t * axisX * axisZ,
tYY = t * axisY * axisY,
tYZ = t * axisY * axisZ,
tZZ = t * axisZ * axisZ;
float sinX = sin * axisX,
sinY = sin * axisY,
sinZ = sin * axisZ;
result.Row0.X = tXX + cos;
result.Row0.Y = tXY - sinZ;
result.Row0.Z = tXZ + sinY;
result.Row1.X = tXY + sinZ;
result.Row1.Y = tYY + cos;
result.Row1.Z = tYZ - sinX;
result.Row2.X = tXZ - sinY;
result.Row2.Y = tYZ + sinX;
result.Row2.Z = tZZ + cos;
}
/// <summary>
/// Build a rotation matrix from the specified axis/angle rotation.
/// </summary>
/// <param name="axis">The axis to rotate about.</param>
/// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param>
/// <returns>A matrix instance.</returns>
public static Matrix3 CreateFromAxisAngle(Vector3 axis, float angle)
{
Matrix3 result;
CreateFromAxisAngle(axis, angle, out result);
return result;
}
#endregion
#region CreateFromQuaternion
/// <summary>
/// Build a rotation matrix from the specified quaternion.
/// </summary>
/// <param name="q">Quaternion to translate.</param>
/// <param name="result">Matrix result.</param>
public static void CreateFromQuaternion(ref Quaternion q, out Matrix3 result)
{
Vector3 axis;
float angle;
q.ToAxisAngle(out axis, out angle);
CreateFromAxisAngle(axis, angle, out result);
}
/// <summary>
/// Build a rotation matrix from the specified quaternion.
/// </summary>
/// <param name="q">Quaternion to translate.</param>
/// <returns>A matrix instance.</returns>
public static Matrix3 CreateFromQuaternion(Quaternion q)
{
Matrix3 result;
CreateFromQuaternion(ref q, out result);
return result;
}
#endregion
#region CreateRotation[XYZ]
/// <summary>
/// Builds a rotation matrix for a rotation around the x-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <param name="result">The resulting Matrix3 instance.</param>
public static void CreateRotationX(float angle, out Matrix3 result)
{
float cos = (float)System.Math.Cos(angle);
float sin = (float)System.Math.Sin(angle);
result = Identity;
result.Row1.Y = cos;
result.Row1.Z = sin;
result.Row2.Y = -sin;
result.Row2.Z = cos;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the x-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <returns>The resulting Matrix3 instance.</returns>
public static Matrix3 CreateRotationX(float angle)
{
Matrix3 result;
CreateRotationX(angle, out result);
return result;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the y-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <param name="result">The resulting Matrix3 instance.</param>
public static void CreateRotationY(float angle, out Matrix3 result)
{
float cos = (float)System.Math.Cos(angle);
float sin = (float)System.Math.Sin(angle);
result = Identity;
result.Row0.X = cos;
result.Row0.Z = -sin;
result.Row2.X = sin;
result.Row2.Z = cos;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the y-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <returns>The resulting Matrix3 instance.</returns>
public static Matrix3 CreateRotationY(float angle)
{
Matrix3 result;
CreateRotationY(angle, out result);
return result;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the z-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <param name="result">The resulting Matrix3 instance.</param>
public static void CreateRotationZ(float angle, out Matrix3 result)
{
float cos = (float)System.Math.Cos(angle);
float sin = (float)System.Math.Sin(angle);
result = Identity;
result.Row0.X = cos;
result.Row0.Y = sin;
result.Row1.X = -sin;
result.Row1.Y = cos;
}
/// <summary>
/// Builds a rotation matrix for a rotation around the z-axis.
/// </summary>
/// <param name="angle">The counter-clockwise angle in radians.</param>
/// <returns>The resulting Matrix3 instance.</returns>
public static Matrix3 CreateRotationZ(float angle)
{
Matrix3 result;
CreateRotationZ(angle, out result);
return result;
}
#endregion
#region CreateScale
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="scale">Single scale factor for the x, y, and z axes.</param>
/// <returns>A scale matrix.</returns>
public static Matrix3 CreateScale(float scale)
{
Matrix3 result;
CreateScale(scale, out result);
return result;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="scale">Scale factors for the x, y, and z axes.</param>
/// <returns>A scale matrix.</returns>
public static Matrix3 CreateScale(Vector3 scale)
{
Matrix3 result;
CreateScale(ref scale, out result);
return result;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="x">Scale factor for the x axis.</param>
/// <param name="y">Scale factor for the y axis.</param>
/// <param name="z">Scale factor for the z axis.</param>
/// <returns>A scale matrix.</returns>
public static Matrix3 CreateScale(float x, float y, float z)
{
Matrix3 result;
CreateScale(x, y, z, out result);
return result;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="scale">Single scale factor for the x, y, and z axes.</param>
/// <param name="result">A scale matrix.</param>
public static void CreateScale(float scale, out Matrix3 result)
{
result = Identity;
result.Row0.X = scale;
result.Row1.Y = scale;
result.Row2.Z = scale;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="scale">Scale factors for the x, y, and z axes.</param>
/// <param name="result">A scale matrix.</param>
public static void CreateScale(ref Vector3 scale, out Matrix3 result)
{
result = Identity;
result.Row0.X = scale.X;
result.Row1.Y = scale.Y;
result.Row2.Z = scale.Z;
}
/// <summary>
/// Creates a scale matrix.
/// </summary>
/// <param name="x">Scale factor for the x axis.</param>
/// <param name="y">Scale factor for the y axis.</param>
/// <param name="z">Scale factor for the z axis.</param>
/// <param name="result">A scale matrix.</param>
public static void CreateScale(float x, float y, float z, out Matrix3 result)
{
result = Identity;
result.Row0.X = x;
result.Row1.Y = y;
result.Row2.Z = z;
}
#endregion
#region Multiply Functions
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The left operand of the multiplication.</param>
/// <param name="right">The right operand of the multiplication.</param>
/// <returns>A new instance that is the result of the multiplication</returns>
public static Matrix3 Mult(Matrix3 left, Matrix3 right)
{
Matrix3 result;
Mult(ref left, ref right, out result);
return result;
}
/// <summary>
/// Multiplies two instances.
/// </summary>
/// <param name="left">The left operand of the multiplication.</param>
/// <param name="right">The right operand of the multiplication.</param>
/// <param name="result">A new instance that is the result of the multiplication</param>
public static void Mult(ref Matrix3 left, ref Matrix3 right, out Matrix3 result)
{
float lM11 = left.Row0.X, lM12 = left.Row0.Y, lM13 = left.Row0.Z,
lM21 = left.Row1.X, lM22 = left.Row1.Y, lM23 = left.Row1.Z,
lM31 = left.Row2.X, lM32 = left.Row2.Y, lM33 = left.Row2.Z,
rM11 = right.Row0.X, rM12 = right.Row0.Y, rM13 = right.Row0.Z,
rM21 = right.Row1.X, rM22 = right.Row1.Y, rM23 = right.Row1.Z,
rM31 = right.Row2.X, rM32 = right.Row2.Y, rM33 = right.Row2.Z;
result.Row0.X = ((lM11 * rM11) + (lM12 * rM21)) + (lM13 * rM31);
result.Row0.Y = ((lM11 * rM12) + (lM12 * rM22)) + (lM13 * rM32);
result.Row0.Z = ((lM11 * rM13) + (lM12 * rM23)) + (lM13 * rM33);
result.Row1.X = ((lM21 * rM11) + (lM22 * rM21)) + (lM23 * rM31);
result.Row1.Y = ((lM21 * rM12) + (lM22 * rM22)) + (lM23 * rM32);
result.Row1.Z = ((lM21 * rM13) + (lM22 * rM23)) + (lM23 * rM33);
result.Row2.X = ((lM31 * rM11) + (lM32 * rM21)) + (lM33 * rM31);
result.Row2.Y = ((lM31 * rM12) + (lM32 * rM22)) + (lM33 * rM32);
result.Row2.Z = ((lM31 * rM13) + (lM32 * rM23)) + (lM33 * rM33);
}
#endregion
#region Invert Functions
/// <summary>
/// Calculate the inverse of the given matrix
/// </summary>
/// <param name="mat">The matrix to invert</param>
/// <param name="result">The inverse of the given matrix if it has one, or the input if it is singular</param>
/// <exception cref="InvalidOperationException">Thrown if the Matrix3 is singular.</exception>
public static void Invert(ref Matrix3 mat, out Matrix3 result)
{
int[] colIdx = { 0, 0, 0 };
int[] rowIdx = { 0, 0, 0 };
int[] pivotIdx = { -1, -1, -1 };
float[,] inverse = {{mat.Row0.X, mat.Row0.Y, mat.Row0.Z},
{mat.Row1.X, mat.Row1.Y, mat.Row1.Z},
{mat.Row2.X, mat.Row2.Y, mat.Row2.Z}};
int icol = 0;
int irow = 0;
for (int i = 0; i < 3; i++)
{
float maxPivot = 0.0f;
for (int j = 0; j < 3; j++)
{
if (pivotIdx[j] != 0)
{
for (int k = 0; k < 3; ++k)
{
if (pivotIdx[k] == -1)
{
float absVal = System.Math.Abs(inverse[j, k]);
if (absVal > maxPivot)
{
maxPivot = absVal;
irow = j;
icol = k;
}
}
else if (pivotIdx[k] > 0)
{
result = mat;
return;
}
}
}
}
++(pivotIdx[icol]);
if (irow != icol)
{
for (int k = 0; k < 3; ++k)
{
float f = inverse[irow, k];
inverse[irow, k] = inverse[icol, k];
inverse[icol, k] = f;
}
}
rowIdx[i] = irow;
colIdx[i] = icol;
float pivot = inverse[icol, icol];
if (pivot == 0.0f)
{
throw new InvalidOperationException("Matrix is singular and cannot be inverted.");
}
float oneOverPivot = 1.0f / pivot;
inverse[icol, icol] = 1.0f;
for (int k = 0; k < 3; ++k)
inverse[icol, k] *= oneOverPivot;
for (int j = 0; j < 3; ++j)
{
if (icol != j)
{
float f = inverse[j, icol];
inverse[j, icol] = 0.0f;
for (int k = 0; k < 3; ++k)
inverse[j, k] -= inverse[icol, k] * f;
}
}
}
for (int j = 2; j >= 0; --j)
{
int ir = rowIdx[j];
int ic = colIdx[j];
for (int k = 0; k < 3; ++k)
{
float f = inverse[k, ir];
inverse[k, ir] = inverse[k, ic];
inverse[k, ic] = f;
}
}
result.Row0.X = inverse[0, 0];
result.Row0.Y = inverse[0, 1];
result.Row0.Z = inverse[0, 2];
result.Row1.X = inverse[1, 0];
result.Row1.Y = inverse[1, 1];
result.Row1.Z = inverse[1, 2];
result.Row2.X = inverse[2, 0];
result.Row2.Y = inverse[2, 1];
result.Row2.Z = inverse[2, 2];
}
/// <summary>
/// Calculate the inverse of the given matrix
/// </summary>
/// <param name="mat">The matrix to invert</param>
/// <returns>The inverse of the given matrix if it has one, or the input if it is singular</returns>
/// <exception cref="InvalidOperationException">Thrown if the Matrix4 is singular.</exception>
public static Matrix3 Invert(Matrix3 mat)
{
Matrix3 result;
Invert(ref mat, out result);
return result;
}
#endregion
#region Transpose
/// <summary>
/// Calculate the transpose of the given matrix
/// </summary>
/// <param name="mat">The matrix to transpose</param>
/// <returns>The transpose of the given matrix</returns>
public static Matrix3 Transpose(Matrix3 mat)
{
return new Matrix3(mat.Column0, mat.Column1, mat.Column2);
}
/// <summary>
/// Calculate the transpose of the given matrix
/// </summary>
/// <param name="mat">The matrix to transpose</param>
/// <param name="result">The result of the calculation</param>
public static void Transpose(ref Matrix3 mat, out Matrix3 result)
{
result.Row0.X = mat.Row0.X;
result.Row0.Y = mat.Row1.X;
result.Row0.Z = mat.Row2.X;
result.Row1.X = mat.Row0.Y;
result.Row1.Y = mat.Row1.Y;
result.Row1.Z = mat.Row2.Y;
result.Row2.X = mat.Row0.Z;
result.Row2.Y = mat.Row1.Z;
result.Row2.Z = mat.Row2.Z;
}
#endregion
#endregion
#region Operators
/// <summary>
/// Matrix multiplication
/// </summary>
/// <param name="left">left-hand operand</param>
/// <param name="right">right-hand operand</param>
/// <returns>A new Matrix3d which holds the result of the multiplication</returns>
public static Matrix3 operator *(Matrix3 left, Matrix3 right)
{
return Matrix3.Mult(left, right);
}
/// <summary>
/// Compares two instances for equality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left equals right; false otherwise.</returns>
public static bool operator ==(Matrix3 left, Matrix3 right)
{
return left.Equals(right);
}
/// <summary>
/// Compares two instances for inequality.
/// </summary>
/// <param name="left">The first instance.</param>
/// <param name="right">The second instance.</param>
/// <returns>True, if left does not equal right; false otherwise.</returns>
public static bool operator !=(Matrix3 left, Matrix3 right)
{
return !left.Equals(right);
}
#endregion
#region Overrides
#region public override string ToString()
/// <summary>
/// Returns a System.String that represents the current Matrix3d.
/// </summary>
/// <returns>The string representation of the matrix.</returns>
public override string ToString()
{
return String.Format("{0}\n{1}\n{2}", Row0, Row1, Row2);
}
#endregion
#region public override int GetHashCode()
/// <summary>
/// Returns the hashcode for this instance.
/// </summary>
/// <returns>A System.Int32 containing the unique hashcode for this instance.</returns>
public override int GetHashCode()
{
return Row0.GetHashCode() ^ Row1.GetHashCode() ^ Row2.GetHashCode();
}
#endregion
#region public override bool Equals(object obj)
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">The object to compare to.</param>
/// <returns>True if the instances are equal; false otherwise.</returns>
public override bool Equals(object obj)
{
if (!(obj is Matrix3))
return false;
return this.Equals((Matrix3)obj);
}
#endregion
#endregion
#endregion
#region IEquatable<Matrix3> Members
/// <summary>Indicates whether the current matrix is equal to another matrix.</summary>
/// <param name="other">A matrix to compare with this matrix.</param>
/// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns>
public bool Equals(Matrix3 other)
{
return
Row0 == other.Row0 &&
Row1 == other.Row1 &&
Row2 == other.Row2;
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using Medo.Security.Cryptography;
namespace QText {
public class DocumentFile {
public DocumentFile(DocumentFolder folder, string fileName) {
Folder = folder;
if (fileName.EndsWith(FileExtensions.PlainText, StringComparison.OrdinalIgnoreCase)) {
Kind = DocumentKind.PlainText;
} else if (fileName.EndsWith(FileExtensions.RichText, StringComparison.OrdinalIgnoreCase)) {
Kind = DocumentKind.RichText;
} else if (fileName.EndsWith(FileExtensions.EncryptedPlainText, StringComparison.OrdinalIgnoreCase)) {
Kind = DocumentKind.EncryptedPlainText;
} else if (fileName.EndsWith(FileExtensions.EncryptedRichText, StringComparison.OrdinalIgnoreCase)) {
Kind = DocumentKind.EncryptedRichText;
} else {
throw new NotSupportedException("Cannot recognize file extension.");
}
Name = fileName.Substring(0, fileName.Length - Extension.Length);
}
/// <summary>
/// Gets folder containing this file.
/// </summary>
public DocumentFolder Folder { get; internal set; }
/// <summary>
/// Gets name of file - for internal use.
/// </summary>
public string Name { get; internal set; }
/// <summary>
/// Gets a full name of a file - for internal use
/// </summary>
public string FullName {
get { return Path.Combine(Folder.FullPath, Name); }
}
/// <summary>
/// Returns true if file exists
/// </summary>
public bool Exists {
get { return File.Exists(FullName); }
}
/// <summary>
/// Gets file's kind.
/// </summary>
public DocumentKind Kind { get; internal set; }
/// <summary>
/// Gets kind of a document without special handling for encryption.
/// </summary>
public DocumentStyle Style {
get {
switch (Kind) {
case DocumentKind.RichText:
case DocumentKind.EncryptedRichText:
return DocumentStyle.RichText;
default:
return DocumentStyle.PlainText;
}
}
}
/// <summary>
/// Gets if document is encrypted
/// </summary>
public bool IsEncrypted { get { return (Kind == DocumentKind.EncryptedPlainText) || (Kind == DocumentKind.EncryptedRichText); } }
/// <summary>
/// Gets full file path.
/// </summary>
internal string FullPath {
get { return Path.Combine(Folder.FullPath, Name + Extension); }
}
/// <summary>
/// Gets file extension.
/// </summary>
public string Extension {
get {
switch (Kind) {
case DocumentKind.PlainText:
return FileExtensions.PlainText;
case DocumentKind.RichText:
return FileExtensions.RichText;
case DocumentKind.EncryptedPlainText:
return FileExtensions.EncryptedPlainText;
case DocumentKind.EncryptedRichText:
return FileExtensions.EncryptedRichText;
default:
throw new InvalidOperationException("Cannot determine kind.");
}
}
}
/// <summary>
/// Gets title to display to user.
/// </summary>
public string Title {
get { return Helper.DecodeFileTitle(Name); }
}
public bool IsPlainText { get { return Style == DocumentStyle.PlainText; } }
public bool IsRichText { get { return Style == DocumentStyle.RichText; } }
#region Encryption
private byte[] PasswordBytes;
public string Password {
set {
if (value != null) {
PasswordBytes = UTF8Encoding.UTF8.GetBytes(value);
ProtectPassword();
} else {
PasswordBytes = null;
}
}
}
public bool NeedsPassword { get { return (IsEncrypted && (PasswordBytes == null)); } }
public bool HasPassword { get { return (IsEncrypted && (PasswordBytes != null)); } }
public void ProtectPassword() {
if (PasswordBytes == null) { return; }
var bytes = PasswordBytes;
PasswordBytes = ProtectedData.Protect(bytes, null, DataProtectionScope.CurrentUser);
Array.Clear(bytes, 0, bytes.Length);
}
public void UnprotectPassword() {
if (PasswordBytes == null) { return; }
PasswordBytes = ProtectedData.Unprotect(PasswordBytes, null, DataProtectionScope.CurrentUser);
}
#endregion
public DateTime LastWriteTimeUtc { get { return File.GetLastAccessTimeUtc(FullPath); } }
#region Rename/Delete
private void GatherRenameData(ref string newTitle, out string newName, out string newPath) {
newTitle = newTitle.Trim();
newName = Helper.EncodeFileTitle(newTitle);
newPath = Path.Combine(Folder.FullPath, newName);
switch (Kind) {
case DocumentKind.PlainText:
newPath += FileExtensions.PlainText;
break;
case DocumentKind.RichText:
newPath += FileExtensions.RichText;
break;
case DocumentKind.EncryptedPlainText:
newPath += FileExtensions.EncryptedPlainText;
break;
case DocumentKind.EncryptedRichText:
newPath += FileExtensions.EncryptedRichText;
break;
default:
throw new NotSupportedException("Unknown file kind.");
}
}
public bool CanRename(string newTitle) {
GatherRenameData(ref newTitle, out _, out var newPath);
return !File.Exists(newPath);
}
public void Rename(string newTitle) {
GatherRenameData(ref newTitle, out var newName, out var newPath);
Debug.WriteLine("File.Rename: " + Name + " -> " + newName);
try {
using (var watcher = new Helper.FileSystemToggler(Folder.Document.Watcher)) {
Helper.MovePath(FullPath, newPath);
}
} catch (Exception ex) {
throw new InvalidOperationException(ex.Message, ex);
}
Name = newName;
Folder.Document.WriteOrder();
Folder.Document.OnFileChanged(new DocumentFileEventArgs(this));
}
public bool CanMove(DocumentFolder newFolder) {
foreach (var file in newFolder.GetFiles()) {
if (file.Title.Equals(Title, StringComparison.OrdinalIgnoreCase)) { return false; }
}
return true;
}
public void Move(DocumentFolder newFolder) {
try {
var oldFolder = Folder;
var oldPath = FullPath;
var newPath = Path.Combine(newFolder.FullPath, Name + Extension);
Debug.WriteLine("File.Move: " + Folder.Name + " -> " + newFolder.Name);
using (var watcher = new Helper.FileSystemToggler(Folder.Document.Watcher)) {
Helper.MovePath(oldPath, newPath);
Folder = newFolder;
}
OrderBefore(null);
Folder.Document.OnFolderChanged(new DocumentFolderEventArgs(oldFolder));
Folder.Document.OnFolderChanged(new DocumentFolderEventArgs(Folder));
} catch (Exception ex) {
throw new InvalidOperationException(ex.Message, ex);
}
}
public void Delete() {
Debug.WriteLine("File.Delete: " + Name);
try {
using (var watcher = new Helper.FileSystemToggler(Folder.Document.Watcher)) {
if (Folder.Document.DeleteToRecycleBin) {
SHFile.Delete(FullPath);
} else {
File.Delete(FullPath);
}
}
Folder.Document.ProcessDelete(FullPath);
Folder.Document.OnFolderChanged(new DocumentFolderEventArgs(Folder));
} catch (Exception ex) {
throw new InvalidOperationException(ex.Message, ex);
}
}
public void OpenInExplorer() {
var exe = new ProcessStartInfo("explorer.exe", "/select,\"" + FullPath + "\"");
Process.Start(exe);
}
#endregion
#region Kind
public void ChangeStyle(DocumentStyle newStyle) {
if (newStyle == Style) { return; }
DocumentKind newKind;
switch (newStyle) {
case DocumentStyle.PlainText:
newKind = IsEncrypted ? DocumentKind.EncryptedPlainText : DocumentKind.PlainText;
break;
case DocumentStyle.RichText:
newKind = IsEncrypted ? DocumentKind.EncryptedRichText : DocumentKind.RichText;
break;
default:
throw new NotSupportedException("Unknown file style.");
}
Debug.WriteLine("File.ChangeStyle: " + Name + " (" + Style.ToString() + " -> " + newStyle.ToString() + ")");
using (var watcher = new Helper.FileSystemToggler(Folder.Document.Watcher)) {
Helper.MovePath(FullPath, Path.Combine(Folder.FullPath, Name + FileExtensions.GetFromKind(newKind)));
}
Kind = newKind;
Folder.Document.OnFileChanged(new DocumentFileEventArgs(this));
}
public void Encrypt(string password) {
if (IsEncrypted) { return; }
Debug.WriteLine("File.Encrypt: " + Name);
var oldPath = FullPath;
using (var stream = new MemoryStream()) {
Read(stream);
Kind = (Style == DocumentStyle.RichText) ? DocumentKind.EncryptedRichText : DocumentKind.EncryptedPlainText;
Password = password;
using (var watcher = new Helper.FileSystemToggler(Folder.Document.Watcher)) {
Write(stream);
File.Delete(oldPath);
}
}
Folder.Document.OnFileChanged(new DocumentFileEventArgs(this));
}
public void Decrypt() {
if (!IsEncrypted) { return; }
Debug.WriteLine("File.Decrypt: " + Name);
var oldPath = FullPath;
using (var stream = new MemoryStream()) {
Read(stream);
Kind = (Style == DocumentStyle.RichText) ? DocumentKind.RichText : DocumentKind.PlainText;
Password = null;
using (var watcher = new Helper.FileSystemToggler(Folder.Document.Watcher)) {
Write(stream);
File.Delete(oldPath);
}
}
Folder.Document.OnFileChanged(new DocumentFileEventArgs(this));
}
#endregion
#region Order
public void OrderBefore(DocumentFile pivotFile) {
Folder.Document.OrderBefore(this, pivotFile);
}
public void OrderAfter(DocumentFile pivotFile) {
Folder.Document.OrderAfter(this, pivotFile);
}
#endregion
#region Read/write
public void Read(MemoryStream stream) {
if (IsEncrypted && !HasPassword) { throw new InvalidOperationException("Missing password."); }
using (var fileStream = new FileStream(FullPath, FileMode.Open, FileAccess.Read, FileShare.Read)) {
var buffer = new byte[65536];
int len;
if (IsEncrypted) {
UnprotectPassword();
try {
using (var aesStream = new OpenSslAesStream(fileStream, PasswordBytes, CryptoStreamMode.Read, 256, CipherMode.CBC)) {
while ((len = aesStream.Read(buffer, 0, buffer.Length)) > 0) {
stream.Write(buffer, 0, len);
}
stream.Position = 0;
}
} catch (CryptographicException) {
PasswordBytes = null; //clear password
throw new InvalidOperationException("Decryption failed.");
} finally {
ProtectPassword();
}
} else {
while ((len = fileStream.Read(buffer, 0, buffer.Length)) > 0) {
stream.Write(buffer, 0, len);
}
stream.Position = 0;
}
}
}
public void Write(MemoryStream stream) {
if (IsEncrypted && !HasPassword) { throw new InvalidOperationException("Missing password."); }
using (var watcher = new Helper.FileSystemToggler(Folder.Document.Watcher)) {
stream.Position = 0;
using (var fileStream = new FileStream(FullPath, FileMode.Create, FileAccess.Write, FileShare.None)) {
var buffer = new byte[65536];
int len;
if (IsEncrypted) {
UnprotectPassword();
try {
using (var aesStream = new OpenSslAesStream(fileStream, PasswordBytes, CryptoStreamMode.Write, 256, CipherMode.CBC)) {
while ((len = stream.Read(buffer, 0, buffer.Length)) > 0) {
aesStream.Write(buffer, 0, len);
}
}
} finally {
ProtectPassword();
}
} else {
while ((len = stream.Read(buffer, 0, buffer.Length)) > 0) {
fileStream.Write(buffer, 0, len);
}
}
}
}
WriteCarbonCopy();
}
internal void WriteCarbonCopy() {
if (Folder.Document.CarbonCopyRootPath != null) {
try {
var ccPath = Folder.IsRoot ? Folder.Document.CarbonCopyRootPath : Path.Combine(Folder.Document.CarbonCopyRootPath, Folder.Name);
Helper.CreatePath(ccPath);
var ccFullPath = Path.Combine(ccPath, Name + Extension);
File.Copy(FullPath, ccFullPath, true);
} catch (Exception ex) {
if (!Folder.Document.CarbonCopyIgnoreErrors) {
throw new InvalidOperationException("Error writing carbon copy for " + Title + ".\n\n" + ex.Message, ex);
}
}
}
}
#endregion
#region Selection
private bool _selected;
/// <summary>
/// Gets/sets if file is currently selected.
/// </summary>
public bool Selected {
get { return _selected; }
set {
if (value) {
foreach (var file in Folder.GetFiles()) {
file._selected = false;
}
}
_selected = value;
Folder.Document.WriteOrder();
}
}
#endregion
#region Overrides
public override bool Equals(object obj) {
return (obj is DocumentFile other) && (FullPath.Equals(other.FullPath, StringComparison.OrdinalIgnoreCase));
}
public override int GetHashCode() {
return Name.GetHashCode();
}
public override string ToString() {
return Title;
}
#endregion
}
}
| |
// CodeContracts
//
// 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.Diagnostics.Contracts;
using System;
using System.Collections.Generic;
namespace System.IO
{
#if !SILVERLIGHT_4_0_WP
// Summary:
// Specifies whether to search the current directory, or the current directory
// and all subdirectories.
public enum SearchOption
{
// Summary:
// Includes only the current directory in a search operation.
TopDirectoryOnly = 0,
//
// Summary:
// Includes the current directory and all its subdirectories in a search operation.
// This option includes reparse points such as mounted drives and symbolic links
// in the search.
AllDirectories = 1,
}
#endif
public class Directory
{
#if false
public static void Delete(string path, bool recursive)
{
}
public static void Delete(string path)
{
}
#endif
public static void Move(string sourceDirName, string destDirName)
{
Contract.Requires(!String.IsNullOrEmpty(sourceDirName));
Contract.Requires(!String.IsNullOrEmpty(destDirName));
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An attempt was made to move a directory to a different volume. -or- destDirName already exists. -or- The sourceDirName and destDirName parameters refer to the same file or directory.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid (for example, it is on an unmapped drive.");
}
#if !SILVERLIGHT_5_0
public static void SetCurrentDirectory(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Requires(path.Length < 260);
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurred.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid (for example, it is on an unmapped drive.");
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The specified path was not found.");
}
#endif
public static string GetCurrentDirectory()
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
public static string GetDirectoryRoot(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Ensures(Contract.Result<string>() != null);
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
return default(string);
}
#if !SILVERLIGHT
public static String[] GetLogicalDrives()
{
Contract.Ensures(Contract.Result<string[]>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<string[]>(), dir => dir != null));
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"An I/O error occurred.");
return default(String[]);
}
#endif
#if !SILVERLIGHT_4_0 && !SILVERLIGHT_5_0
public static String[] GetFileSystemEntries(string path, string searchPattern)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Requires(searchPattern != null);
Contract.Ensures(Contract.Result<string[]>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<string[]>(), file => file != null));
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"path is a file name.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid (for example, it is on an unmapped drive.");
return default(String[]);
}
public static String[] GetFileSystemEntries(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Requires(path.Length < 260);
Contract.Ensures(Contract.Result<string[]>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<string[]>(), file => file != null));
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"path is a file name.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid (for example, it is on an unmapped drive.");
return default(String[]);
}
public static String[] GetDirectories(string path, string searchPattern)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Requires(searchPattern != null);
Contract.Ensures(Contract.Result<string[]>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<string[]>(), dir => dir != null));
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"path is a file name.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid (for example, it is on an unmapped drive.");
return default(String[]);
}
public static String[] GetDirectories(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Ensures(Contract.Result<string[]>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<string[]>(), dir => dir != null));
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"path is a file name.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid (for example, it is on an unmapped drive.");
return default(String[]);
}
public static String[] GetFiles(string path, string searchPattern)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Requires(searchPattern != null);
Contract.Ensures(Contract.Result<string[]>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<string[]>(), file => file != null));
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"path is a file name.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid (for example, it is on an unmapped drive.");
return default(String[]);
}
public static String[] GetFiles(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Ensures(Contract.Result<string[]>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<string[]>(), file => file != null));
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"path is a file name.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid (for example, it is on an unmapped drive.");
return default(String[]);
}
#endif
#if !SILVERLIGHT
public static DateTime GetLastAccessTimeUtc(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
return default(DateTime);
}
#endif
public static DateTime GetLastAccessTime(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
return default(DateTime);
}
#if !SILVERLIGHT
public static void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The specified path was not found.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
}
public static void SetLastAccessTime(string path, DateTime lastAccessTime)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The specified path was not found.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
}
public static DateTime GetLastWriteTimeUtc(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
return default(DateTime);
}
#endif
public static DateTime GetLastWriteTime(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
return default(DateTime);
}
#if !SILVERLIGHT
public static void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The specified path was not found.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
}
public static void SetLastWriteTime(string path, DateTime lastWriteTime)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The specified path was not found.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
}
#endif
#if !SILVERLIGHT
public static DateTime GetCreationTimeUtc(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
return default(DateTime);
}
#endif
public static DateTime GetCreationTime(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
return default(DateTime);
}
#if !SILVERLIGHT
public static void SetCreationTimeUtc(string path, DateTime creationTimeUtc)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The specified path was not found.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
}
public static void SetCreationTime(string path, DateTime creationTime)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.FileNotFoundException>(true, @"The specified path was not found.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
}
#endif
#if !SILVERLIGHT_4_0_WP && !SILVERLIGHT_3_0 && !NETFRAMEWORK_3_5
//
// Summary:
// Returns an enumerable collection of directory names in a specified path.
//
// Parameters:
// path:
// The directory to search.
//
// Returns:
// An enumerable collection of the full names (including paths) for the directories
// in the directory specified by path.
//
// Exceptions:
// System.ArgumentException:
// path is a zero-length string, contains only white space, or contains invalid
// characters as defined by System.IO.Path.GetInvalidPathChars().
//
// System.ArgumentNullException:
// path is null.
//
// System.IO.DirectoryNotFoundException:
// path is invalid, such as referring to an unmapped drive.
//
// System.IO.IOException:
// path is a file name.
//
// System.IO.PathTooLongException:
// The specified path, file name, or combined exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters and file names must be less than 260 characters.
//
// System.Security.SecurityException:
// The caller does not have the required permission.
//
// System.UnauthorizedAccessException:
// The caller does not have the required permission.
public static IEnumerable<string> EnumerateDirectories(string path)
{
Contract.Requires(path != null);
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<string>>(), d => d != null));
return null;
}
//
// Summary:
// Returns an enumerable collection of directory names that match a search pattern
// in a specified path.
//
// Parameters:
// path:
// The directory to search.
//
// searchPattern:
// The search string to match against the names of directories in path.
//
// Returns:
// An enumerable collection of the full names (including paths) for the directories
// in the directory specified by path and that match the specified search pattern.
//
// Exceptions:
// System.ArgumentException:
// path is a zero-length string, contains only white space, or contains invalid
// characters as defined by System.IO.Path.GetInvalidPathChars().- or -searchPattern
// does not contain a valid pattern.
//
// System.ArgumentNullException:
// path is null.-or-searchPattern is null.
//
// System.IO.DirectoryNotFoundException:
// path is invalid, such as referring to an unmapped drive.
//
// System.IO.IOException:
// path is a file name.
//
// System.IO.PathTooLongException:
// The specified path, file name, or combined exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters and file names must be less than 260 characters.
//
// System.Security.SecurityException:
// The caller does not have the required permission.
//
// System.UnauthorizedAccessException:
// The caller does not have the required permission.
public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern) {
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<string>>(), d => d != null));
return null;
}
//
// Summary:
// Returns an enumerable collection of directory names that match a search pattern
// in a specified path, and optionally searches subdirectories.
//
// Parameters:
// path:
// The directory to search.
//
// searchPattern:
// The search string to match against the names of directories in path.
//
// searchOption:
// One of the enumeration values that specifies whether the search operation
// should include only the current directory or should include all subdirectories.The
// default value is System.IO.SearchOption.TopDirectoryOnly.
//
// Returns:
// An enumerable collection of the full names (including paths) for the directories
// in the directory specified by path and that match the specified search pattern
// and option.
//
// Exceptions:
// System.ArgumentException:
// path is a zero-length string, contains only white space, or contains invalid
// characters as defined by System.IO.Path.GetInvalidPathChars().- or -searchPattern
// does not contain a valid pattern.
//
// System.ArgumentNullException:
// path is null.-or-searchPattern is null.
//
// System.ArgumentOutOfRangeException:
// searchOption is not a valid System.IO.SearchOption value.
//
// System.IO.DirectoryNotFoundException:
// path is invalid, such as referring to an unmapped drive.
//
// System.IO.IOException:
// path is a file name.
//
// System.IO.PathTooLongException:
// The specified path, file name, or combined exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters and file names must be less than 260 characters.
//
// System.Security.SecurityException:
// The caller does not have the required permission.
//
// System.UnauthorizedAccessException:
// The caller does not have the required permission.
public static IEnumerable<string> EnumerateDirectories(string path, string searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<string>>(), d => d != null));
return null;
}
//
// Summary:
// Returns an enumerable collection of file names in a specified path.
//
// Parameters:
// path:
// The directory to search.
//
// Returns:
// An enumerable collection of the full names (including paths) for the files
// in the directory specified by path.
//
// Exceptions:
// System.ArgumentException:
// path is a zero-length string, contains only white space, or contains invalid
// characters as defined by System.IO.Path.GetInvalidPathChars().
//
// System.ArgumentNullException:
// path is null.
//
// System.IO.DirectoryNotFoundException:
// path is invalid, such as referring to an unmapped drive.
//
// System.IO.IOException:
// path is a file name.
//
// System.IO.PathTooLongException:
// The specified path, file name, or combined exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters and file names must be less than 260 characters.
//
// System.Security.SecurityException:
// The caller does not have the required permission.
//
// System.UnauthorizedAccessException:
// The caller does not have the required permission.
public static IEnumerable<string> EnumerateFiles(string path)
{
Contract.Requires(path != null);
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<string>>(), f => f != null));
return null;
}
//
// Summary:
// Returns an enumerable collection of file names that match a search pattern
// in a specified path.
//
// Parameters:
// path:
// The directory to search.
//
// searchPattern:
// The search string to match against the names of directories in path.
//
// Returns:
// An enumerable collection of the full names (including paths) for the files
// in the directory specified by path and that match the specified search pattern.
//
// Exceptions:
// System.ArgumentException:
// path is a zero-length string, contains only white space, or contains invalid
// characters as defined by System.IO.Path.GetInvalidPathChars().- or -searchPattern
// does not contain a valid pattern.
//
// System.ArgumentNullException:
// path is null.-or-searchPattern is null.
//
// System.IO.DirectoryNotFoundException:
// path is invalid, such as referring to an unmapped drive.
//
// System.IO.IOException:
// path is a file name.
//
// System.IO.PathTooLongException:
// The specified path, file name, or combined exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters and file names must be less than 260 characters.
//
// System.Security.SecurityException:
// The caller does not have the required permission.
//
// System.UnauthorizedAccessException:
// The caller does not have the required permission.
public static IEnumerable<string> EnumerateFiles(string path, string searchPattern)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<string>>(), f => f != null));
return null;
}
//
// Summary:
// Returns an enumerable collection of file names that match a search pattern
// in a specified path, and optionally searches subdirectories.
//
// Parameters:
// path:
// The directory to search.
//
// searchPattern:
// The search string to match against the names of directories in path.
//
// searchOption:
// One of the enumeration values that specifies whether the search operation
// should include only the current directory or should include all subdirectories.The
// default value is System.IO.SearchOption.TopDirectoryOnly.
//
// Returns:
// An enumerable collection of the full names (including paths) for the files
// in the directory specified by path and that match the specified search pattern
// and option.
//
// Exceptions:
// System.ArgumentException:
// path is a zero-length string, contains only white space, or contains invalid
// characters as defined by System.IO.Path.GetInvalidPathChars().- or -searchPattern
// does not contain a valid pattern.
//
// System.ArgumentNullException:
// path is null.-or-searchPattern is null.
//
// System.ArgumentOutOfRangeException:
// searchOption is not a valid System.IO.SearchOption value.
//
// System.IO.DirectoryNotFoundException:
// path is invalid, such as referring to an unmapped drive.
//
// System.IO.IOException:
// path is a file name.
//
// System.IO.PathTooLongException:
// The specified path, file name, or combined exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters and file names must be less than 260 characters.
//
// System.Security.SecurityException:
// The caller does not have the required permission.
//
// System.UnauthorizedAccessException:
// The caller does not have the required permission.
public static IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<string>>(), f => f != null));
return null;
}
//
// Summary:
// Returns an enumerable collection of file-system entries in a specified path.
//
// Parameters:
// path:
// The directory to search.
//
// Returns:
// An enumerable collection of file-system entries in the directory specified
// by path.
//
// Exceptions:
// System.ArgumentException:
// path is a zero-length string, contains only white space, or contains invalid
// characters as defined by System.IO.Path.GetInvalidPathChars().
//
// System.ArgumentNullException:
// path is null.
//
// System.IO.DirectoryNotFoundException:
// path is invalid, such as referring to an unmapped drive.
//
// System.IO.IOException:
// path is a file name.
//
// System.IO.PathTooLongException:
// The specified path, file name, or combined exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters and file names must be less than 260 characters.
//
// System.Security.SecurityException:
// The caller does not have the required permission.
//
// System.UnauthorizedAccessException:
// The caller does not have the required permission.
public static IEnumerable<string> EnumerateFileSystemEntries(string path)
{
Contract.Requires(path != null);
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<string>>(), fs => fs != null));
return null;
}
//
// Summary:
// Returns an enumerable collection of file-system entries that match a search
// pattern in a specified path.
//
// Parameters:
// path:
// The directory to search.
//
// searchPattern:
// The search string to match against the names of directories in path.
//
// Returns:
// An enumerable collection of file-system entries in the directory specified
// by path and that match the specified search pattern.
//
// Exceptions:
// System.ArgumentException:
// path is a zero-length string, contains only white space, or contains invalid
// characters as defined by System.IO.Path.GetInvalidPathChars().- or -searchPattern
// does not contain a valid pattern.
//
// System.ArgumentNullException:
// path is null.-or-searchPattern is null.
//
// System.IO.DirectoryNotFoundException:
// path is invalid, such as referring to an unmapped drive.
//
// System.IO.IOException:
// path is a file name.
//
// System.IO.PathTooLongException:
// The specified path, file name, or combined exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters and file names must be less than 260 characters.
//
// System.Security.SecurityException:
// The caller does not have the required permission.
//
// System.UnauthorizedAccessException:
// The caller does not have the required permission.
public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<string>>(), fs => fs != null));
return null;
}
//
// Summary:
// Returns an enumerable collection of file names and directory names that match
// a search pattern in a specified path, and optionally searches subdirectories.
//
// Parameters:
// path:
// The directory to search.
//
// searchPattern:
// The search string to match against the names of directories in path.
//
// searchOption:
// One of the enumeration values that specifies whether the search operation
// should include only the current directory or should include all subdirectories.The
// default value is System.IO.SearchOption.TopDirectoryOnly.
//
// Returns:
// An enumerable collection of file-system entries in the directory specified
// by path and that match the specified search pattern and option.
//
// Exceptions:
// System.ArgumentException:
// path is a zero-length string, contains only white space, or contains invalid
// characters as defined by System.IO.Path.GetInvalidPathChars().- or -searchPattern
// does not contain a valid pattern.
//
// System.ArgumentNullException:
// path is null.-or-searchPattern is null.
//
// System.ArgumentOutOfRangeException:
// searchOption is not a valid System.IO.SearchOption value.
//
// System.IO.DirectoryNotFoundException:
// path is invalid, such as referring to an unmapped drive.
//
// System.IO.IOException:
// path is a file name.
//
// System.IO.PathTooLongException:
// The specified path, file name, or combined exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters and file names must be less than 260 characters.
//
// System.Security.SecurityException:
// The caller does not have the required permission.
//
// System.UnauthorizedAccessException:
// The caller does not have the required permission.
public static IEnumerable<string> EnumerateFileSystemEntries(string path, string searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
Contract.Ensures(Contract.ForAll(Contract.Result<IEnumerable<string>>(), fs => fs != null));
return null;
}
#endif
public static bool Exists(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
return default(bool);
}
public static DirectoryInfo CreateDirectory(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.Requires(path.Length != 0);
Contract.Ensures(Contract.Result<DirectoryInfo>() != null);
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"path is a file name.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid (for example, it is on an unmapped drive.");
return default(DirectoryInfo);
}
#if !SILVERLIGHT
public static DirectoryInfo GetParent(string path)
{
Contract.Requires(!String.IsNullOrEmpty(path));
Contract.EnsuresOnThrow<System.IO.IOException>(true, @"path is a file name.");
Contract.EnsuresOnThrow<System.IO.PathTooLongException>(true, @"The specified path, file name, or both exceed the system-defined maximum length.");
Contract.EnsuresOnThrow<System.IO.DirectoryNotFoundException>(true, @"The specified path is invalid (for example, it is on an unmapped drive.");
return default(DirectoryInfo);
}
#endif
}
}
| |
using Stylet;
using SyncTrayzor.Syncthing;
using SyncTrayzor.Utils;
using System;
using System.Globalization;
using CefSharp;
using CefSharp.Wpf;
using SyncTrayzor.Services.Config;
using System.Threading;
using SyncTrayzor.Services;
using SyncTrayzor.Properties;
using Microsoft.WindowsAPICodePack.Dialogs;
using CefSharp.Handler;
namespace SyncTrayzor.Pages
{
public class ViewerViewModel : Screen, IResourceRequestHandlerFactory, ILifeSpanHandler, IContextMenuHandler, IDisposable
{
private readonly IWindowManager windowManager;
private readonly ISyncthingManager syncthingManager;
private readonly IProcessStartProvider processStartProvider;
private readonly IConfigurationProvider configurationProvider;
private readonly IApplicationPathsProvider pathsProvider;
private readonly CustomResourceRequestHandler customResourceRequestHandler;
private readonly object cultureLock = new object(); // This can be read from many threads
private CultureInfo culture;
private double zoomLevel;
public string Location
{
get => this.WebBrowser?.Address;
private set
{
if (this.WebBrowser != null)
this.WebBrowser.Address = value;
}
}
private SyncthingState syncthingState { get; set; }
public bool ShowSyncthingStarting => this.syncthingState == SyncthingState.Starting;
public bool ShowSyncthingStopped => this.syncthingState == SyncthingState.Stopped;
public ChromiumWebBrowser WebBrowser { get; set; }
private JavascriptCallbackObject callback;
public ViewerViewModel(
IWindowManager windowManager,
ISyncthingManager syncthingManager,
IConfigurationProvider configurationProvider,
IProcessStartProvider processStartProvider,
IApplicationPathsProvider pathsProvider)
{
this.windowManager = windowManager;
this.syncthingManager = syncthingManager;
this.processStartProvider = processStartProvider;
this.configurationProvider = configurationProvider;
this.pathsProvider = pathsProvider;
var configuration = this.configurationProvider.Load();
this.zoomLevel = configuration.SyncthingWebBrowserZoomLevel;
this.syncthingManager.StateChanged += this.SyncthingStateChanged;
this.customResourceRequestHandler = new CustomResourceRequestHandler(this);
this.callback = new JavascriptCallbackObject(this);
this.SetCulture(configuration);
configurationProvider.ConfigurationChanged += this.ConfigurationChanged;
}
private void SyncthingStateChanged(object sender, SyncthingStateChangedEventArgs e)
{
this.syncthingState = e.NewState;
this.RefreshBrowser();
}
private void ConfigurationChanged(object sender, ConfigurationChangedEventArgs e)
{
this.SetCulture(e.NewConfiguration);
}
private void SetCulture(Configuration configuration)
{
lock (this.cultureLock)
{
this.culture = configuration.UseComputerCulture ? Thread.CurrentThread.CurrentUICulture : null;
}
}
protected override void OnInitialActivate()
{
if (!Cef.IsInitialized)
{
var configuration = this.configurationProvider.Load();
var settings = new CefSettings()
{
RemoteDebuggingPort = AppSettings.Instance.CefRemoteDebuggingPort,
// We really only want to set the LocalStorage path, but we don't have that level of control....
CachePath = this.pathsProvider.CefCachePath,
IgnoreCertificateErrors = true,
LogSeverity = LogSeverity.Disable,
};
// System proxy settings (which also specify a proxy for localhost) shouldn't affect us
settings.CefCommandLineArgs.Add("no-proxy-server", "1");
settings.CefCommandLineArgs.Add("disable-cache", "1");
settings.CefCommandLineArgs.Add("disable-extensions", "1");
if (configuration.DisableHardwareRendering)
{
settings.CefCommandLineArgs.Add("disable-gpu");
settings.CefCommandLineArgs.Add("disable-gpu-vsync");
settings.CefCommandLineArgs.Add("disable-gpu-compositing");
settings.CefCommandLineArgs.Add("disable-application-cache");
}
Cef.Initialize(settings);
}
var webBrowser = new ChromiumWebBrowser();
this.InitializeBrowser(webBrowser);
this.WebBrowser = webBrowser;
this.RefreshBrowser();
}
private void InitializeBrowser(ChromiumWebBrowser webBrowser)
{
webBrowser.RequestHandler = new CustomRequestHandler();
webBrowser.ResourceRequestHandlerFactory = this;
webBrowser.LifeSpanHandler = this;
webBrowser.MenuHandler = this;
webBrowser.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
webBrowser.JavascriptObjectRepository.Register("callbackObject", this.callback, isAsync: true);
// So. Fun story. From https://github.com/cefsharp/CefSharp/issues/738#issuecomment-91099199, we need to set the zoom level
// in the FrameLoadStart event. However, the IWpfWebBrowser's ZoomLevel is a DependencyProperty, and it wraps
// the SetZoomLevel method on the unmanaged browser (which is exposed directly by ChromiumWebBrowser, but not by IWpfWebBrowser).
// Now, FrameLoadState and FrameLoadEnd are called on a background thread, and since ZoomLevel is a DP, it can only be changed
// from the UI thread (it's "helpful" and does a dispatcher check for us). But, if we dispatch back to the UI thread to call
// ZoomLevel = xxx, then CEF seems to hit threading issues, and can sometimes render things entirely badly (massive icons, no
// localization, bad spacing, no JavaScript at all, etc).
// So, in this case, we need to call SetZoomLevel directly, as we can do that from the thread on which FrameLoadStart is called,
// and everything's happy.
// However, this means that the DP value isn't updated... Which means we can't use the DP at all. We have to call SetZoomLevel
// *everywhere*, and that means keeping a local field zoomLevel to track the current zoom level. Such is life
webBrowser.FrameLoadStart += (o, e) => webBrowser.SetZoomLevel(this.zoomLevel);
webBrowser.FrameLoadEnd += (o, e) =>
{
if (e.Frame.IsMain && e.Url != "about:blank")
{
// I tried to do this using Syncthing's events, but it's very painful - the DOM is updated some time
// after the event is fired. It's a lot easier to just watch for changes on the DOM.
var addOpenFolderButton =
@"var syncTrayzorAddOpenFolderButton = function(elem) {" +
@" var $buttonContainer = elem.find('.panel-footer .pull-right');" +
@" $buttonContainer.find('.panel-footer .synctrayzor-add-folder-button').remove();" +
@" $buttonContainer.prepend(" +
@" '<button class=""btn btn-sm btn-default synctrayzor-add-folder-button"" onclick=""callbackObject.openFolder(angular.element(this).scope().folder.id)"">" +
@" <span class=""fa fa-folder-open""></span>" +
@" <span style=""margin-left: 3px"">" + Resources.ViewerView_OpenFolder + @"</span>" +
@" </button>');" +
@"};" +
@"new MutationObserver(function(mutations, observer) {" +
@" for (var i = 0; i < mutations.length; i++) {" +
@" for (var j = 0; j < mutations[i].addedNodes.length; j++) {" +
@" syncTrayzorAddOpenFolderButton($(mutations[i].addedNodes[j]));" +
@" }" +
@" }" +
@"}).observe(document.getElementById('folders'), {" +
@" childList: true" +
@"});" +
@"syncTrayzorAddOpenFolderButton($('#folders'));" +
@"";
webBrowser.ExecuteScriptAsync(addOpenFolderButton);
var addFolderBrowse =
@"$('#folderPath').wrap($('<div/>').css('display', 'flex'));" +
@"$('#folderPath').after(" +
@" $('<button>').attr('id', 'folderPathBrowseButton')" +
@" .addClass('btn btn-sm btn-default')" +
@" .html('" + Resources.ViewerView_BrowseToFolder + @"')" +
@" .css({'flex-grow': 1, 'margin': '0 0 0 5px'})" +
@" .on('click', function() { callbackObject.browseFolderPath() })" +
@");" +
@"$('#folderPath').removeAttr('list');" +
@"$('#directory-list').remove();" +
@"$('#editFolder').on('shown.bs.modal', function() {" +
@" if ($('#folderPath').is('[readonly]')) {" +
@" $('#folderPathBrowseButton').attr('disabled', 'disabled');" +
@" }" +
@" else {" +
@" $('#folderPathBrowseButton').removeAttr('disabled');" +
@" }" +
@"});";
webBrowser.ExecuteScriptAsync(addFolderBrowse);
}
};
// Chinese IME workaround, copied from
// https://github.com/cefsharp/CefSharp/commit/c7c90581da7ed3dda80fd8304a856462d133d9a7
webBrowser.PreviewTextInput += (o, e) =>
{
var host = webBrowser.GetBrowser().GetHost();
var keyEvent = new KeyEvent();
foreach (var character in e.Text)
{
keyEvent.WindowsKeyCode = character;
keyEvent.Type = KeyEventType.Char;
host.SendKeyEvent(keyEvent);
}
e.Handled = true;
};
}
public void RefreshBrowserNukeCache()
{
if (this.Location == this.GetSyncthingAddress().ToString())
{
this.WebBrowser?.Reload(ignoreCache: true);
}
else if (this.syncthingManager.State == SyncthingState.Running)
{
this.Location = this.GetSyncthingAddress().ToString();
}
}
public void RefreshBrowser()
{
this.Location = "about:blank";
if (this.syncthingManager.State == SyncthingState.Running)
{
this.Location = this.GetSyncthingAddress().ToString();
}
}
public void ZoomIn()
{
this.ZoomTo(this.zoomLevel + 0.2);
}
public void ZoomOut()
{
this.ZoomTo(this.zoomLevel - 0.2);
}
public void ZoomReset()
{
this.ZoomTo(0.0);
}
private void ZoomTo(double zoomLevel)
{
if (this.WebBrowser == null || this.syncthingState != SyncthingState.Running)
return;
this.zoomLevel = zoomLevel;
this.WebBrowser.SetZoomLevel(zoomLevel);
this.configurationProvider.AtomicLoadAndSave(c => c.SyncthingWebBrowserZoomLevel = zoomLevel);
}
private void OpenFolder(string folderId)
{
if (!this.syncthingManager.Folders.TryFetchById(folderId, out var folder))
return;
this.processStartProvider.ShowFolderInExplorer(folder.Path);
}
private void BrowseFolderPath()
{
Execute.OnUIThread(() =>
{
var dialog = new CommonOpenFileDialog()
{
IsFolderPicker = true,
};
var result = dialog.ShowDialog();
if (result == CommonFileDialogResult.Ok)
{
var script =
@"$('#folderPath').val('" + dialog.FileName.Replace("\\", "\\\\").Replace("'", "\\'") + "');" +
@"$('#folderPath').change();";
this.WebBrowser.ExecuteScriptAsync(script);
}
});
}
protected override void OnClose()
{
this.WebBrowser?.Dispose();
this.WebBrowser = null;
// This is such a dirty, horrible, hacky thing to do...
// So it turns out that doesn't like being shut down, then re-initialized, see http://www.magpcss.org/ceforum/viewtopic.php?f=6&t=10807&start=10
// and others. However, if we wait a little while (presumably for the WebBrowser to die and all open connections to the subprocess
// to close), then kill it in a very dirty way (by killing the process rather than calling Cef.Shutdown), it springs back to life
// when Cef.Initialize is called again.
// I'm not 100% it's not leaking something somewhere, but it seems to work, and saves 50MB of idle memory usage
// However, I'm not comfortable enough with this to enable it permanently yet
//await Task.Delay(5000);
//CefSharpHelper.TerminateCefSharpProcess();
}
public async void Start()
{
await this.syncthingManager.StartWithErrorDialogAsync(this.windowManager);
}
private Uri GetSyncthingAddress()
{
// SyncthingManager will always request over HTTPS, whether Syncthing enforces this or not.
// However in an attempt to avoid #201 we'll use HTTP if available, and if not Syncthing will redirect us.
var uriBuilder = new UriBuilder(this.syncthingManager.Address.NormalizeZeroHost())
{
Scheme = "http"
};
return uriBuilder.Uri;
}
bool IResourceRequestHandlerFactory.HasHandlers => true;
IResourceRequestHandler IResourceRequestHandlerFactory.GetResourceRequestHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling)
{
return this.customResourceRequestHandler;
}
private CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
{
var uri = new Uri(request.Url);
// We can get http requests just after changing Syncthing's address: after we've navigated to about:blank but before navigating to
// the new address (Which we do when Syncthing hits the 'running' State).
// Therefore only open external browsers if Syncthing is actually running
if (this.syncthingManager.State == SyncthingState.Running && (uri.Scheme == "http" || uri.Scheme == "https") && uri.Host != this.GetSyncthingAddress().Host)
{
this.processStartProvider.StartDetached(request.Url);
return CefReturnValue.Cancel;
}
// See https://github.com/canton7/SyncTrayzor/issues/13
// and https://github.com/cefsharp/CefSharp/issues/534#issuecomment-60694502
var headers = request.Headers;
headers["X-API-Key"] = this.syncthingManager.ApiKey;
// I don't know why it adds these, even when we explicitly disable caching.
headers.Remove("Cache-Control");
headers.Remove("If-None-Match");
headers.Remove("If-Modified-Since");
lock (this.cultureLock)
{
if (this.culture != null)
headers["Accept-Language"] = $"{this.culture.Name};q=0.8,en;q=0.6";
}
request.Headers = headers;
return CefReturnValue.Continue;
}
void ILifeSpanHandler.OnBeforeClose(IWebBrowser browserControl, IBrowser browser)
{
}
bool ILifeSpanHandler.OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
{
this.processStartProvider.StartDetached(targetUrl);
newBrowser = null;
return true;
}
void ILifeSpanHandler.OnAfterCreated(IWebBrowser browserControl, IBrowser browser)
{
}
bool ILifeSpanHandler.DoClose(IWebBrowser browserControl, IBrowser browser)
{
return false;
}
void IContextMenuHandler.OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
{
// Clear the default menu, just leaving our custom one
model.Clear();
}
bool IContextMenuHandler.OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
{
return false;
}
void IContextMenuHandler.OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame)
{
}
bool IContextMenuHandler.RunContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback)
{
return false;
}
public void Dispose()
{
this.syncthingManager.StateChanged -= this.SyncthingStateChanged;
this.configurationProvider.ConfigurationChanged -= this.ConfigurationChanged;
}
private class CustomRequestHandler : RequestHandler
{
protected override bool OnCertificateError(IWebBrowser chromiumWebBrowser, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback)
{
// We shouldn't hit this because IgnoreCertificateErrors is true, but we do
callback.Continue(true);
return true;
}
}
private class CustomResourceRequestHandler : ResourceRequestHandler
{
private readonly ViewerViewModel parent;
public CustomResourceRequestHandler(ViewerViewModel parent)
{
this.parent = parent;
}
protected override CefReturnValue OnBeforeResourceLoad(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
{
return this.parent.OnBeforeResourceLoad(chromiumWebBrowser, browser, frame, request, callback);
}
}
private class JavascriptCallbackObject
{
private readonly ViewerViewModel parent;
public JavascriptCallbackObject(ViewerViewModel parent)
{
this.parent = parent;
}
public void OpenFolder(string folderId)
{
this.parent.OpenFolder(folderId);
}
public void BrowseFolderPath()
{
this.parent.BrowseFolderPath();
}
}
}
}
| |
//////////////////////////////////////////////////////////////////////
// Part of the Dynamic Query Engine (DQE) for Sybase ASA, used in the generated code.
// LLBLGen Pro is (c) 2002-2016 Solutions Design. All rights reserved.
// http://www.llblgen.com
//////////////////////////////////////////////////////////////////////
// This DQE's sourcecode is released under the following license:
// --------------------------------------------------------------------------------------------
//
// The MIT License(MIT)
//
// Copyright (c)2002-2016 Solutions Design. All rights reserved.
// http://www.llblgen.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.
//////////////////////////////////////////////////////////////////////
// Contributers to the code:
// - Frans Bouma [FB]
//////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Text;
using System.Collections.Generic;
using SD.LLBLGen.Pro.ORMSupportClasses;
namespace SD.LLBLGen.Pro.DQE.SybaseAsa
{
/// <summary>
/// Implements IDbSpecificCreator for SybaseAsa.
/// </summary>
[Serializable]
public class SybaseAsaSpecificCreator : DbSpecificCreatorBase
{
#region Statics
// this info is defined here and not in the base class because now a user can use more than one DQE at the same time with different providers.
private static readonly DbProviderFactoryInfo _dbProviderFactoryInfo = new DbProviderFactoryInfo();
#endregion
/// <summary>
/// CTor
/// </summary>
public SybaseAsaSpecificCreator()
{
}
/// <summary>
/// Sets the db provider factory parameter data. This will influence which DbProviderFactory is used and which enum types the field persistence info
/// field type names are resolved to.
/// </summary>
/// <param name="dbProviderFactoryInvariantName">Name of the db provider factory invariant.</param>
/// <param name="dbProviderSpecificEnumTypeName">Name of the db provider specific enum type.</param>
/// <param name="dbProviderSpecificEnumTypePropertyName">Name of the db provider specific enum type property.</param>
public static void SetDbProviderFactoryParameterData(string dbProviderFactoryInvariantName, string dbProviderSpecificEnumTypeName,
string dbProviderSpecificEnumTypePropertyName)
{
_dbProviderFactoryInfo.SetDbProviderFactoryParameterData(dbProviderFactoryInvariantName, dbProviderSpecificEnumTypeName, dbProviderSpecificEnumTypePropertyName);
}
/// <summary>
/// Sets the db provider factory parameter data. This will influence which DbProviderFactory is used and which enum types the field persistence info
/// field type names are resolved to.
/// </summary>
/// <param name="dbProviderFactoryInvariantNamesAndEnumTypeNames">The database provider factory invariant names and enum type names.</param>
/// <param name="dbProviderSpecificEnumTypePropertyName">Name of the db provider specific enum type property.</param>
public static void SetDbProviderFactoryParameterData(List<ValuePair<string, string>> dbProviderFactoryInvariantNamesAndEnumTypeNames, string dbProviderSpecificEnumTypePropertyName)
{
_dbProviderFactoryInfo.SetDbProviderFactoryParameterData(dbProviderFactoryInvariantNamesAndEnumTypeNames, dbProviderSpecificEnumTypePropertyName);
}
/// <summary>
/// Determines the db type name for value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="realValueToUse">The real value to use. Normally it's the same as value, but in cases where value as a type isn't supported, the
/// value is converted to a value which is supported.</param>
/// <returns>The name of the provider specific DbType enum name for the value specified</returns>
public override string DetermineDbTypeNameForValue(object value, out object realValueToUse)
{
realValueToUse = value;
string toReturn = "VarChar";
if (value != null)
{
switch (value.GetType().UnderlyingSystemType.FullName)
{
case "System.String":
if (((string)value).Length < 4000)
{
toReturn = "NVarChar";
}
else
{
toReturn = ((string)value).Length < 8000 ? "VarChar" : "Text";
}
break;
case "System.Byte":
toReturn = "TinyInt";
break;
case "System.Int32":
toReturn = "Integer";
break;
case "System.Int16":
toReturn = "SmallInt";
break;
case "System.Int64":
toReturn = "BigInt";
break;
case "System.DateTime":
toReturn = "DateTime";
break;
case "System.Decimal":
toReturn = "Decimal";
break;
case "System.Double":
toReturn = "Double";
break;
case "System.Single":
toReturn = "Real";
break;
case "System.Boolean":
toReturn = "Bit";
break;
case "System.Byte[]":
byte[] valueAsArray = (byte[])value;
toReturn = valueAsArray.Length < 8000 ? "VarBinary" : "Image";
break;
default:
toReturn = "VarChar";
break;
}
}
return toReturn;
}
/// <summary>
/// Creates a valid Parameter for the pattern in a LIKE statement. This is a special case, because it shouldn't rely on the type of the
/// field the LIKE statement is used with but should be the unicode varchar type.
/// </summary>
/// <param name="pattern">The pattern to be passed as the value for the parameter. Is used to determine length of the parameter.</param>
/// <param name="targetFieldDbType">Type of the target field db, in provider specific enum string format (e.g. "Int" for SqlDbType.Int)</param>
/// <returns>
/// Valid parameter for usage with the target database.
/// </returns>
/// <remarks>This version ignores targetFieldDbType and calls CreateLikeParameter(fieldname, pattern). When you override this one, also
/// override the other.</remarks>
public override DbParameter CreateLikeParameter(string pattern, string targetFieldDbType)
{
string typeOfParameter = targetFieldDbType;
switch (typeOfParameter)
{
case "Text":
typeOfParameter = "VarChar";
break;
case "Char":
case "NChar":
case "NVarChar":
case "VarChar":
// keep type
break;
default:
typeOfParameter = "NVarChar";
break;
}
return this.CreateParameter(typeOfParameter, pattern.Length, ParameterDirection.Input, false, 0, 0, pattern);
}
/// <summary>
/// Creates a valid object name (e.g. a name for a table or view) based on the fragments specified. The name is ready to use and contains
/// all alias wrappings required.
/// </summary>
/// <param name="catalogName">Name of the catalog.</param>
/// <param name="schemaName">Name of the schema.</param>
/// <param name="elementName">Name of the element.</param>
/// <returns>valid object name</returns>
public override string CreateObjectName(string catalogName, string schemaName, string elementName)
{
StringBuilder name = new StringBuilder();
string schemaNameToUse = new DynamicQueryEngine().GetNewSchemaName(this.GetNewPerCallSchemaName(schemaName));
if (schemaNameToUse.Length > 0)
{
name.AppendFormat("{0}.", CreateValidAlias(schemaNameToUse));
}
name.AppendFormat("{0}", CreateValidAlias(elementName));
return name.ToString();
}
/// <summary>
/// Routine which creates a valid alias string for the raw alias passed in. For example, the alias will be surrounded by "[]" on sqlserver.
/// Used by the RelationCollection to produce a valid alias for joins.
/// </summary>
/// <param name="rawAlias">the raw alias to make valid</param>
/// <returns>valid alias string to use.</returns>
public override string CreateValidAlias(string rawAlias)
{
if (string.IsNullOrEmpty(rawAlias))
{
return rawAlias;
}
if (rawAlias[0] == '[')
{
return rawAlias;
}
return "[" + rawAlias + "]";
}
/// <inheritdoc />
public override void AppendValidIdentifier(QueryFragments toAppendTo, string rawIdentifier)
{
if (string.IsNullOrEmpty(rawIdentifier))
{
return;
}
if (rawIdentifier[0] == '[')
{
toAppendTo.AddFragment(rawIdentifier);
}
else
{
toAppendTo.AddStringFragmentsAsSingleUnit("[", rawIdentifier, "]");
}
}
/// <summary>
/// Creates a new dynamic query engine instance
/// </summary>
/// <returns></returns>
protected override DynamicQueryEngineBase CreateDynamicQueryEngine()
{
return new DynamicQueryEngine();
}
/// <summary>
/// Sets the ADO.NET provider specific Enum type of the parameter, using the string presentation specified.
/// </summary>
/// <param name="parameter">The parameter.</param>
/// <param name="parameterType">Type of the parameter as string.</param>
protected override void SetParameterType(DbParameter parameter, string parameterType)
{
_dbProviderFactoryInfo.SetParameterType(parameter, parameterType);
}
/// <summary>
/// Constructs a call to the aggregate function specified with the field name specified as parameter.
/// </summary>
/// <param name="function">The function.</param>
/// <param name="fieldName">Name of the field.</param>
/// <returns>
/// ready to append string which represents the call to the aggregate function with the field as a parameter or the fieldname itself if
/// the aggregate function isn't known.
/// </returns>
/// <remarks>Override this method and replace function with a function which is supported if your database doesn't support the function used.</remarks>
protected override string ConstructCallToAggregateWithFieldAsParameter(AggregateFunction function, string fieldName)
{
AggregateFunction toUse = function;
switch (toUse)
{
case AggregateFunction.CountBig:
toUse = AggregateFunction.Count;
break;
case AggregateFunction.CountBigDistinct:
toUse = AggregateFunction.CountDistinct;
break;
case AggregateFunction.CountBigRow:
toUse = AggregateFunction.CountRow;
break;
}
return base.ConstructCallToAggregateWithFieldAsParameter(toUse, fieldName);
}
#region Class Property Declarations
/// <summary>
/// Gets the parameter prefix, if required. If no parameter prefix is required, this property will return the empty string (by default it returns the empty string).
/// </summary>
protected override string ParameterPrefix
{
get { return "@"; }
}
/// <summary>
/// Gets the DbProviderFactory instance to use.
/// </summary>
public override DbProviderFactory FactoryToUse
{
get { return _dbProviderFactoryInfo.FactoryToUse; }
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Newtonsoft.Json;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace Looker.RTL
{
// Ref: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1
/// <summary>
/// Interface for API transport values
/// </summary>
public interface ITransportSettings
{
/// base URL of API REST web service
string BaseUrl { get; set; }
/// whether to verify ssl certs or not. Defaults to true
bool VerifySsl { get; set; }
/// request timeout in seconds. Default to 30
int Timeout { get; set; }
/// agent tag to use for the SDK requests
string AgentTag { get; set; }
}
/// <summary>
/// HTTP response without any error handling. Based on Looker SDK response interface
/// </summary>
public interface IRawResponse
{
/// <summary>
/// ok is <c>true</c> if the response is successful, <c>false</c> otherwise
/// </summary>
bool Ok { get; }
HttpStatusCode StatusCode { get; set; }
/// <summary>
/// HTTP response status message text
/// </summary>
string StatusMessage { get; set; }
/// <summary>
/// MIME type of the response from the HTTP response header as a semicolon-delimited string
/// </summary>
string ContentType { get; set; }
/// <summary>
/// The body of the HTTP response, with minimal conversion
/// </summary>
object Body { get; set; }
}
public interface ISdkResponse<TSuccess, TError>
{
bool Ok { get; }
TSuccess Value { get; set; }
TError Error { get; set; }
}
public struct SdkResponse<TSuccess, TError> : ISdkResponse<TSuccess, TError>
{
public bool Ok => Value != null;
public TSuccess Value { get; set; }
public TError Error { get; set; }
}
/// <summary>
/// Http request authenticator callback used by AuthSession and any other automatically authenticating request processor
/// </summary>
/// <param name="request">request to update with auth properties</param>
public delegate Task<HttpRequestMessage> Authenticator(HttpRequestMessage request);
/// <summary>
/// Concrete implementation of IRawResponse interface
/// </summary>
/// <remarks>
/// The <c>Ok</c> property is read-only, determining its value by checking <c>StatusCode</c>.
/// </remarks>
public struct RawResponse : IRawResponse
{
public bool Ok => (StatusCode >= HttpStatusCode.OK && StatusCode < HttpStatusCode.Ambiguous);
public HttpMethod Method { get; set; }
public HttpStatusCode StatusCode { get; set; }
public string StatusMessage { get; set; }
public string ContentType { get; set; }
public object Body { get; set; }
}
/// <summary>
/// The HTTP request/response processing interface
/// </summary>
public interface ITransport
{
/// <summary>
/// Process a request without type conversion or error handling
/// </summary>
/// <param name="method">the <c>HttpMethod</c> to use</param>
/// <param name="path">the url path (either absolute or relative)</param>
/// <param name="queryParams">optional query parameters</param>
/// <param name="body">optional body value.
/// If the body is a <c>string</c> type, the post will be marked as <c>x-www-urlformencoded</c>.
/// Otherwise, it will be converted to JSON.
/// </param>
/// <param name="authenticator">Optional authenticator callback for the request.</param>
/// <param name="options">Transport option overrides, such as a different timeout.
/// TODO not implemented yet
/// </param>
/// <returns>the raw response to the HTTP request. The <c>Ok</c> property will be <c>False</c> if the request failed.</returns>
Task<IRawResponse> RawRequest(
HttpMethod method,
string path,
Values queryParams = null,
object body = null,
Authenticator authenticator = null,
ITransportSettings options = null
);
/// <summary>
/// Process an HTTP request and convert it to the indicated type
/// </summary>
/// <param name="method">the <c>HttpMethod</c> to use</param>
/// <param name="path">the url path (either absolute or relative)</param>
/// <param name="queryParams">optional query parameters</param>
/// <param name="body">optional body value.
/// If the body is a <c>string</c> type, the post will be marked as <c>x-www-urlformencoded</c>.
/// Otherwise, it will be converted to JSON.
/// </param>
/// <param name="authenticator">Optional authenticator callback for the request.</param>
/// <param name="options">Transport option overrides, such as a different timeout.
/// TODO not implemented yet
/// </param>
/// <typeparam name="TSuccess">Type of response if the request succeeds</typeparam>
/// <typeparam name="TError">Type of response if the request fails</typeparam>
/// <returns>A <c>TSuccess</c> response if successful, a <c>TError</c> response if not.</returns>
Task<SdkResponse<TSuccess, TError>> Request<TSuccess, TError>(
HttpMethod method,
string path,
Values queryParams = null,
object body = null,
Authenticator authenticator = null,
ITransportSettings options = null
) where TSuccess : class where TError : class;
}
/// <summary>
/// HTPP request processor
/// </summary>
public class Transport : ITransport, ITransportSettings
{
private readonly HttpClient _client;
private readonly ITransportSettings _settings;
static Transport()
{
// Long docs on DateTime support at https://docs.microsoft.com/en-us/dotnet/standard/datetime/system-text-json-support
// JsonSerializerSettings settings = new JsonSerializerSettings
// {
// DateFormatHandling = DateFormatHandling.IsoDateFormat,
// DateTimeZoneHandling = DateTimeZoneHandling.Utc
// };
}
public Transport(ITransportSettings settings, HttpClient client = null)
{
_client = client ?? new HttpClient();
_settings = settings;
}
/// <summary>
/// Makes adjustments to path based on whether the path is relative or not
/// </summary>
/// <param name="path"></param>
/// <param name="queryParams"></param>
/// <param name="authenticator"></param>
/// <returns></returns>
public string MakeUrl(string path, Values queryParams = null, Authenticator authenticator = null)
{
if (path.StartsWith("http:", StringComparison.InvariantCultureIgnoreCase)
|| path.StartsWith("https:", StringComparison.InvariantCultureIgnoreCase))
return SdkUtils.AddQueryParams(path, queryParams);
// TODO I don't think authenticator is needed here any more?
return SdkUtils.AddQueryParams($"{BaseUrl}{path}", queryParams);
}
private static RawResponse InitRawResponse(HttpResponseMessage response)
{
var raw = new RawResponse();
if (response != null)
{
raw.Method = response.RequestMessage.Method;
raw.StatusCode = response.StatusCode;
raw.StatusMessage = response.ReasonPhrase;
response.Content.Headers.TryGetValues("Content-Type", out var values);
raw.ContentType = string.Join("; ", values ?? new [] {"text/plain"});
}
else
{
raw.StatusCode = HttpStatusCode.BadRequest;
raw.ContentType = "text/plain";
raw.Body = new SdkError("Response is null. That's all I know.");
}
return raw;
}
public async Task<IRawResponse> RawRequest(
HttpMethod method,
string path,
Values queryParams = null,
object body = null,
Authenticator authenticator = null,
ITransportSettings options = null
)
{
var url = MakeUrl(path, queryParams, authenticator);
var request = new HttpRequestMessage(method,
url);
request.Headers.Add(Constants.LookerAppiId, _settings.AgentTag);
if (body != null)
{
if (body is string)
{
request.Content = new StringContent(
body.ToString(),
Encoding.UTF8,
"application/x-www-form-urlencoded");
}
else
{
request.Content =
new StringContent(
JsonSerializer.Serialize(body, new JsonSerializerOptions { IgnoreNullValues = true }),
Encoding.UTF8,
"application/json");
}
}
if (authenticator != null) request = await authenticator(request);
RawResponse result = new RawResponse();
HttpResponseMessage response = null;
try
{
response = await _client.SendAsync(request);
result = InitRawResponse(response);
// if (response.IsSuccessStatusCode)
await using var stream = await response.Content.ReadAsStreamAsync();
// Simple content conversion here to make body easily readable in consumers
switch (SdkUtils.ResponseMode(result.ContentType))
{
case ResponseMode.Binary:
result.Body = SdkUtils.StreamToByteArray(stream);
break;
case ResponseMode.String:
using (var sr = new StreamReader(stream))
{
result.Body = await sr.ReadToEndAsync();
}
break;
case ResponseMode.Unknown:
result.Body = SdkUtils.StreamToByteArray(stream);
break;
default:
throw new ArgumentOutOfRangeException($"Unrecognized Content Type {result.ContentType}");
}
}
catch (Exception e)
{
result = InitRawResponse(response);
result.Body = e;
}
return result;
}
public static SdkResponse<TSuccess, TError> ParseResponse<TSuccess, TError>(IRawResponse response)
where TSuccess : class where TError : class
{
if (response.Body is Exception)
{
return new SdkResponse<TSuccess, TError> { Error = response.Body as TError};
}
switch (SdkUtils.ResponseMode(response.ContentType))
{
case ResponseMode.Binary:
return new SdkResponse<TSuccess, TError> {Value = response.Body as TSuccess};
case ResponseMode.String:
if (response.ContentType.StartsWith("application/json"))
{
return new SdkResponse<TSuccess, TError>
{
Value = JsonConvert.DeserializeObject<TSuccess>(response.Body.ToString())
};
}
else
{
return new SdkResponse<TSuccess, TError> {Value = response.Body.ToString() as TSuccess};
}
case ResponseMode.Unknown:
return new SdkResponse<TSuccess, TError>
{
Error = JsonConvert.DeserializeObject<TError>(response.Body.ToString())
};
default:
throw new ArgumentOutOfRangeException($"Unrecognized Content Type {response.ContentType}");
}
}
public async Task<SdkResponse<TSuccess, TError>> Request<TSuccess, TError>(
HttpMethod method,
string path,
Values queryParams = null,
object body = null,
Authenticator authenticator = null,
ITransportSettings options = null
) where TSuccess : class where TError : class
{
var raw = await RawRequest(method, path, queryParams, body, authenticator, options);
return ParseResponse<TSuccess, TError>(raw);
}
public string BaseUrl
{
get => _settings.BaseUrl;
set => _settings.BaseUrl = value;
}
public bool VerifySsl
{
get => _settings.VerifySsl;
set => _settings.VerifySsl = value;
}
public int Timeout
{
get => _settings.Timeout;
set => _settings.Timeout = value;
}
public string AgentTag
{
get => _settings.AgentTag;
set => _settings.AgentTag = value;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Afnor.Silverlight.Toolkit.Collections;
using Afnor.Silverlight.Toolkit.ViewServices;
using AutoMapper;
using EspaceClient.BackOffice.Silverlight.Business.Depots;
using EspaceClient.BackOffice.Silverlight.Business.Interfaces;
using EspaceClient.BackOffice.Silverlight.Business.Loader;
using EspaceClient.BackOffice.Silverlight.ViewModels.Common.Modularity;
using EspaceClient.BackOffice.Silverlight.ViewModels.Common.Selecteur;
using EspaceClient.BackOffice.Silverlight.ViewModels.DtoViewModels;
using EspaceClient.BackOffice.Silverlight.ViewModels.Messages;
using EspaceClient.FrontOffice.Domaine;
using EspaceClient.FrontOffice.Infrastructure.Constant;
using nRoute.Components;
using nRoute.Components.Composition;
using OGDC.Silverlight.Toolkit.Services.Services;
namespace EspaceClient.BackOffice.Silverlight.ViewModels.GestionClient.DemandeContact.Tabs.Details
{
public class InformationViewModel : LazyPanel<DemandeContactEntityViewModel>
{
private readonly IDepotRessource _ressourceDepot;
private readonly IApplicationContext _applicationContext;
private readonly IResourceWrapper _ressourceWrapper;
private readonly IDepotDemandeContact _demandeContact;
private readonly ILoaderReferentiel _referentiel;
private readonly IMessenging _messengingService;
private readonly IDepotPersonne _personneDepot;
private readonly IDepotClient _clientDepot;
private readonly IDepotSociete _societeDepot;
private readonly ModelBuilders.GestionClient.ClientPM.IModelBuilderDetails _buildeDetailsSociete;
private readonly ModelBuilders.Administration.Personne.IModelBuilderDetails _buildeDetailsPersonne;
private readonly ModelBuilders.GestionClient.ClientPP.IModelBuilderDetails _buildeDetailsClient;
private INavigatableChildWindowService _childWindowService;
private IEnumerable<StatutDemandeContactDto> _statuts;
public IEnumerable<StatutDemandeContactDto> Statuts
{
get
{
return _statuts;
}
set
{
if (_statuts != value)
{
_statuts = value;
NotifyPropertyChanged(() => Statuts);
}
}
}
private IEnumerable<CategorieContactDto> _categories;
public IEnumerable<CategorieContactDto> Categories
{
get
{
return _categories;
}
set
{
if (_categories != value)
{
_categories = value;
NotifyPropertyChanged(() => Categories);
}
}
}
private IEnumerable<LangueDto> _langues;
public IEnumerable<LangueDto> Langues
{
get
{
return _langues;
}
set
{
if (_langues != value)
{
_langues = value;
NotifyPropertyChanged(() => Langues);
}
}
}
private IEnumerable<ContactDto> _sujets;
public IEnumerable<ContactDto> Sujets
{
get
{
return _sujets;
}
set
{
if (_sujets != value)
{
_sujets = value;
NotifyPropertyChanged(() => Sujets);
}
}
}
private IEnumerable<DemandeContactGroupeDestinataireDto> _demandeContactGroupeDestinataire;
public IEnumerable<DemandeContactGroupeDestinataireDto> DemandeContactGroupeDestinataires
{
get
{
return _demandeContactGroupeDestinataire;
}
set
{
if (_demandeContactGroupeDestinataire != value)
{
_demandeContactGroupeDestinataire = value;
NotifyPropertyChanged(() => DemandeContactGroupeDestinataires);
}
}
}
public bool IsFrancais
{
get
{
return (Entity.DemandeContact.LangueID == (long)LanguageCultureCode.French);
}
}
public ICommand OpenPersonne { get; private set; }
public ICommand OpenSociete { get; private set; }
public ICommand CommandPopulateSujets { get; private set; }
public ICommand CommandChangeLangue { get; private set; }
[ResolveConstructor]
public InformationViewModel(
ILoaderReferentiel referentiel,
IMessenging messengingService,
IDepotDemandeContact demandeContact,
IDepotPersonne personneDepot,
IDepotClient clientDepot,
IDepotSociete societeDepot,
IDepotRessource ressourceDepot,
IApplicationContext applicationContext,
IResourceWrapper ressourceWrapper,
INavigatableChildWindowService childWindowService,
ModelBuilders.Administration.Personne.IModelBuilderDetails buildeDetailsPersonne,
ModelBuilders.GestionClient.ClientPM.IModelBuilderDetails buildeDetailsSociete,
ModelBuilders.GestionClient.ClientPP.IModelBuilderDetails buildeDetailsClient)
: base()
{
_referentiel = referentiel;
_demandeContact = demandeContact;
_messengingService = messengingService;
_personneDepot = personneDepot;
_clientDepot = clientDepot;
_societeDepot = societeDepot;
_ressourceDepot = ressourceDepot;
_applicationContext = applicationContext;
_ressourceWrapper = ressourceWrapper;
_childWindowService = childWindowService;
_buildeDetailsPersonne = buildeDetailsPersonne;
_buildeDetailsSociete = buildeDetailsSociete;
_buildeDetailsClient = buildeDetailsClient;
InitializeCommands();
InitializeUI();
}
private void InitializeCommands()
{
// OpenPersonne = new ActionCommand<long>(OnOpenPersonne);
// OpenSociete = new ActionCommand<long>(OnOpenSociete);
CommandPopulateSujets = new ActionCommand<long>(OnCommandPopulateSujets);
CommandChangeLangue = new ActionCommand(OnCommandChangeLangue);
}
private void OnCommandChangeLangue()
{
NotifyPropertyChanged(() => IsFrancais);
}
public void OnCommandPopulateSujets(long categorieID)
{
OnCommandPopulateSujets(categorieID, false);
}
public void OnCommandPopulateSujets(long categorieID, bool isLoading)
{
if (!isLoading)
Entity.DemandeContact.ContactID = -1;
if (categorieID > 0)
Sujets = _referentiel.Referentiel.Contacts.Where(x => x.CategorieContactID == categorieID).WithEmptyItem(() => new ContactDto() { ID = -1, LibelleComboFrancais = " ", LibelleComboAnglais = " " });
else
Sujets = new List<ContactDto>().WithEmptyItem(() => new ContactDto() { ID = -1, LibelleComboFrancais = " ", LibelleComboAnglais = " " });
Entity.DemandeContact.UpdateSujetByCategorie();
Entity.UpdateCategorie();
}
private void InitializeUI()
{
Statuts = _referentiel.Referentiel.StatutDemandeContacts.WithEmptyItem(() => new StatutDemandeContactDto() { ID = -1, Libelle = " " });
Categories = _referentiel.Referentiel.CategorieContacts.WithEmptyItem(() => new CategorieContactDto() { ID = -1, Description = " " });
Sujets = new List<ContactDto>().WithEmptyItem(() => new ContactDto() { ID = -1, LibelleComboFrancais = " ", LibelleComboAnglais = " " });
Langues = _referentiel.Referentiel.Langues;
DemandeContactGroupeDestinataires = _referentiel.Referentiel.DemandeContactGroupeDestinataires.WithEmptyItem(() => new DemandeContactGroupeDestinataireDto() { ID = -1, Libelle = " " });
}
public override VueCode Code { get { return VueCode.DemandeContactInformation; } }
public override Nullable<long> VueIdentifier
{
get
{
return Entity.DemandeContact.ID;
}
}
public override void Load()
{
if (Parent.Parent.IsCreating == false)
{
BeginLoading();
Entity.ChangeTracker.EndTracking(Entity);
_demandeContact.GetDemandeContactCompositeByID(
Entity.DemandeContact.ID,
composite =>
{
if (!composite.DemandeContact.DemandeContactGroupeDestinataireID.HasValue)
composite.DemandeContact.DemandeContactGroupeDestinataireID = -1;
Entity.DemandeContact = Mapper.Map<DemandeContactDto, DemandeContactDtoViewModel>(composite.DemandeContact);
Entity.Personne = Mapper.Map<PersonneDto, PersonneDtoViewModel>(composite.Personne);
Entity.Societe = Mapper.Map<SocieteDto, SocieteDtoViewModel>(composite.Societe);
Entity.DemandeContact.Ressource = new SelecteurRessourceViewModel(
_referentiel,
_childWindowService,
_ressourceDepot,
_messengingService,
_applicationContext,
_ressourceWrapper)
{
SelectedRessource = composite.Ressource,
};
Entity.CategorieID = composite.CategorieID;
if (Entity.CategorieID.HasValue)
OnCommandPopulateSujets(Entity.CategorieID.Value, true);
Entity.ChangeTracker.BeginTracking(Entity);
EndLoading();
},
error =>
{
_messengingService.Publish(new ErrorMessage(error));
Entity.ChangeTracker.BeginTracking(Entity);
EndLoading();
});
}
else
{
Entity.ChangeTracker.BeginTracking(Entity);
}
EnableLazyLoading = false;
}
//private void OnOpenPersonne(long selectedId)
//{
// ClientPPHelper.AddClientPPTab(selectedId, _messengingService, _clientDepot, _buildeDetailsClient, _referentiel);
//}
//private void OnOpenSociete(long selectedId)
//{
// ClientPMHelper.AddClientPMTab(selectedId, _messengingService, _societeDepot, _buildeDetailsSociete, _referentiel);
//}
}
}
| |
using System.Collections.Generic;
using libtcod;
using Magecrawl.Interfaces;
using Magecrawl.Utilities;
namespace Magecrawl.GameUI.ListSelection
{
public delegate void ListItemSelected(INamedItem item);
public delegate bool ListItemShouldBeEnabled(INamedItem item);
// This code is scary, I admit it. It looks complex, but it has to be.
// Scrolling inventory right, when it might be lettered, is hard.
internal class ListSelectionPainter : PainterBase
{
private bool m_enabled; // Are we showing the inventory
private IList<INamedItem> m_itemList; // Items to display
private int m_lowerRange; // If we're scrolling, the loweset number item to show
private int m_higherRange; // Last item to show
private bool m_isScrollingNeeded; // Do we need to scroll at all?
private int m_cursorPosition; // What item is the cursor on
private bool m_useCharactersNextToItems; // Should we put letters next to each letter
private bool m_shouldNotResetCursorPosition; // If set, the next time we show the inventory window, we don't reset the position.
private ListItemShouldBeEnabled m_shouldBeSelectedDelegate; // Called for each item to determine if we should enable it if not null
private string m_title;
private DialogColorHelper m_dialogColorHelper;
private const int ScrollAmount = 8;
private const int InventoryWindowOffset = 5;
private const int InventoryItemWidth = UIHelper.ScreenWidth - 10;
private const int InventoryItemHeight = UIHelper.ScreenHeight - 10;
private const int NumberOfLinesDisplayable = InventoryItemHeight - 2;
internal ListSelectionPainter()
{
m_dialogColorHelper = new DialogColorHelper();
m_enabled = false;
m_shouldNotResetCursorPosition = false;
}
public override void UpdateFromNewData(IGameEngine engine, Point mapUpCorner, Point cursorPosition)
{
m_shouldNotResetCursorPosition = false;
}
public override void DrawNewFrame(TCODConsole screen)
{
if (m_enabled)
{
m_higherRange = m_isScrollingNeeded ? m_lowerRange + NumberOfLinesDisplayable : m_itemList.Count;
screen.printFrame(InventoryWindowOffset, InventoryWindowOffset, InventoryItemWidth, InventoryItemHeight, true, TCODBackgroundFlag.Set, m_title);
// Start lettering from our placementOffset.
char currentLetter = 'a';
if (m_useCharactersNextToItems)
{
for (int i = 0; i < m_lowerRange; ++i)
currentLetter = IncrementLetter(currentLetter);
}
int positionalOffsetFromTop = 0;
m_dialogColorHelper.SaveColors(screen);
int farRightPaddingAmount = DetermineFarRightPaddingForMagicList();
for (int i = m_lowerRange; i < m_higherRange; ++i)
{
string displayString = m_itemList[i].DisplayName;
m_dialogColorHelper.SetColors(screen, i == m_cursorPosition, m_shouldBeSelectedDelegate(m_itemList[i]));
if (displayString.Contains('\t'.ToString()))
{
// This is the case for Tab Seperated Spaces, used for magic lists and such
string[] sectionArray = displayString.Split(new char[] { '\t' }, 3);
screen.print(InventoryWindowOffset + 1, InventoryWindowOffset + 1 + positionalOffsetFromTop, currentLetter + " - " + sectionArray[0]);
if (sectionArray.Length > 1)
{
screen.print(InventoryWindowOffset + (InventoryItemWidth / 2), InventoryWindowOffset + 1 + positionalOffsetFromTop, sectionArray[1]);
if (sectionArray.Length > 2)
{
screen.printEx(InventoryWindowOffset - 2 + InventoryItemWidth, InventoryWindowOffset + 1 + positionalOffsetFromTop, TCODBackgroundFlag.Set, TCODAlignment.RightAlignment, sectionArray[2].PadRight(farRightPaddingAmount));
}
}
}
else
{
string printString;
if (m_useCharactersNextToItems)
printString = string.Format("{0} - {1}", currentLetter, displayString);
else
printString = " - " + displayString;
screen.print(InventoryWindowOffset + 1, InventoryWindowOffset + 1 + positionalOffsetFromTop, printString);
}
currentLetter = IncrementLetter(currentLetter);
positionalOffsetFromTop++;
}
m_dialogColorHelper.ResetColors(screen);
}
}
// A "magic" list is one that embeds '\t' in it for columns. If we have 3 columns, figure out how much we should pad the right
// most one so it stays lined up nice
private int DetermineFarRightPaddingForMagicList()
{
int farRightPaddingAmount = 0;
for (int i = 0; i < m_itemList.Count; ++i)
{
string displayString = m_itemList[i].DisplayName;
if (displayString.Contains('\t'.ToString()))
{
// This is the case for Tab Seperated Spaces, used for magic lists and such
string[] sectionArray = displayString.Split(new char[] { '\t' }, 3);
if (sectionArray.Length > 2)
farRightPaddingAmount = System.Math.Max(farRightPaddingAmount, sectionArray[2].Length);
}
}
return farRightPaddingAmount;
}
public bool IsEnabled(INamedItem item)
{
return m_shouldBeSelectedDelegate != null ? m_shouldBeSelectedDelegate(item) : true;
}
internal INamedItem CurrentSelection
{
get
{
if (m_itemList.Count <= m_cursorPosition)
return null;
return m_itemList[m_cursorPosition];
}
}
internal void SelectionFromChar(char toSelect, ListItemSelected onSelect)
{
if (m_useCharactersNextToItems)
{
List<char> listOfLettersUsed = GetListOfLettersUsed();
if (listOfLettersUsed.Contains(toSelect))
{
m_cursorPosition = listOfLettersUsed.IndexOf(toSelect);
onSelect(m_itemList[m_cursorPosition]);
}
}
}
internal void Enable(List<INamedItem> data, string title, bool useLetters, ListItemShouldBeEnabled shouldBeSelectedDelegate)
{
if (!m_shouldNotResetCursorPosition)
{
m_cursorPosition = 0;
m_lowerRange = 0;
m_higherRange = 0;
}
else
{
m_shouldNotResetCursorPosition = false;
}
// This gets set before UpdateFromNewData in case we say we want letters but have too many items
m_useCharactersNextToItems = useLetters;
UpdateFromNewData(data);
m_shouldBeSelectedDelegate = shouldBeSelectedDelegate;
m_title = title;
m_enabled = true;
}
internal void Disable()
{
m_enabled = false;
}
internal bool SaveSelectionPosition
{
get
{
return m_shouldNotResetCursorPosition;
}
set
{
m_shouldNotResetCursorPosition = value;
}
}
private void UpdateFromNewData(List<INamedItem> data)
{
m_itemList = data;
m_isScrollingNeeded = m_itemList.Count > NumberOfLinesDisplayable;
// If we're going to run out of letters, don't show em.
if (m_itemList.Count > 26 * 2)
m_useCharactersNextToItems = false;
}
private List<char> GetListOfLettersUsed()
{
if (!m_useCharactersNextToItems)
throw new System.ArgumentException("GetListOfLettersUsed can't be called when not using letters next to names");
List<char> returnList = new List<char>();
char elt = 'a';
while (elt != MapSelectionOffsetToLetter(m_itemList.Count))
{
returnList.Add(elt);
elt = IncrementLetter(elt);
}
return returnList;
}
private static char MapSelectionOffsetToLetter(int offset)
{
if (offset > 25)
return (char)('A' + (char)(offset - 26));
else
return (char)('a' + (char)offset);
}
private static char IncrementLetter(char letter)
{
if (letter == 'Z')
return 'a';
else if (letter == 'z')
return 'A';
else
return (char)(((int)letter) + 1);
}
internal void MoveInventorySelection(Direction cursorDirection)
{
if (cursorDirection == Direction.North)
{
if (m_cursorPosition > 0)
{
if (m_isScrollingNeeded && (m_cursorPosition == m_lowerRange))
{
m_lowerRange -= ScrollAmount;
if (m_lowerRange < 0)
m_lowerRange = 0;
}
m_cursorPosition--;
}
}
if (cursorDirection == Direction.South && m_cursorPosition < m_itemList.Count - 1)
{
// If we need scrolling and we're pointed at the end of the list and there's more to show.
if (m_isScrollingNeeded && (m_cursorPosition == (m_lowerRange - 1 + NumberOfLinesDisplayable)) && (m_lowerRange + NumberOfLinesDisplayable < m_itemList.Count))
{
m_lowerRange += ScrollAmount;
if ((m_lowerRange + NumberOfLinesDisplayable) > m_itemList.Count)
m_lowerRange = m_itemList.Count - NumberOfLinesDisplayable;
m_cursorPosition++;
}
else
{
if ((m_cursorPosition + 1) < m_itemList.Count)
m_cursorPosition++;
}
}
}
}
}
| |
// SharpMath - C# Mathematical Library
// Copyright (c) 2014 Morten Bakkedal
// This code is published under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
namespace SharpMath.Optimization.DualNumbers
{
/// <summary>
/// To avoid errors in handcrafted <see cref="DualNumber" /> instances this derivative tester may be used. The verification is done by a simple
/// finite differences approximation, where each component of the user-provided point is perturbed one by one. The second derivatives
/// are approximated by finite differences of the first derivatives, so first derivatives should be tested before the second derivatives.
/// </summary>
public class DualNumberDerivativeTest
{
private Function function;
private ImmutableVariableCollection variables;
private int n;
private double tolerance, perturbation;
private bool showAll, showNames;
/// <summary>
/// Creates a new instance of the derivative tester.
/// </summary>
/// <param name="function">The function to test.</param>
/// <param name="variables">The variables to test.</param>
public DualNumberDerivativeTest(Function function, params Variable[] variables)
{
this.function = function;
this.variables = ImmutableVariableCollection.Create(variables);
n = variables.Length;
tolerance = 0.0001;
perturbation = 1.0e-6;
showAll = false;
showNames = false;
}
/// <summary>
/// Creates a new instance of the derivative tester.
/// </summary>
/// <param name="function">The function to test constructed using <see cref="DualNumberFunction" />.</param>
/// <param name="variables">The variables that the function depends on.</param>
public DualNumberDerivativeTest(Func<IDualNumberTransform, DualNumber> function, params Variable[] variables)
: this(DualNumberFunction.Create(function, variables), variables)
{
}
public void Test(IPoint point)
{
// http://en.wikipedia.org/wiki/Finite_difference_coefficients
//int k = 2;
//int[] xdelta = new int[] { 0, 1 };
//double[] wdelta = new double[] { -1.0, 1.0 };
//int k = 2;
//int[] xdelta = new int[] { -1, 1 };
//double[] wdelta = new double[] { -0.5, 0.5 };
int k = 4;
int[] xdelta = new int[] { -2, -1, 1, 2 };
double[] wdelta = new double[] { 0.083333333333333329, -0.66666666666666663, 0.66666666666666663, -0.083333333333333329 };
//int k = 6;
//int[] xdelta = new int[] { -3, -2, -1, 1, 2, 3 };
//double[] wdelta = new double[] { -0.016666666666666666, 0.15, -0.75, 0.75, -0.15, 0.016666666666666666 };
// The following test code is heavily inspired by Ipopt::TNLPAdapter::CheckDerivatives in IPOPT (see IpTNLPAdapter.cpp).
Console.WriteLine("Evaluating unperturbed function");
Console.WriteLine();
DualNumber y = Compute(point);
double[] delta = new double[n];
DualNumber[] ydelta = new DualNumber[n];
Console.WriteLine("Starting derivative checker for first derivatives");
Console.WriteLine();
for (int i = 0; i < n; i++)
{
double exact = y.Gradient[i];
try
{
if (point[variables[i]] != 0.0)
{
delta[i] = perturbation * Math.Abs(point[variables[i]]);
}
else
{
// Don't know the scale in this particular case. Choose an arbitrary scale (i.e. 1).
delta[i] = perturbation;
}
double approx = 0.0;
for (int j = 0; j < k; j++)
{
approx += wdelta[j] * ComputeDelta(point, i, xdelta[j] * delta[i]).Value;
}
approx /= delta[i];
ydelta[i] = ComputeDelta(point, i, delta[i]);
//approx = (ydelta[i].Value - y.Value) / delta[i];
double relativeError = Math.Abs(approx - exact) / Math.Max(1.0, Math.Abs(approx));
bool error = relativeError >= tolerance;
if (error || showAll)
{
Console.WriteLine("{0} Gradient [{1} {2}] = {3} ~ {4} [{5}]",
error ? "*" : " ", FormatIndex(-1), FormatIndex(i), FormatValue(exact), FormatValue(approx), FormatRelativeValue(relativeError));
}
}
catch (ArithmeticException)
{
Console.WriteLine("* Gradient [{0} {1}] = {2} ~ FAILED", FormatIndex(-1), FormatIndex(i), FormatValue(exact));
}
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Starting derivative checker for second derivatives");
Console.WriteLine();
for (int i = 0; i < n; i++)
{
// Though the Hessian is supposed to be symmetric test the full matrix anyway
// (the finite difference could very well be different and provide insight).
for (int j = 0; j < n; j++)
{
double exact = y.Hessian[i, j];
try
{
double approx = 0.0;
for (int l = 0; l < k; l++)
{
approx += wdelta[l] * ComputeDelta(point, i, xdelta[l] * delta[i]).Gradient[j];
}
approx /= delta[i];
//approx = (ydelta[i].Gradient[j] - y.Gradient[j]) / delta[i];
double relativeError = Math.Abs(approx - exact) / Math.Max(1.0, Math.Abs(approx));
bool error = relativeError >= tolerance;
if (error || showAll)
{
Console.WriteLine("{0} Hessian [{1},{2}] = {3} ~ {4} [{5}]",
error ? "*" : " ", FormatIndex(i), FormatIndex(j), FormatValue(exact), FormatValue(approx), FormatRelativeValue(relativeError));
}
}
catch (ArithmeticException)
{
Console.WriteLine("* Hessian [{0},{1}] = {2} ~ FAILED", FormatIndex(i), FormatIndex(j), FormatValue(exact));
}
}
}
}
private string FormatValue(double value)
{
return value.ToString("0.00000000000000e+00", CultureInfo.InvariantCulture).PadLeft(21);
}
private string FormatRelativeValue(double value)
{
return value.ToString("0.000e+00", CultureInfo.InvariantCulture).PadLeft(10);
}
private string FormatIndex(int index)
{
int size = 4;
if (showNames)
{
// Try to resolve the name of the variables.
size = 12;
if (index != -1 && variables[index].Name != null)
{
return variables[index].Name.PadRight(size);
}
// Fall through to show the index if not defined.
}
return (index != -1 ? index.ToString() : "").PadLeft(size);
}
/*private IPoint PointDelta(IPoint point, int index, double delta)
{
Dictionary<Variable, double> values = new Dictionary<Variable, double>(point.ToDictionary());
values[variables[index]] = values[variables[index]] + delta;
return new Point(values);
}*/
public DualNumber Compute(IPoint point)
{
double value = function.Value(point);
double[] gradientArray = new double[n];
double[] hessianArray = new double[DualNumber.HessianSize(n)];
for (int i = 0, k = 0; i < n; i++)
{
Function derivative = function.Derivative(variables[i]);
gradientArray[i] = derivative.Value(point);
for (int j = i; j < n; j++, k++)
{
hessianArray[k] = derivative.Derivative(variables[j]).Value(point);
}
}
return new DualNumber(value, gradientArray, hessianArray);
}
public DualNumber ComputeDelta(IPoint point, int index, double delta)
{
if (index < 0 || index >= n)
{
throw new IndexOutOfRangeException();
}
VariableAssignment[] assignments = new VariableAssignment[n];
for (int i = 0; i < n; i++)
{
Variable variable = variables[i];
double value = point[variable];
// Add delta to the selected variable.
if (i == index)
{
value += delta;
}
assignments[i] = new VariableAssignment(variable, value);
}
return Compute(new Point(assignments));
}
/// <summary>
/// Threshold for indicating wrong derivative.
/// </summary>
public double Tolerance
{
get
{
return tolerance;
}
set
{
tolerance = value;
}
}
/// <summary>
/// The relative size of the perturbation in the derivative test. The default value (1e-8, about the square root of the machine precision) is probably fine in most cases.
/// </summary>
public double Perturbation
{
get
{
return perturbation;
}
set
{
perturbation = value;
}
}
/// <summary>
/// Toggle to show the user-provided and estimated derivative values with the relative deviation for each single partial derivative.
/// </summary>
public bool ShowAll
{
get
{
return showAll;
}
set
{
showAll = value;
}
}
/// <summary>
/// Show resolved variable names instead of indices.
/// </summary>
public bool ShowNames
{
get
{
return showNames;
}
set
{
showNames = value;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
/*============================================================
**
**
**
** Provides a way for an app to not start an operation unless
** there's a reasonable chance there's enough memory
** available for the operation to succeed.
**
**
===========================================================*/
using System;
using System.IO;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Security.Permissions;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
/*
This class allows an application to fail before starting certain
activities. The idea is to fail early instead of failing in the middle
of some long-running operation to increase the survivability of the
application and ensure you don't have to write tricky code to handle an
OOM anywhere in your app's code (which implies state corruption, meaning you
should unload the appdomain, if you have a transacted environment to ensure
rollback of individual transactions). This is an incomplete tool to attempt
hoisting all your OOM failures from anywhere in your worker methods to one
particular point where it is easier to handle an OOM failure, and you can
optionally choose to not start a workitem if it will likely fail. This does
not help the performance of your code directly (other than helping to avoid
AD unloads). The point is to avoid starting work if it is likely to fail.
The Enterprise Services team has used these memory gates effectively in the
unmanaged world for a decade.
In Whidbey, we will simply check to see if there is enough memory available
in the OS's page file & attempt to ensure there might be enough space free
within the process's address space (checking for address space fragmentation
as well). We will not commit or reserve any memory. To avoid race conditions with
other threads using MemoryFailPoints, we'll also keep track of a
process-wide amount of memory "reserved" via all currently-active
MemoryFailPoints. This has two problems:
1) This can account for memory twice. If a thread creates a
MemoryFailPoint for 100 MB then allocates 99 MB, we'll see 99 MB
less free memory and 100 MB less reserved memory. Yet, subtracting
off the 100 MB is necessary because the thread may not have started
allocating memory yet. Disposing of this class immediately after
front-loaded allocations have completed is a great idea.
2) This is still vulnerable to race conditions with other threads that don't use
MemoryFailPoints.
So this class is far from perfect. But it may be good enough to
meaningfully reduce the frequency of OutOfMemoryExceptions in managed apps.
In Orcas or later, we might allocate some memory from the OS and add it
to a allocation context for this thread. Obviously, at that point we need
some way of conveying when we release this block of memory. So, we
implemented IDisposable on this type in Whidbey and expect all users to call
this from within a using block to provide lexical scope for their memory
usage. The call to Dispose (implicit with the using block) will give us an
opportunity to release this memory, perhaps. We anticipate this will give
us the possibility of a more effective design in a future version.
In Orcas, we may also need to differentiate between allocations that would
go into the normal managed heap vs. the large object heap, or we should
consider checking for enough free space in both locations (with any
appropriate adjustments to ensure the memory is contiguous).
*/
namespace System.Runtime
{
public sealed class MemoryFailPoint : CriticalFinalizerObject, IDisposable
{
// Find the top section of user mode memory. Avoid the last 64K.
// Windows reserves that block for the kernel, apparently, and doesn't
// let us ask about that memory. But since we ask for memory in 1 MB
// chunks, we don't have to special case this. Also, we need to
// deal with 32 bit machines in 3 GB mode.
// Using Win32's GetSystemInfo should handle all this for us.
private static readonly ulong TopOfMemory;
// Walking the address space is somewhat expensive, taking around half
// a millisecond. Doing that per transaction limits us to a max of
// ~2000 transactions/second. Instead, let's do this address space
// walk once every 10 seconds, or when we will likely fail. This
// amortization scheme can reduce the cost of a memory gate by about
// a factor of 100.
private static long hiddenLastKnownFreeAddressSpace = 0;
private static long hiddenLastTimeCheckingAddressSpace = 0;
private const int CheckThreshold = 10 * 1000; // 10 seconds
private static long LastKnownFreeAddressSpace
{
get { return Volatile.Read(ref hiddenLastKnownFreeAddressSpace); }
set { Volatile.Write(ref hiddenLastKnownFreeAddressSpace, value); }
}
private static long AddToLastKnownFreeAddressSpace(long addend)
{
return Interlocked.Add(ref hiddenLastKnownFreeAddressSpace, addend);
}
private static long LastTimeCheckingAddressSpace
{
get { return Volatile.Read(ref hiddenLastTimeCheckingAddressSpace); }
set { Volatile.Write(ref hiddenLastTimeCheckingAddressSpace, value); }
}
// When allocating memory segment by segment, we've hit some cases
// where there are only 22 MB of memory available on the machine,
// we need 1 16 MB segment, and the OS does not succeed in giving us
// that memory. Reasons for this could include:
// 1) The GC does allocate memory when doing a collection.
// 2) Another process on the machine could grab that memory.
// 3) Some other part of the runtime might grab this memory.
// If we build in a little padding, we can help protect
// ourselves against some of these cases, and we want to err on the
// conservative side with this class.
private const int LowMemoryFudgeFactor = 16 << 20;
// Round requested size to a 16MB multiple to have a better granularity
// when checking for available memory.
private const int MemoryCheckGranularity = 16;
// Note: This may become dynamically tunable in the future.
// Also note that we can have different segment sizes for the normal vs.
// large object heap. We currently use the max of the two.
private static readonly ulong GCSegmentSize;
// For multi-threaded workers, we want to ensure that if two workers
// use a MemoryFailPoint at the same time, and they both succeed, that
// they don't trample over each other's memory. Keep a process-wide
// count of "reserved" memory, and decrement this in Dispose and
// in the critical finalizer. See
// SharedStatics.MemoryFailPointReservedMemory
private ulong _reservedMemory; // The size of this request (from user)
private bool _mustSubtractReservation; // Did we add data to SharedStatics?
[System.Security.SecuritySafeCritical] // auto-generated
static MemoryFailPoint()
{
GetMemorySettings(out GCSegmentSize, out TopOfMemory);
}
// We can remove this link demand in a future version - we will
// have scenarios for this in partial trust in the future, but
// we're doing this just to restrict this in case the code below
// is somehow incorrect.
[System.Security.SecurityCritical] // auto-generated_required
public MemoryFailPoint(int sizeInMegabytes)
{
if (sizeInMegabytes <= 0)
throw new ArgumentOutOfRangeException("sizeInMegabytes", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
ulong size = ((ulong)sizeInMegabytes) << 20;
_reservedMemory = size;
// Check to see that we both have enough memory on the system
// and that we have enough room within the user section of the
// process's address space. Also, we need to use the GC segment
// size, not the amount of memory the user wants to allocate.
// Consider correcting this to reflect free memory within the GC
// heap, and to check both the normal & large object heaps.
ulong segmentSize = (ulong) (Math.Ceiling((double)size / GCSegmentSize) * GCSegmentSize);
if (segmentSize >= TopOfMemory)
throw new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint_TooBig"));
ulong requestedSizeRounded = (ulong)(Math.Ceiling((double)sizeInMegabytes / MemoryCheckGranularity) * MemoryCheckGranularity);
//re-convert into bytes
requestedSizeRounded <<= 20;
ulong availPageFile = 0; // available VM (physical + page file)
ulong totalAddressSpaceFree = 0; // non-contiguous free address space
// Check for available memory, with 2 attempts at getting more
// memory.
// Stage 0: If we don't have enough, trigger a GC.
// Stage 1: If we don't have enough, try growing the swap file.
// Stage 2: Update memory state, then fail or leave loop.
//
// (In the future, we could consider adding another stage after
// Stage 0 to run finalizers. However, before doing that make sure
// that we could abort this constructor when we call
// GC.WaitForPendingFinalizers, noting that this method uses a CER
// so it can't be aborted, and we have a critical finalizer. It
// would probably work, but do some thinking first.)
for(int stage = 0; stage < 3; stage++) {
CheckForAvailableMemory(out availPageFile, out totalAddressSpaceFree);
// If we have enough room, then skip some stages.
// Note that multiple threads can still lead to a race condition for our free chunk
// of address space, which can't be easily solved.
ulong reserved = SharedStatics.MemoryFailPointReservedMemory;
ulong segPlusReserved = segmentSize + reserved;
bool overflow = segPlusReserved < segmentSize || segPlusReserved < reserved;
bool needPageFile = availPageFile < (requestedSizeRounded + reserved + LowMemoryFudgeFactor) || overflow;
bool needAddressSpace = totalAddressSpaceFree < segPlusReserved || overflow;
// Ensure our cached amount of free address space is not stale.
long now = Environment.TickCount; // Handle wraparound.
if ((now > LastTimeCheckingAddressSpace + CheckThreshold || now < LastTimeCheckingAddressSpace) ||
LastKnownFreeAddressSpace < (long) segmentSize) {
CheckForFreeAddressSpace(segmentSize, false);
}
bool needContiguousVASpace = (ulong) LastKnownFreeAddressSpace < segmentSize;
BCLDebug.Trace("MEMORYFAILPOINT", "MemoryFailPoint: Checking for {0} MB, for allocation size of {1} MB, stage {9}. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved via process's MemoryFailPoints: {8} MB",
segmentSize >> 20, sizeInMegabytes, needPageFile,
needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved, stage);
if (!needPageFile && !needAddressSpace && !needContiguousVASpace)
break;
switch(stage) {
case 0:
// The GC will release empty segments to the OS. This will
// relieve us from having to guess whether there's
// enough memory in either GC heap, and whether
// internal fragmentation will prevent those
// allocations from succeeding.
GC.Collect();
continue;
case 1:
// Do this step if and only if the page file is too small.
if (!needPageFile)
continue;
// Attempt to grow the OS's page file. Note that we ignore
// any allocation routines from the host intentionally.
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
// This shouldn't overflow due to the if clauses above.
UIntPtr numBytes = new UIntPtr(segmentSize);
unsafe {
void * pMemory = Win32Native.VirtualAlloc(null, numBytes, Win32Native.MEM_COMMIT, Win32Native.PAGE_READWRITE);
if (pMemory != null) {
bool r = Win32Native.VirtualFree(pMemory, UIntPtr.Zero, Win32Native.MEM_RELEASE);
if (!r)
__Error.WinIOError();
}
}
}
continue;
case 2:
// The call to CheckForAvailableMemory above updated our
// state.
if (needPageFile || needAddressSpace) {
InsufficientMemoryException e = new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint"));
#if _DEBUG
e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
needPageFile, needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved);
#endif
throw e;
}
if (needContiguousVASpace) {
InsufficientMemoryException e = new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint_VAFrag"));
#if _DEBUG
e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
needPageFile, needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved);
#endif
throw e;
}
break;
default:
Contract.Assert(false, "Fell through switch statement!");
break;
}
}
// Success - we have enough room the last time we checked.
// Now update our shared state in a somewhat atomic fashion
// and handle a simple race condition with other MemoryFailPoint instances.
AddToLastKnownFreeAddressSpace(-((long) size));
if (LastKnownFreeAddressSpace < 0)
CheckForFreeAddressSpace(segmentSize, true);
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
SharedStatics.AddMemoryFailPointReservation((long) size);
_mustSubtractReservation = true;
}
}
[System.Security.SecurityCritical] // auto-generated
private static void CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree)
{
bool r;
Win32Native.MEMORYSTATUSEX memory = new Win32Native.MEMORYSTATUSEX();
r = Win32Native.GlobalMemoryStatusEx(ref memory);
if (!r)
__Error.WinIOError();
availPageFile = memory.availPageFile;
totalAddressSpaceFree = memory.availVirtual;
//Console.WriteLine("Memory gate: Mem load: {0}% Available memory (physical + page file): {1} MB Total free address space: {2} MB GC Heap: {3} MB", memory.memoryLoad, memory.availPageFile >> 20, memory.availVirtual >> 20, GC.GetTotalMemory(true) >> 20);
}
// Based on the shouldThrow parameter, this will throw an exception, or
// returns whether there is enough space. In all cases, we update
// our last known free address space, hopefully avoiding needing to
// probe again.
[System.Security.SecurityCritical] // auto-generated
private static unsafe bool CheckForFreeAddressSpace(ulong size, bool shouldThrow)
{
// Start walking the address space at 0. VirtualAlloc may wrap
// around the address space. We don't need to find the exact
// pages that VirtualAlloc would return - we just need to
// know whether VirtualAlloc could succeed.
ulong freeSpaceAfterGCHeap = MemFreeAfterAddress(null, size);
BCLDebug.Trace("MEMORYFAILPOINT", "MemoryFailPoint: Checked for free VA space. Found enough? {0} Asked for: {1} Found: {2}", (freeSpaceAfterGCHeap >= size), size, freeSpaceAfterGCHeap);
// We may set these without taking a lock - I don't believe
// this will hurt, as long as we never increment this number in
// the Dispose method. If we do an extra bit of checking every
// once in a while, but we avoid taking a lock, we may win.
LastKnownFreeAddressSpace = (long) freeSpaceAfterGCHeap;
LastTimeCheckingAddressSpace = Environment.TickCount;
if (freeSpaceAfterGCHeap < size && shouldThrow)
throw new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint_VAFrag"));
return freeSpaceAfterGCHeap >= size;
}
// Returns the amount of consecutive free memory available in a block
// of pages. If we didn't have enough address space, we still return
// a positive value < size, to help potentially avoid the overhead of
// this check if we use a MemoryFailPoint with a smaller size next.
[System.Security.SecurityCritical] // auto-generated
private static unsafe ulong MemFreeAfterAddress(void * address, ulong size)
{
if (size >= TopOfMemory)
return 0;
ulong largestFreeRegion = 0;
Win32Native.MEMORY_BASIC_INFORMATION memInfo = new Win32Native.MEMORY_BASIC_INFORMATION();
UIntPtr sizeOfMemInfo = (UIntPtr) Marshal.SizeOf(memInfo);
while (((ulong)address) + size < TopOfMemory) {
UIntPtr r = Win32Native.VirtualQuery(address, ref memInfo, sizeOfMemInfo);
if (r == UIntPtr.Zero)
__Error.WinIOError();
ulong regionSize = memInfo.RegionSize.ToUInt64();
if (memInfo.State == Win32Native.MEM_FREE) {
if (regionSize >= size)
return regionSize;
else
largestFreeRegion = Math.Max(largestFreeRegion, regionSize);
}
address = (void *) ((ulong) address + regionSize);
}
return largestFreeRegion;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void GetMemorySettings(out ulong maxGCSegmentSize, out ulong topOfMemory);
[System.Security.SecuritySafeCritical] // destructors should be safe to call
~MemoryFailPoint()
{
Dispose(false);
}
// Applications must call Dispose, which conceptually "releases" the
// memory that was "reserved" by the MemoryFailPoint. This affects a
// global count of reserved memory in this version (helping to throttle
// future MemoryFailPoints) in this version. We may in the
// future create an allocation context and release it in the Dispose
// method. While the finalizer will eventually free this block of
// memory, apps will help their performance greatly by calling Dispose.
[System.Security.SecuritySafeCritical] // auto-generated
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private void Dispose(bool disposing)
{
// This is just bookkeeping to ensure multiple threads can really
// get enough memory, and this does not actually reserve memory
// within the GC heap.
if (_mustSubtractReservation) {
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
SharedStatics.AddMemoryFailPointReservation(-((long)_reservedMemory));
_mustSubtractReservation = false;
}
}
/*
// Prototype performance
// Let's pretend that we returned at least some free memory to
// the GC heap. We don't know this is true - the objects could
// have a longer lifetime, and the memory could be elsewhere in the
// GC heap. Additionally, we subtracted off the segment size, not
// this size. That's ok - we don't mind if this slowly degrades
// and requires us to refresh the value a little bit sooner.
// But releasing the memory here should help us avoid probing for
// free address space excessively with large workItem sizes.
Interlocked.Add(ref LastKnownFreeAddressSpace, _reservedMemory);
*/
}
#if _DEBUG
[Serializable]
internal sealed class MemoryFailPointState
{
private ulong _segmentSize;
private int _allocationSizeInMB;
private bool _needPageFile;
private bool _needAddressSpace;
private bool _needContiguousVASpace;
private ulong _availPageFile;
private ulong _totalFreeAddressSpace;
private long _lastKnownFreeAddressSpace;
private ulong _reservedMem;
private String _stackTrace; // Where did we fail, for additional debugging.
internal MemoryFailPointState(int allocationSizeInMB, ulong segmentSize, bool needPageFile, bool needAddressSpace, bool needContiguousVASpace, ulong availPageFile, ulong totalFreeAddressSpace, long lastKnownFreeAddressSpace, ulong reservedMem)
{
_allocationSizeInMB = allocationSizeInMB;
_segmentSize = segmentSize;
_needPageFile = needPageFile;
_needAddressSpace = needAddressSpace;
_needContiguousVASpace = needContiguousVASpace;
_availPageFile = availPageFile;
_totalFreeAddressSpace = totalFreeAddressSpace;
_lastKnownFreeAddressSpace = lastKnownFreeAddressSpace;
_reservedMem = reservedMem;
try
{
_stackTrace = Environment.StackTrace;
}
catch (System.Security.SecurityException)
{
_stackTrace = "no permission";
}
catch (OutOfMemoryException)
{
_stackTrace = "out of memory";
}
}
public override String ToString()
{
return String.Format(System.Globalization.CultureInfo.InvariantCulture, "MemoryFailPoint detected insufficient memory to guarantee an operation could complete. Checked for {0} MB, for allocation size of {1} MB. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved by process's MemoryFailPoints: {8} MB",
_segmentSize >> 20, _allocationSizeInMB, _needPageFile,
_needAddressSpace, _needContiguousVASpace,
_availPageFile >> 20, _totalFreeAddressSpace >> 20,
_lastKnownFreeAddressSpace >> 20, _reservedMem);
}
public String StackTrace {
get { return _stackTrace; }
}
}
#endif
}
}
| |
// Copyright (c) 2013-2017 SIL International
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Globalization;
using System.Runtime.InteropServices;
namespace Icu
{
/// <summary>
/// Provides access to Unicode Character Database.
/// In addition to raw property values, some convenience functions calculate
/// derived properties.
/// </summary>
public static class Character
{
/// <summary>
/// Defined in ICU uchar.h
/// http://icu-project.org/apiref/icu4c/uchar_8h.html
/// </summary>
public enum UProperty
{
/* See note !!. Comments of the form "Binary property Dash",
"Enumerated property Script", "Double property Numeric_Value",
and "String property Age" are read by genpname. */
/* Note: Place ALPHABETIC before BINARY_START so that
debuggers display ALPHABETIC as the symbolic name for 0,
rather than BINARY_START. Likewise for other *_START
identifiers. */
/// <summary>
/// Same as u_isUAlphabetic, different from u_isalpha.
/// Lu+Ll+Lt+Lm+Lo+Nl+Other_Alphabetic
/// </summary>
ALPHABETIC = 0,
/// <summary>First constant for binary Unicode properties.</summary>
BINARY_START = ALPHABETIC,
/// <summary>0-9 A-F a-f</summary>
ASCII_HEX_DIGIT = 1,
/// <summary>Format controls which have specific functions in the Bidi Algorithm.</summary>
BIDI_CONTROL = 2,
/// <summary>
/// Characters that may change display in RTL text. Same as
/// u_isMirrored. See Bidi Algorithm, UTR 9.
/// </summary>
BIDI_MIRRORED = 3,
/// <summary>Variations of dashes.</summary>
DASH = 4,
/// <summary>Ignorable in most processing.</summary>
/// <example><2060..206F, FFF0..FFFB, E0000..E0FFF>+Other_Default_Ignorable_Code_Point+(Cf+Cc+Cs-White_Space)</example>
DEFAULT_IGNORABLE_CODE_POINT = 5,
/// <summary>The usage of deprecated characters is strongly discouraged.</summary>
DEPRECATED = 6,
/// <summary>
/// Characters that linguistically modify the meaning of another
/// character to which they apply.
/// </summary>
DIACRITIC = 7,
/// <summary>
/// Extend the value or shape of a preceding alphabetic character,
/// e.g., length and iteration marks.
/// </summary>
EXTENDER = 8,
/// <summary>CompositionExclusions.txt+Singleton Decompositions+ Non-Starter Decompositions.</summary>
FULL_COMPOSITION_EXCLUSION = 9,
/// <summary>For programmatic determination of grapheme cluster boundaries.</summary>
/// <example>[0..10FFFF]-Cc-Cf-Cs-Co-Cn-Zl-Zp-Grapheme_Link-Grapheme_Extend-CGJ</example>
GRAPHEME_BASE = 10,
/// <summary>For programmatic determination of grapheme cluster boundaries.</summary>
/// <example>Me+Mn+Mc+Other_Grapheme_Extend-Grapheme_Link-CGJ</example>
GRAPHEME_EXTEND = 11,
/// <summary>For programmatic determination of grapheme cluster boundaries.</summary>
GRAPHEME_LINK = 12,
/// <summary>Characters commonly used for hexadecimal numbers.</summary>
HEX_DIGIT = 13,
/// <summary>
/// Dashes used to mark connections between pieces of words, plus the
/// Katakana middle dot.
/// </summary>
HYPHEN = 14,
/// <summary>
/// Characters that can continue an identifier.
/// DerivedCoreProperties.txt also says "NOTE: Cf characters should
/// be filtered out."
/// </summary>
/// <example>ID_Start+Mn+Mc+Nd+Pc</example>
ID_CONTINUE = 15,
/// <summary>Characters that can start an identifier.</summary>
/// <example>Lu+Ll+Lt+Lm+Lo+Nl</example>
ID_START = 16,
/// <summary>CJKV ideographs.</summary>
IDEOGRAPHIC = 17,
/// <summary>For programmatic determination of Ideographic Description Sequences.</summary>
IDS_BINARY_OPERATOR = 18,
/// <summary>For programmatic determination of Ideographic Description Sequences.</summary>
IDS_TRINARY_OPERATOR = 19,
/// <summary>Format controls for cursive joining and ligation.</summary>
JOIN_CONTROL = 20,
/// <summary>
/// Characters that do not use logical order and require special
/// handling in most processing.
/// </summary>
LOGICAL_ORDER_EXCEPTION = 21,
/// <summary>Same as u_isULowercase, different from u_islower.</summary>
/// <example>Ll+Other_Lowercase</example>
LOWERCASE = 22,
/// <summary>Sm+Other_Math</summary>
MATH = 23,
/// <summary>Code points that are explicitly defined as illegal for the encoding of characters.</summary>
NONCHARACTER_CODE_POINT = 24,
/// <summary>Binary property Quotation_Mark.</summary>
QUOTATION_MARK = 25,
/// <summary>For programmatic determination of Ideographic Description Sequences.</summary>
RADICAL = 26,
/// <summary>
/// Characters with a "soft dot", like i or j. An accent placed on
/// these characters causes the dot to disappear.
/// </summary>
SOFT_DOTTED = 27,
/// <summary>Punctuation characters that generally mark the end of textual units.</summary>
TERMINAL_PUNCTUATION = 28,
/// <summary>For programmatic determination of Ideographic Description Sequences.</summary>
UNIFIED_IDEOGRAPH = 29,
/// <summary>Same as u_isUUppercase, different from u_isupper. Lu+Other_Uppercase</summary>
UPPERCASE = 30,
/// <summary>
/// Same as u_isUWhiteSpace, different from u_isspace and
/// u_isWhitespace. Space characters+TAB+CR+LF-ZWSP-ZWNBSP
/// </summary>
WHITE_SPACE = 31,
/// <summary>ID_Continue modified to allow closure under normalization forms NFKC and NFKD.</summary>
XID_CONTINUE = 32,
/// <summary>ID_Start modified to allow closure under normalization forms NFKC and NFKD.</summary>
XID_START = 33,
/// <summary>
/// Either the source of a case mapping or in the target of a case
/// mapping. Not the same as the general category Cased_Letter.
/// </summary>
CASE_SENSITIVE = 34,
/// <summary>Sentence Terminal. Used in UAX #29: Text Boundaries (http://www.unicode.org/reports/tr29/)</summary>
S_TERM = 35,
/// <summary>
/// ICU-specific property for characters that are inert under NFD,
/// i.e., they do not interact with adjacent characters. See the
/// documentation for the Normalizer2 class and the
/// Normalizer2::isInert() method.
/// http://www.icu-project.org/apiref/icu4c/classicu_1_1Normalizer2.html
/// </summary>
VARIATION_SELECTOR = 36,
/// <summary>
/// ICU-specific property for characters that are inert under NFD,
/// i.e., they do not interact with adjacent characters. See the
/// documentation for the Normalizer2 class and the
/// Normalizer2::isInert() method.
/// http://www.icu-project.org/apiref/icu4c/classicu_1_1Normalizer2.html
/// </summary>
NFD_INERT = 37,
/// <summary>
/// ICU-specific property for characters that are inert under NFKD,
/// i.e., they do not interact with adjacent characters. See the
/// documentation for the Normalizer2 class and the
/// Normalizer2::isInert() method.
/// http://www.icu-project.org/apiref/icu4c/classicu_1_1Normalizer2.html
/// </summary>
NFKD_INERT = 38,
/// <summary>
/// ICU-specific property for characters that are inert under NFC,
/// i.e., they do not interact with adjacent characters. See the
/// documentation for the Normalizer2 class and the
/// Normalizer2::isInert() method.
/// http://www.icu-project.org/apiref/icu4c/classicu_1_1Normalizer2.html
/// </summary>
NFC_INERT = 39,
/// <summary>
/// ICU-specific property for characters that are inert under NFKC,
/// i.e., they do not interact with adjacent characters. See the
/// documentation for the Normalizer2 class and the
/// Normalizer2::isInert() method.
/// http://www.icu-project.org/apiref/icu4c/classicu_1_1Normalizer2.html
/// </summary>
NFKC_INERT = 40,
/// <summary>
/// ICU-specific property for characters that are starters in terms
/// of Unicode normalization and combining character sequences. They
/// have ccc=0 and do not occur in non-initial position of the
/// canonical decomposition of any character (like a-umlaut in NFD
/// and a Jamo T in an NFD(Hangul LVT)). ICU uses this property for
/// segmenting a string for generating a set of canonically
/// equivalent strings, e.g. for canonical closure while processing
/// collation tailoring rules.
/// </summary>
SEGMENT_STARTER = 41,
/// <summary>See UAX #31 Identifier and Pattern Syntax (http://www.unicode.org/reports/tr31/)</summary>
PATTERN_SYNTAX = 42,
/// <summary>See UAX #31 Identifier and Pattern Syntax (http://www.unicode.org/reports/tr31/)</summary>
PATTERN_WHITE_SPACE = 43,
/// <summary>
/// Implemented according to the UTS #18 Annex C Standard
/// Recommendation. See the uchar.h file documentation.
/// http://icu-project.org/apiref/icu4c/uchar_8h.html
/// </summary>
POSIX_ALNUM = 44,
/// <summary>
/// Implemented according to the UTS #18 Annex C Standard
/// Recommendation. See the uchar.h file documentation.
/// http://icu-project.org/apiref/icu4c/uchar_8h.html
/// </summary>
POSIX_BLANK = 45,
/// <summary>
/// Implemented according to the UTS #18 Annex C Standard
/// Recommendation. See the uchar.h file documentation.
/// http://icu-project.org/apiref/icu4c/uchar_8h.html
/// </summary>
POSIX_GRAPH = 46,
/// <summary>
/// Implemented according to the UTS #18 Annex C Standard
/// Recommendation. See the uchar.h file documentation.
/// http://icu-project.org/apiref/icu4c/uchar_8h.html
/// </summary>
POSIX_PRINT = 47,
/// <summary>
/// Implemented according to the UTS #18 Annex C Standard
/// Recommendation. See the uchar.h file documentation.
/// http://icu-project.org/apiref/icu4c/uchar_8h.html
/// </summary>
POSIX_XDIGIT = 48,
/// <summary>For Lowercase, Uppercase and Titlecase characters.</summary>
CASED = 49,
/// <summary>Used in context-sensitive case mappings.</summary>
CASE_IGNORABLE = 50,
/// <summary>Binary property Changes_When_Lowercased.</summary>
CHANGES_WHEN_LOWERCASED = 51,
/// <summary>Binary property Changes_When_Uppercased.</summary>
CHANGES_WHEN_UPPERCASED = 52,
/// <summary>Binary property Changes_When_Titlecased.</summary>
CHANGES_WHEN_TITLECASED = 53,
/// <summary>Binary property Changes_When_Casefolded.</summary>
CHANGES_WHEN_CASEFOLDED = 54,
/// <summary>Binary property Changes_When_Casemapped.</summary>
CHANGES_WHEN_CASEMAPPED = 55,
/// <summary>Binary property Changes_When_NFKC_Casefolded.</summary>
CHANGES_WHEN_NFKC_CASEFOLDED = 56,
/// <summary>Binary property EMOJI.</summary>
EMOJI = 57,
/// <summary>Binary property EMOJI_PRESENTATION.</summary>
EMOJI_PRESENTATION = 58,
/// <summary>Binary property EMOJI_MODIFIER.</summary>
EMOJI_MODIFIER = 59,
/// <summary>Binary property EMOJI_MODIFIER_BASE.</summary>
EMOJI_MODIFIER_BASE = 60,
/// <summary>Binary property EMOJI_COMPONENT.</summary>
EMOJI_COMPONENT = 61,
/// <summary>Binary property REGIONAL_INDICATOR.</summary>
REGIONAL_INDICATOR = 62,
/// <summary>Binary property PREPENDED_CONCATENATION_MARK.</summary>
PREPENDED_CONCATENATION_MARK = 63,
/// <summary>Binary property EXTENDED_PICTOGRAPHIC.</summary>
EXTENDED_PICTOGRAPHIC = 64,
/// <summary>One more than the last constant for binary Unicode properties.</summary>
[Obsolete("ICU 58 The numeric value may change over time, see ICU ticket #12420.")]
BINARY_LIMIT,
/// <summary>Same as u_charDirection, returns UCharDirection values.</summary>
BIDI_CLASS = 0x1000,
/// <summary>First constant for enumerated/integer Unicode properties.</summary>
INT_START = BIDI_CLASS,
/// <summary>Same as ublock_getCode, returns UBlockCode values.</summary>
BLOCK = 0x1001,
/// <summary>Same as u_getCombiningClass, returns 8-bit numeric values.</summary>
CANONICAL_COMBINING_CLASS = 0x1002,
/// <summary>Returns UDecompositionType values.</summary>
DECOMPOSITION_TYPE = 0x1003,
/// <summary>See http://www.unicode.org/reports/tr11/ Returns UEastAsianWidth values.</summary>
EAST_ASIAN_WIDTH = 0x1004,
/// <summary>Same as u_charType, returns UCharCategory values.</summary>
GENERAL_CATEGORY = 0x1005,
/// <summary>Returns UJoiningGroup values.</summary>
JOINING_GROUP = 0x1006,
/// <summary>Returns UJoiningType values.</summary>
JOINING_TYPE = 0x1007,
/// <summary>Returns ULineBreak values.</summary>
LINE_BREAK = 0x1008,
/// <summary>Returns UNumericType values.</summary>
NUMERIC_TYPE = 0x1009,
/// <summary>Same as uscript_getScript, returns UScriptCode values.</summary>
SCRIPT = 0x100A,
/// <summary>Returns UHangulSyllableType values.</summary>
HANGUL_SYLLABLE_TYPE = 0x100B,
/// <summary>Returns UNormalizationCheckResult values.</summary>
NFD_QUICK_CHECK = 0x100C,
/// <summary>Returns UNormalizationCheckResult values.</summary>
NFKD_QUICK_CHECK = 0x100D,
/// <summary>Returns UNormalizationCheckResult values.</summary>
NFC_QUICK_CHECK = 0x100E,
/// <summary>Returns UNormalizationCheckResult values.</summary>
NFKC_QUICK_CHECK = 0x100F,
/// <summary>
/// ICU-specific property for the ccc of the first code point of the
/// decomposition, or lccc(c)=ccc(NFD(c)[0]). Useful for checking
/// for canonically ordered text; see UNORM_FCD and
/// http://www.unicode.org/notes/tn5/#FCD . Returns 8-bit numeric
/// values like UCHAR_CANONICAL_COMBINING_CLASS.
/// </summary>
LEAD_CANONICAL_COMBINING_CLASS = 0x1010,
/// <summary>
/// ICU-specific property for the ccc of the last code point of the
/// decomposition, or tccc(c)=ccc(NFD(c)[last]). Useful for checking
/// for canonically ordered text; see UNORM_FCD and
/// http://www.unicode.org/notes/tn5/#FCD . Returns 8-bit numeric
/// values like UCHAR_CANONICAL_COMBINING_CLASS.
/// </summary>
TRAIL_CANONICAL_COMBINING_CLASS = 0x1011,
/// <summary>
/// Used in UAX #29: Text Boundaries (http://www.unicode.org/reports/tr29/)
/// Returns UGraphemeClusterBreak values.
/// </summary>
GRAPHEME_CLUSTER_BREAK = 0x1012,
/// <summary>
/// Used in UAX #29: Text Boundaries (http://www.unicode.org/reports/tr29/)
/// Returns USentenceBreak values
/// </summary>
SENTENCE_BREAK = 0x1013,
/// <summary>
/// Used in UAX #29: Text Boundaries (http://www.unicode.org/reports/tr29/)
/// Returns UWordBreakValues values.
/// </summary>
WORD_BREAK = 0x1014,
/// <summary>
/// Used in UAX #9: Unicode Bidirectional Algorithm (http://www.unicode.org/reports/tr9/)
/// Returns UBidiPairedBracketType values.
/// </summary>
BIDI_PAIRED_BRACKET_TYPE =0x1015,
/// <summary>One more than the last constant for enumerated/integer Unicode properties.</summary>
[Obsolete("ICU 58 The numeric value may change over time, see ICU ticket #12420.")]
INT_LIMIT = 0x1016,
/// <summary>
/// This is the General_Category property returned as a bit mask.
/// When used in u_getIntPropertyValue(c), same as
/// U_MASK(u_charType(c)), returns bit masks for UCharCategory
/// values where exactly one bit is set. When used with
/// u_getPropertyValueName() and u_getPropertyValueEnum(), a
/// multi-bit mask is used for sets of categories like "Letters".
/// Mask values should be cast to uint32_t.
/// http://icu-project.org/apiref/icu4c/uchar_8h.html#a3f694e48867909fbe555586f2b3565be
/// </summary>
GENERAL_CATEGORY_MASK = 0x2000,
/// <summary>First constant for bit-mask Unicode properties.</summary>
MASK_START = GENERAL_CATEGORY_MASK,
/// <summary>One more than the last constant for bit-mask Unicode properties.</summary>
[Obsolete("ICU 58 The numeric value may change over time, see ICU ticket #12420.")]
MASK_LIMIT = 0x2001,
/// <summary>Corresponds to u_getNumericValue.</summary>
NUMERIC_VALUE = 0x3000,
/// <summary>First constant for double Unicode properties.</summary>
DOUBLE_START = NUMERIC_VALUE,
/// <summary>One more than the last constant for double Unicode properties.</summary>
[Obsolete("ICU 58 The numeric value may change over time, see ICU ticket #12420.")]
DOUBLE_LIMIT = 0x3001,
/// <summary>Corresponds to u_charAge.</summary>
AGE = 0x4000,
/// <summary>First constant for string Unicode properties.</summary>
STRING_START = AGE,
/// <summary>Corresponds to u_charMirror.</summary>
BIDI_MIRRORING_GLYPH = 0x4001,
/// <summary>Corresponds to u_strFoldCase in ustring.h (http://icu-project.org/apiref/icu4c/ustring_8h.html).</summary>
CASE_FOLDING = 0x4002,
/// <summary>Corresponds to u_getISOComment.</summary>
[Obsolete("ICU 49")]
ISO_COMMENT = 0x4003,
/// <summary>Corresponds to u_strToLower in ustring.h (http://icu-project.org/apiref/icu4c/ustring_8h.html).</summary>
LOWERCASE_MAPPING = 0x4004,
/// <summary>Corresponds to u_charName.</summary>
NAME = 0x4005,
/// <summary>Corresponds to u_foldCase.</summary>
SIMPLE_CASE_FOLDING = 0x4006,
/// <summary> Corresponds to u_tolower.</summary>
SIMPLE_LOWERCASE_MAPPING = 0x4007,
/// <summary> Corresponds to u_totitle.</summary>
SIMPLE_TITLECASE_MAPPING = 0x4008,
/// <summary> Corresponds to u_toupper.</summary>
SIMPLE_UPPERCASE_MAPPING = 0x4009,
/// <summary>Corresponds to u_strToTitle in ustring.h (http://icu-project.org/apiref/icu4c/ustring_8h.html).</summary>
TITLECASE_MAPPING = 0x400A,
/// <summary>
/// This property is of little practical value. Beginning with
/// ICU 49, ICU APIs return an empty string for this property.
/// Corresponds to u_charName(U_UNICODE_10_CHAR_NAME).
/// </summary>
[Obsolete("ICU 49")]
UNICODE_1_NAME = 0x400B,
/// <summary>Corresponds to u_strToUpper in ustring.h (http://icu-project.org/apiref/icu4c/ustring_8h.html).</summary>
UPPERCASE_MAPPING = 0x400C,
/// <summary>Corresponds to u_getBidiPairedBracket.</summary>
BIDI_PAIRED_BRACKET = 0x400D,
/// <summary>One more than the last constant for string Unicode properties.</summary>
[Obsolete("ICU 58 The numeric value may change over time, see ICU ticket #12420.")]
STRING_LIMIT = 0x400E,
/// <summary>
/// Some characters are commonly used in multiple scripts. For more
/// information, see UAX #24: http://www.unicode.org/reports/tr24/.
/// Corresponds to uscript_hasScript and uscript_getScriptExtensions
/// in uscript.h. http://icu-project.org/apiref/icu4c/uscript_8h.html
/// </summary>
SCRIPT_EXTENSIONS = 0x7000,
/// <summary>First constant for Unicode properties with unusual value types</summary>
OTHER_PROPERTY_START = SCRIPT_EXTENSIONS,
/// <summary>One more than the last constant for Unicode properties with unusual value types.</summary>
[Obsolete("ICU 58 The numeric value may change over time, see ICU ticket #12420.")]
OTHER_PROPERTY_LIMIT = 0x7001,
/// <summary>Represents a nonexistent or invalid property or property value.</summary>
INVALID_CODE = -1
}
///<summary>
/// enumerated Unicode general category types.
/// See http://www.unicode.org/Public/UNIDATA/UnicodeData.html .
/// </summary>
public enum UCharCategory
{
///<summary>Non-category for unassigned and non-character code points.</summary>
UNASSIGNED = 0,
///<summary>Cn "Other, Not Assigned (no characters in [UnicodeData.txt] have this property)" (same as U_UNASSIGNED!)</summary>
GENERAL_OTHER_TYPES = 0,
///<summary>Lu</summary>
UPPERCASE_LETTER = 1,
///<summary>Ll</summary>
LOWERCASE_LETTER = 2,
///<summary>Lt</summary>
TITLECASE_LETTER = 3,
///<summary>Lm</summary>
MODIFIER_LETTER = 4,
///<summary>Lo</summary>
OTHER_LETTER = 5,
///<summary>Mn</summary>
NON_SPACING_MARK = 6,
///<summary>Me</summary>
ENCLOSING_MARK = 7,
///<summary>Mc</summary>
COMBINING_SPACING_MARK = 8,
///<summary>Nd</summary>
DECIMAL_DIGIT_NUMBER = 9,
///<summary>Nl</summary>
LETTER_NUMBER = 10,
///<summary>No</summary>
OTHER_NUMBER = 11,
///<summary>Zs</summary>
SPACE_SEPARATOR = 12,
///<summary>Zl</summary>
LINE_SEPARATOR = 13,
///<summary>Zp</summary>
PARAGRAPH_SEPARATOR = 14,
///<summary>Cc</summary>
CONTROL_CHAR = 15,
///<summary>Cf</summary>
FORMAT_CHAR = 16,
///<summary>Co</summary>
PRIVATE_USE_CHAR = 17,
///<summary>Cs</summary>
SURROGATE = 18,
///<summary>Pd</summary>
DASH_PUNCTUATION = 19,
///<summary>Ps</summary>
START_PUNCTUATION = 20,
///<summary>Pe</summary>
END_PUNCTUATION = 21,
///<summary>Pc</summary>
CONNECTOR_PUNCTUATION = 22,
///<summary>Po</summary>
OTHER_PUNCTUATION = 23,
///<summary>Sm</summary>
MATH_SYMBOL = 24,
///<summary>Sc</summary>
CURRENCY_SYMBOL = 25,
///<summary>Sk</summary>
MODIFIER_SYMBOL = 26,
///<summary>So</summary>
OTHER_SYMBOL = 27,
///<summary>Pi</summary>
INITIAL_PUNCTUATION = 28,
///<summary>Pf</summary>
FINAL_PUNCTUATION = 29,
///<summary>One higher than the last enum UCharCategory constant.</summary>
CHAR_CATEGORY_COUNT
}
/// <summary>
/// Selector constants for u_charName().
/// u_charName() returns the "modern" name of a Unicode character; or the name that was
/// defined in Unicode version 1.0, before the Unicode standard merged with ISO-10646; or
/// an "extended" name that gives each Unicode code point a unique name.
/// </summary>
public enum UCharNameChoice
{
/// <summary>Unicode character name (Name property). </summary>
UNICODE_CHAR_NAME,
/// <summary>The Unicode_1_Name property value which is of little practical value.
/// Beginning with ICU 49, ICU APIs return an empty string for this name choice. </summary>
[Obsolete("ICU 49")]
UNICODE_10_CHAR_NAME,
/// <summary>Standard or synthetic character name. </summary>
EXTENDED_CHAR_NAME,
/// <summary>Corrected name from NameAliases.txt. </summary>
NAME_ALIAS,
/// <summary>One more than the highest normal UCharNameChoice value. </summary>
[Obsolete("ICU 58 The numeric value may change over time, see ICU ticket #12420.")]
CHAR_NAME_CHOICE_COUNT
}
/// <summary>
/// Decomposition Type constants.
/// </summary>
/// <remarks>
/// Note: UDecompositionType constants are parsed by preparseucd.py.
/// It matches lines like U_DT_<Unicode Decomposition_Type value name>
/// </remarks>
public enum UDecompositionType
{
/// <summary>[none]</summary>
NONE,
/// <summary>[can]</summary>
CANONICAL,
/// <summary>[com]</summary>
COMPAT,
/// <summary>[enc]</summary>
CIRCLE,
/// <summary>[fin]</summary>
FINAL,
/// <summary>[font]</summary>
FONT,
/// <summary>[fra]</summary>
FRACTION,
/// <summary>[init]</summary>
INITIAL,
/// <summary>[iso]</summary>
ISOLATED,
/// <summary>[med]</summary>
MEDIAL,
/// <summary>[nar]</summary>
NARROW,
/// <summary>[nb]</summary>
NOBREAK,
/// <summary>[sml]</summary>
SMALL,
/// <summary>[sqr]</summary>
SQUARE,
/// <summary>[sub]</summary>
SUB,
/// <summary>[sup]</summary>
SUPER,
/// <summary>[vert]</summary>
VERTICAL,
/// <summary>[wide]</summary>
WIDE,
/// <summary>18</summary>
COUNT
}
/// <summary>
/// Numeric Type constants
/// </summary>
/// <remarks>Note: UNumericType constants are parsed by preparseucd.py.
/// It matches lines like U_NT_<Unicode Numeric_Type value name></remarks>
public enum UNumericType
{
/// <summary>[None]</summary>
NONE,
/// <summary>[de]</summary>
DECIMAL,
/// <summary>[di]</summary>
DIGIT,
/// <summary>[nu]</summary>
NUMERIC,
/// <summary></summary>
COUNT
}
/// <summary>
/// BIDI direction constants
/// </summary>
public enum UCharDirection
{
/// <summary>L.</summary>
LEFT_TO_RIGHT = 0,
/// <summary>R.</summary>
RIGHT_TO_LEFT = 1,
/// <summary>EN.</summary>
EUROPEAN_NUMBER = 2,
/// <summary>ES.</summary>
EUROPEAN_NUMBER_SEPARATOR = 3,
/// <summary>ET.</summary>
EUROPEAN_NUMBER_TERMINATOR = 4,
/// <summary>AN.</summary>
ARABIC_NUMBER = 5,
/// <summary>CS.</summary>
COMMON_NUMBER_SEPARATOR = 6,
/// <summary>B.</summary>
BLOCK_SEPARATOR = 7,
/// <summary>S.</summary>
SEGMENT_SEPARATOR = 8,
/// <summary>WS.</summary>
WHITE_SPACE_NEUTRAL = 9,
/// <summary>ON.</summary>
OTHER_NEUTRAL = 10,
/// <summary>LRE.</summary>
LEFT_TO_RIGHT_EMBEDDING = 11,
/// <summary>LRO.</summary>
LEFT_TO_RIGHT_OVERRIDE = 12,
/// <summary>AL.</summary>
RIGHT_TO_LEFT_ARABIC = 13,
/// <summary>RLE.</summary>
RIGHT_TO_LEFT_EMBEDDING = 14,
/// <summary>RLO.</summary>
RIGHT_TO_LEFT_OVERRIDE = 15,
/// <summary>PDF.</summary>
POP_DIRECTIONAL_FORMAT = 16,
/// <summary>NSM.</summary>
DIR_NON_SPACING_MARK = 17,
/// <summary>BN.</summary>
BOUNDARY_NEUTRAL = 18,
/// <summary>FSI.</summary>
FIRST_STRONG_ISOLATE = 19,
/// <summary>LRI.</summary>
LEFT_TO_RIGHT_ISOLATE = 20,
/// <summary>RLI.</summary>
RIGHT_TO_LEFT_ISOLATE = 21,
/// <summary>PDI.</summary>
POP_DIRECTIONAL_ISOLATE = 22,
/// <summary>One more than the highest UCharDirection value.
/// The highest value is available via u_getIntPropertyMaxValue(BIDI_CLASS).</summary>
[Obsolete("ICU 58 The numeric value may change over time, see ICU ticket #12420.")]
CHAR_DIRECTION_COUNT
}
/// <summary>
/// Special value that is returned by <see cref="GetNumericValue(int)"/>
/// when no numeric value is defined for a code point.
/// </summary>
public const double NO_NUMERIC_VALUE = -123456789;
/// <summary>
/// Returns the decimal digit value of the code point in the specified radix.
/// </summary>
/// <param name="characterCode">The code point to be tested</param>
/// <param name="radix">The radix</param>
public static int Digit(int characterCode, byte radix)
{
return NativeMethods.u_digit(characterCode, radix);
}
/// <summary>
/// Determines whether the specified character code is alphabetic, based on the
/// UProperty.ALPHABETIC property.
/// </summary>
/// <param name="characterCode">The character code.</param>
public static bool IsAlphabetic(int characterCode)
{
return NativeMethods.u_getIntPropertyValue(characterCode, UProperty.ALPHABETIC) != 0;
}
/// <summary>
/// Determines whether the specified character code is ideographic, based on the
/// UProperty.IDEOGRAPHIC property.
/// </summary>
/// <param name="characterCode">The character code.</param>
public static bool IsIdeographic(int characterCode)
{
return NativeMethods.u_getIntPropertyValue(characterCode, UProperty.IDEOGRAPHIC) != 0;
}
/// <summary>
/// Determines whether the specified character code is alphabetic, based on the
/// UProperty.DIACRITIC property.
/// </summary>
/// <param name="characterCode">The character code.</param>
public static bool IsDiacritic(int characterCode)
{
return NativeMethods.u_getIntPropertyValue(characterCode, UProperty.DIACRITIC) != 0;
}
/// <summary>
/// Determines whether the specified code point is a symbol character
/// </summary>
/// <param name="characterCode">the code point to be tested</param>
public static bool IsSymbol(int characterCode)
{
switch (GetCharType(characterCode))
{
case UCharCategory.MATH_SYMBOL:
case UCharCategory.CURRENCY_SYMBOL:
case UCharCategory.MODIFIER_SYMBOL:
case UCharCategory.OTHER_SYMBOL:
return true;
default:
return false;
}
}
/// <summary>
/// Determines whether the specified character is a letter, i.e. if code point is in the
/// category Lu, Ll, Lt, Lm and Lo.
/// </summary>
public static bool IsLetter(int characterCode)
{
switch (GetCharType(characterCode))
{
case UCharCategory.UPPERCASE_LETTER:
case UCharCategory.LOWERCASE_LETTER:
case UCharCategory.TITLECASE_LETTER:
case UCharCategory.MODIFIER_LETTER:
case UCharCategory.OTHER_LETTER:
return true;
default:
return false;
}
}
/// <summary>
/// Determines whether the specified character is a mark, i.e. if code point is in the
/// category Mn, Me and Mc.
/// </summary>
public static bool IsMark(int characterCode)
{
switch (GetCharType(characterCode))
{
case UCharCategory.NON_SPACING_MARK:
case UCharCategory.ENCLOSING_MARK:
case UCharCategory.COMBINING_SPACING_MARK:
return true;
default:
return false;
}
}
/// <summary>
/// Determines whether the specified character is a separator, i.e. if code point is in
/// the category Zs, Zl and Zp.
/// </summary>
public static bool IsSeparator(int characterCode)
{
switch (GetCharType(characterCode))
{
case UCharCategory.SPACE_SEPARATOR:
case UCharCategory.LINE_SEPARATOR:
case UCharCategory.PARAGRAPH_SEPARATOR:
return true;
default:
return false;
}
}
/// <summary>
/// Determines whether the specified character code is numeric, based on the
/// UProperty.NUMERIC_TYPE property.
/// </summary>
/// <param name="characterCode">The character code.</param>
public static bool IsNumeric(int characterCode)
{
return NativeMethods.u_getIntPropertyValue(characterCode, UProperty.NUMERIC_TYPE) != 0;
}
/// <summary>Determines whether the specified code point is a punctuation character, as
/// defined by the ICU NativeMethods.u_ispunct function.</summary>
public static bool IsPunct(int characterCode)
{
return NativeMethods.u_ispunct(characterCode);
}
/// <summary>Determines whether the code point has the Bidi_Mirrored property. </summary>
public static bool IsMirrored(int characterCode)
{
return NativeMethods.u_isMirrored(characterCode);
}
/// <summary>Determines whether the specified code point is a control character, as
/// defined by the ICU NativeMethods.u_iscntrl function.</summary>
public static bool IsControl(int characterCode)
{
return NativeMethods.u_iscntrl(characterCode);
}
/// <summary>
/// Determines whether the specified character is a control character. A control
/// character is one of the following:
/// <list>
/// <item>ISO 8-bit control character (U+0000..U+001f and U+007f..U+009f)</item>
/// <item>U_CONTROL_CHAR (Cc)</item>
/// <item>U_FORMAT_CHAR (Cf)</item>
/// <item>U_LINE_SEPARATOR (Zl)</item>
/// <item>U_PARAGRAPH_SEPARATOR (Zp)</item>
/// </list>
/// </summary>
public static bool IsControl(string chr)
{
return !string.IsNullOrEmpty(chr) && chr.Length == 1 && IsControl(chr[0]);
}
/// <summary>Determines whether the specified character is a space character, as
/// defined by the ICU NativeMethods.u_isspace function.</summary>
public static bool IsSpace(int characterCode)
{
return NativeMethods.u_isspace(characterCode);
}
/// <summary>
/// Determines whether the specified character is a space character.
/// </summary>
public static bool IsSpace(string chr)
{
return !string.IsNullOrEmpty(chr) && chr.Length == 1 && IsSpace(chr[0]);
}
///<summary>
/// Get the general character category value for the given code point.
///</summary>
///<param name="ch">the code point to be checked</param>
///<returns></returns>
public static UCharCategory GetCharType(int ch)
{
return (UCharCategory)NativeMethods.u_charType(ch);
}
/// <summary></summary>
public static double GetNumericValue(int characterCode)
{
return NativeMethods.u_getNumericValue(characterCode);
}
/// <summary>
/// Returns the bidirectional category value for the code point, which is used in the
/// Unicode bidirectional algorithm (UAX #9 http://www.unicode.org/reports/tr9/).
/// </summary>
/// <param name="code">the code point to be tested </param>
/// <returns>the bidirectional category (UCharDirection) value</returns>
/// <remarks><para>Note that some unassigned code points have bidi values of R or AL because
/// they are in blocks that are reserved for Right-To-Left scripts.</para>
/// <para>Same as java.lang.Character.getDirectionality()</para></remarks>
public static UCharDirection CharDirection(int code)
{
return (UCharDirection) NativeMethods.u_charDirection(code);
}
/// <summary>
/// Get the description for a given ICU code point.
/// </summary>
/// <param name="code">the code point to get description/name of</param>
/// <param name="nameChoice">what type of information to retrieve</param>
/// <param name="name">return string</param>
/// <returns>length of string</returns>
private static int CharName(int code, UCharNameChoice nameChoice, out string name)
{
name = NativeMethods.GetAnsiString((ptr, length) =>
{
length = NativeMethods.u_charName(code, nameChoice, ptr, length, out var err);
return new Tuple<ErrorCode, int>(err, length);
});
return name.Length;
}
/// <summary>
/// Gets the ICU display name of the specified character.
/// </summary>
public static string GetPrettyICUCharName(string chr)
{
if (!string.IsNullOrEmpty(chr) && chr.Length == 1)
{
string name;
if (CharName(chr[0], UCharNameChoice.UNICODE_CHAR_NAME, out name) > 0)
{
var lowercase = CultureInfo.CurrentUICulture.TextInfo.ToLower(name);
return UnicodeString.ToTitle(lowercase, new Locale());
}
}
return null;
}
/// <summary>
/// Gets the raw ICU display name of the specified character code.
/// </summary>
public static string GetCharName(int code)
{
string name;
if (CharName(code, UCharNameChoice.UNICODE_CHAR_NAME, out name) > 0)
{
return name;
}
return null;
}
/// <summary>
/// Get the property value for an enumerated or integer Unicode property for a code point.
/// Also returns binary and mask property values.
/// </summary>
/// <param name="codePoint">Code point to test. </param>
/// <param name="which">UProperty selector constant, identifies which property to check.
/// Must be UProperty.BINARY_START <= which < UProperty.BINARY_LIMIT or
/// UProperty.INT_START <= which < UProperty.INT_LIMIT or
/// UProperty.MASK_START <= which < UProperty.MASK_LIMIT.</param>
/// <returns>
/// Numeric value that is directly the property value or, for enumerated properties,
/// corresponds to the numeric value of the enumerated constant of the respective property
/// value enumeration type (cast to enum type if necessary).
/// Returns 0 or 1 (for <c>false</c>/<c>true</c>) for binary Unicode properties.
/// Returns a bit-mask for mask properties.
/// Returns 0 if 'which' is out of bounds or if the Unicode version does not have data for
/// the property at all, or not for this code point.
/// </returns>
/// <remarks>
/// Unicode, especially in version 3.2, defines many more properties than the original set
/// in UnicodeData.txt.
/// The properties APIs are intended to reflect Unicode properties as defined in the
/// Unicode Character Database (UCD) and Unicode Technical Reports (UTR). For details
/// about the properties <see href="http: //www.unicode.org/"/> . For names of Unicode
/// properties see the UCD file <see cref="PropertyAliases.txt"/>.
/// </remarks>
public static int GetIntPropertyValue(int codePoint, UProperty which)
{
return NativeMethods.u_getIntPropertyValue(codePoint, which);
}
/// <summary>
/// The given character is mapped to its lowercase equivalent according to UnicodeData.txt;
/// if the character has no lowercase equivalent, the character itself is returned.
///
/// This function only returns the simple, single-code point case mapping. Full case
/// mappings should be used whenever possible because they produce better results by
/// working on whole strings. They take into account the string context and the language
/// and can map to a result string with a different length as appropriate. Full case
/// mappings are applied by the string case mapping functions, <see cref="UnicodeString"/>
/// See also the User Guide chapter on C/POSIX migration:
/// <seealso href="http: //icu-project.org/userguide/posix.html#case_mappings"/>
/// </summary>
/// <param name="codePoint">the code point to be mapped </param>
/// <returns>the Simple_Lowercase_Mapping of the code point, if any; otherwise the code
/// point itself. </returns>
public static int ToLower(int codePoint)
{
return NativeMethods.u_tolower(codePoint);
}
/// <summary>
/// The given character is mapped to its titlecase equivalent according to UnicodeData.txt;
/// if the character has no lowercase equivalent, the character itself is returned.
///
/// This function only returns the simple, single-code point case mapping. Full case
/// mappings should be used whenever possible because they produce better results by
/// working on whole strings. They take into account the string context and the language
/// and can map to a result string with a different length as appropriate. Full case
/// mappings are applied by the string case mapping functions, <see cref="UnicodeString"/>
/// See also the User Guide chapter on C/POSIX migration:
/// <seealso href="http: //icu-project.org/userguide/posix.html#case_mappings"/>
/// </summary>
/// <param name="codePoint">the code point to be mapped </param>
/// <returns>the Simple_Titlecase_Mapping of the code point, if any; otherwise the code
/// point itself. </returns>
public static int ToTitle(int codePoint)
{
return NativeMethods.u_totitle(codePoint);
}
/// <summary>
/// The given character is mapped to its uppercase equivalent according to UnicodeData.txt;
/// if the character has no lowercase equivalent, the character itself is returned.
///
/// This function only returns the simple, single-code point case mapping. Full case
/// mappings should be used whenever possible because they produce better results by
/// working on whole strings. They take into account the string context and the language
/// and can map to a result string with a different length as appropriate. Full case
/// mappings are applied by the string case mapping functions, <see cref="UnicodeString"/>
/// See also the User Guide chapter on C/POSIX migration:
/// <seealso href="http: //icu-project.org/userguide/posix.html#case_mappings"/>
/// </summary>
/// <param name="codePoint">the code point to be mapped </param>
/// <returns>the Simple_Uppercase_Mapping of the code point, if any; otherwise the code
/// point itself. </returns>
public static int ToUpper(int codePoint)
{
return NativeMethods.u_toupper(codePoint);
}
}
}
| |
// Copyright (c) 2017 Andrew Vardeman. Published under the MIT license.
// See license.txt in the FileSharper distribution or repository for the
// full text of the license.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using FileSharperCore.Conditions;
using Newtonsoft.Json;
namespace FileSharperCore
{
public class ConditionNode: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string m_ConditionTypeName;
private bool m_Not;
private ConditionNode m_Owner;
private int m_Index;
private ICondition m_ConditionInternal;
private bool m_Loaded;
[JsonProperty(Order = int.MinValue)]
public string ConditionTypeName
{
get => m_ConditionTypeName;
set {
if (m_ConditionTypeName != value)
{
ConditionNode[] oldChildren = ChildNodes.ToArray();
ICondition oldCondition = m_ConditionInternal;
ChildNodes.Clear();
m_ConditionTypeName = value;
if (value == null)
{
ConditionInternal = null;
}
else
{
ConditionInternal = ConditionCatalog.Instance.CreateCondition(m_ConditionTypeName);
if (ConditionInternal is CompoundCondition)
{
if (oldChildren.Length > 0)
{
foreach (ConditionNode child in oldChildren)
{
ChildNodes.Add(child);
}
}
else if (Loaded)
{
ConditionNode starterNode = new ConditionNode();
if (oldCondition != null)
{
starterNode.ConditionTypeName = oldCondition.GetType().FullName;
starterNode.ConditionInternal = oldCondition;
starterNode.Not = this.Not;
}
this.Not = false;
starterNode.Loaded = Loaded;
ChildNodes.Add(starterNode);
}
}
}
OnPropertyChanged();
}
}
}
public bool Not
{
get => m_Not;
set => SetField(ref m_Not, value);
}
[JsonIgnore]
public bool Loaded
{
get
{
return m_Loaded;
}
set
{
if (m_Loaded != value)
{
m_Loaded = value;
foreach (ConditionNode child in ChildNodes)
{
child.Loaded = Loaded;
}
}
}
}
[JsonIgnore]
public ConditionNode Owner
{
get => m_Owner;
set
{
SetField(ref m_Owner, value);
OnPropertyChanged(nameof(First));
OnPropertyChanged(nameof(Last));
}
}
[JsonIgnore]
public int Index
{
get => m_Index;
set
{
SetField(ref m_Index, value);
OnPropertyChanged(nameof(First));
OnPropertyChanged(nameof(Last));
}
}
[JsonIgnore]
public bool First => Index == 0;
[JsonIgnore]
public bool Last => m_Owner != null && m_Owner.ChildNodes.Count - 1 == Index;
private ICondition ConditionInternal
{
get => m_ConditionInternal;
set
{
if (m_ConditionInternal != value)
{
ICondition old = m_ConditionInternal;
m_ConditionInternal = value;
OnPropertyChanged();
OnPropertyChanged(nameof(Parameters));
OnPropertyChanged(nameof(Description));
}
}
}
public string Description => m_ConditionInternal?.Description;
public object Parameters => m_ConditionInternal?.Parameters;
public ObservableCollection<ConditionNode> ChildNodes
{
get;
} = new ObservableCollection<ConditionNode>();
public ConditionNode()
{
ChildNodes.CollectionChanged += ChildNodes_CollectionChanged;
}
private void ChildNodes_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (ConditionNode newNode in e.NewItems)
{
newNode.Owner = this;
}
}
if (e.Action == NotifyCollectionChangedAction.Remove ||
e.Action == NotifyCollectionChangedAction.Replace ||
e.Action == NotifyCollectionChangedAction.Reset)
{
if (e.OldItems != null)
{
foreach (ConditionNode oldNode in e.OldItems)
{
oldNode.Owner = null;
}
}
}
for (int i = 0; i < ChildNodes.Count; i++)
{
ChildNodes[i].Index = i;
}
}
public ICondition BuildCondition()
{
ICondition condition = ConditionInternal;
if (condition is CompoundCondition)
{
CompoundCondition cc = (CompoundCondition)condition;
cc.Conditions.Clear();
foreach (ConditionNode child in ChildNodes)
{
ICondition childCondition = child.BuildCondition();
if (childCondition != null)
{
cc.Conditions.Add(childCondition);
}
}
}
if (condition != null && Not)
{
condition = new NotCondition(condition);
}
if (condition == null)
{
condition = new MatchEverythingCondition();
}
return condition;
}
[JsonIgnore]
public ICommand RemoveCommand { get { return new ChildNodeRemover(this); } }
[JsonIgnore]
public ICommand AddCommand { get { return new ChildNodeAdder(this); } }
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetField<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
public class ChildNodeRemover : ICommand
{
public event EventHandler CanExecuteChanged;
public ConditionNode Node
{
get; set;
}
public ChildNodeRemover(ConditionNode node)
{
Node = node;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
Node.ChildNodes.Remove((ConditionNode)parameter);
}
}
public class ChildNodeAdder : ICommand
{
public event EventHandler CanExecuteChanged;
public ConditionNode Node
{
get; set;
}
public ChildNodeAdder(ConditionNode node)
{
Node = node;
}
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
ConditionNode newNode = new ConditionNode();
newNode.Loaded = Node.Loaded;
Node.ChildNodes.Add(newNode);
}
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLoption = Interop.Http.CURLoption;
using CurlProtocols = Interop.Http.CurlProtocols;
using CURLProxyType = Interop.Http.curl_proxytype;
using SafeCurlHandle = Interop.Http.SafeCurlHandle;
using SafeCurlSListHandle = Interop.Http.SafeCurlSListHandle;
using SafeCallbackHandle = Interop.Http.SafeCallbackHandle;
using SeekCallback = Interop.Http.SeekCallback;
using ReadWriteCallback = Interop.Http.ReadWriteCallback;
using ReadWriteFunction = Interop.Http.ReadWriteFunction;
using SslCtxCallback = Interop.Http.SslCtxCallback;
using DebugCallback = Interop.Http.DebugCallback;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
/// <summary>Provides all of the state associated with a single request/response, referred to as an "easy" request in libcurl parlance.</summary>
private sealed class EasyRequest : TaskCompletionSource<HttpResponseMessage>
{
internal readonly CurlHandler _handler;
internal readonly HttpRequestMessage _requestMessage;
internal readonly CurlResponseMessage _responseMessage;
internal readonly CancellationToken _cancellationToken;
internal readonly HttpContentAsyncStream _requestContentStream;
internal SafeCurlHandle _easyHandle;
private SafeCurlSListHandle _requestHeaders;
internal MultiAgent _associatedMultiAgent;
internal SendTransferState _sendTransferState;
internal bool _isRedirect = false;
internal Uri _targetUri;
internal StrongToWeakReference<EasyRequest> _selfStrongToWeakReference;
private SafeCallbackHandle _callbackHandle;
public EasyRequest(CurlHandler handler, HttpRequestMessage requestMessage, CancellationToken cancellationToken) :
base(TaskCreationOptions.RunContinuationsAsynchronously)
{
_handler = handler;
_requestMessage = requestMessage;
_cancellationToken = cancellationToken;
if (requestMessage.Content != null)
{
_requestContentStream = new HttpContentAsyncStream(requestMessage.Content);
}
_responseMessage = new CurlResponseMessage(this);
_targetUri = requestMessage.RequestUri;
}
/// <summary>
/// Initialize the underlying libcurl support for this EasyRequest.
/// This is separated out of the constructor so that we can take into account
/// any additional configuration needed based on the request message
/// after the EasyRequest is configured and so that error handling
/// can be better handled in the caller.
/// </summary>
internal void InitializeCurl()
{
// Create the underlying easy handle
SafeCurlHandle easyHandle = Interop.Http.EasyCreate();
if (easyHandle.IsInvalid)
{
throw new OutOfMemoryException();
}
_easyHandle = easyHandle;
// Configure the handle
SetUrl();
SetMultithreading();
SetTimeouts();
SetRedirection();
SetVerb();
SetVersion();
SetDecompressionOptions();
SetProxyOptions(_requestMessage.RequestUri);
SetCredentialsOptions(_handler.GetCredentials(_requestMessage.RequestUri));
SetCookieOption(_requestMessage.RequestUri);
SetRequestHeaders();
SetSslOptions();
}
public void EnsureResponseMessagePublished()
{
// If the response message hasn't been published yet, do any final processing of it before it is.
if (!Task.IsCompleted)
{
// On Windows, if the response was automatically decompressed, Content-Encoding and Content-Length
// headers are removed from the response. Do the same thing here.
DecompressionMethods dm = _handler.AutomaticDecompression;
if (dm != DecompressionMethods.None)
{
HttpContentHeaders contentHeaders = _responseMessage.Content.Headers;
IEnumerable<string> encodings;
if (contentHeaders.TryGetValues(HttpKnownHeaderNames.ContentEncoding, out encodings))
{
foreach (string encoding in encodings)
{
if (((dm & DecompressionMethods.GZip) != 0 && string.Equals(encoding, EncodingNameGzip, StringComparison.OrdinalIgnoreCase)) ||
((dm & DecompressionMethods.Deflate) != 0 && string.Equals(encoding, EncodingNameDeflate, StringComparison.OrdinalIgnoreCase)))
{
contentHeaders.Remove(HttpKnownHeaderNames.ContentEncoding);
contentHeaders.Remove(HttpKnownHeaderNames.ContentLength);
break;
}
}
}
}
}
// Now ensure it's published.
bool completedTask = TrySetResult(_responseMessage);
Debug.Assert(completedTask || Task.Status == TaskStatus.RanToCompletion,
"If the task was already completed, it should have been completed successfully; " +
"we shouldn't be completing as successful after already completing as failed.");
// If we successfully transitioned it to be completed, we also handed off lifetime ownership
// of the response to the owner of the task. Transition our reference on the EasyRequest
// to be weak instead of strong, so that we don't forcibly keep it alive.
if (completedTask)
{
Debug.Assert(_selfStrongToWeakReference != null, "Expected non-null wrapper");
_selfStrongToWeakReference.MakeWeak();
}
}
public void FailRequestAndCleanup(Exception error)
{
FailRequest(error);
Cleanup();
}
public void FailRequest(Exception error)
{
Debug.Assert(error != null, "Expected non-null exception");
var oce = error as OperationCanceledException;
if (oce != null)
{
TrySetCanceled(oce.CancellationToken);
}
else
{
if (error is IOException || error is CurlException || error == null)
{
error = CreateHttpRequestException(error);
}
TrySetException(error);
}
// There's not much we can reasonably assert here about the result of TrySet*.
// It's possible that the task wasn't yet completed (e.g. a failure while initiating the request),
// it's possible that the task was already completed as success (e.g. a failure sending back the response),
// and it's possible that the task was already completed as failure (e.g. we handled the exception and
// faulted the task, but then tried to fault it again while finishing processing in the main loop).
// Make sure the exception is available on the response stream so that it's propagated
// from any attempts to read from the stream.
_responseMessage.ResponseStream.SignalComplete(error);
}
public void Cleanup() // not called Dispose because the request may still be in use after it's cleaned up
{
_responseMessage.ResponseStream.SignalComplete(); // No more callbacks so no more data
// Don't dispose of the ResponseMessage.ResponseStream as it may still be in use
// by code reading data stored in the stream.
// Dispose of the input content stream if there was one. Nothing should be using it any more.
_requestContentStream?.Dispose();
// Dispose of the underlying easy handle. We're no longer processing it.
_easyHandle?.Dispose();
// Dispose of the request headers if we had any. We had to keep this handle
// alive as long as the easy handle was using it. We didn't need to do any
// ref counting on the safe handle, though, as the only processing happens
// in Process, which ensures the handle will be rooted while libcurl is
// doing any processing that assumes it's valid.
_requestHeaders?.Dispose();
_callbackHandle?.Dispose();
}
private void SetUrl()
{
EventSourceTrace("Url: {0}", _requestMessage.RequestUri);
SetCurlOption(CURLoption.CURLOPT_URL, _requestMessage.RequestUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_PROTOCOLS, (long)(CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS));
}
private void SetMultithreading()
{
SetCurlOption(CURLoption.CURLOPT_NOSIGNAL, 1L);
}
private void SetTimeouts()
{
// Set timeout limit on the connect phase.
SetCurlOption(CURLoption.CURLOPT_CONNECTTIMEOUT_MS, _handler.ConnectTimeout == Timeout.InfiniteTimeSpan ?
int.MaxValue :
Math.Max(1, (long)_handler.ConnectTimeout.TotalMilliseconds));
// Override the default DNS cache timeout. libcurl defaults to a 1 minute
// timeout, but we extend that to match the Windows timeout of 10 minutes.
const int DnsCacheTimeoutSeconds = 10 * 60;
SetCurlOption(CURLoption.CURLOPT_DNS_CACHE_TIMEOUT, DnsCacheTimeoutSeconds);
}
private void SetRedirection()
{
if (!_handler._automaticRedirection)
{
return;
}
SetCurlOption(CURLoption.CURLOPT_FOLLOWLOCATION, 1L);
CurlProtocols redirectProtocols = string.Equals(_requestMessage.RequestUri.Scheme, UriSchemeHttps, StringComparison.OrdinalIgnoreCase) ?
CurlProtocols.CURLPROTO_HTTPS : // redirect only to another https
CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS; // redirect to http or to https
SetCurlOption(CURLoption.CURLOPT_REDIR_PROTOCOLS, (long)redirectProtocols);
SetCurlOption(CURLoption.CURLOPT_MAXREDIRS, _handler._maxAutomaticRedirections);
EventSourceTrace("Max automatic redirections: {0}", _handler._maxAutomaticRedirections);
}
private void SetContentLength(CURLoption lengthOption)
{
Debug.Assert(lengthOption == CURLoption.CURLOPT_POSTFIELDSIZE || lengthOption == CURLoption.CURLOPT_INFILESIZE);
if (_requestMessage.Content == null)
{
// Tell libcurl there's no data to be sent.
SetCurlOption(lengthOption, 0L);
return;
}
long? contentLengthOpt = _requestMessage.Content.Headers.ContentLength;
if (contentLengthOpt != null)
{
long contentLength = contentLengthOpt.GetValueOrDefault();
if (contentLength <= int.MaxValue)
{
// Tell libcurl how much data we expect to send.
SetCurlOption(lengthOption, contentLength);
}
else
{
// Similarly, tell libcurl how much data we expect to send. However,
// as the amount is larger than a 32-bit value, switch to the "_LARGE"
// equivalent libcurl options.
SetCurlOption(
lengthOption == CURLoption.CURLOPT_INFILESIZE ? CURLoption.CURLOPT_INFILESIZE_LARGE : CURLoption.CURLOPT_POSTFIELDSIZE_LARGE,
contentLength);
}
return;
}
// There is content but we couldn't determine its size. Don't set anything.
}
private void SetVerb()
{
EventSourceTrace<string>("Verb: {0}", _requestMessage.Method.Method);
if (_requestMessage.Method == HttpMethod.Put)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
SetContentLength(CURLoption.CURLOPT_INFILESIZE);
}
else if (_requestMessage.Method == HttpMethod.Head)
{
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else if (_requestMessage.Method == HttpMethod.Post)
{
SetCurlOption(CURLoption.CURLOPT_POST, 1L);
SetContentLength(CURLoption.CURLOPT_POSTFIELDSIZE);
}
else if (_requestMessage.Method == HttpMethod.Trace)
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
if (_requestMessage.Content != null)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
SetContentLength(CURLoption.CURLOPT_INFILESIZE);
}
}
}
private void SetVersion()
{
Version v = _requestMessage.Version;
if (v != null)
{
// Try to use the requested version, if a known version was explicitly requested.
// If an unknown version was requested, we simply use libcurl's default.
var curlVersion =
(v.Major == 1 && v.Minor == 1) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_1 :
(v.Major == 1 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_0 :
(v.Major == 2 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_2_0 :
Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE;
if (curlVersion != Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE)
{
// Ask libcurl to use the specified version if possible.
CURLcode c = Interop.Http.EasySetOptionLong(_easyHandle, CURLoption.CURLOPT_HTTP_VERSION, (long)curlVersion);
if (c == CURLcode.CURLE_OK)
{
// Success. The requested version will be used.
EventSourceTrace("HTTP version: {0}", v);
}
else if (c == CURLcode.CURLE_UNSUPPORTED_PROTOCOL)
{
// The requested version is unsupported. Fall back to using the default version chosen by libcurl.
EventSourceTrace("Unsupported protocol: {0}", v);
}
else
{
// Some other error. Fail.
ThrowIfCURLEError(c);
}
}
}
}
private void SetDecompressionOptions()
{
if (!_handler.SupportsAutomaticDecompression)
{
return;
}
DecompressionMethods autoDecompression = _handler.AutomaticDecompression;
bool gzip = (autoDecompression & DecompressionMethods.GZip) != 0;
bool deflate = (autoDecompression & DecompressionMethods.Deflate) != 0;
if (gzip || deflate)
{
string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate :
gzip ? EncodingNameGzip :
EncodingNameDeflate;
SetCurlOption(CURLoption.CURLOPT_ACCEPT_ENCODING, encoding);
EventSourceTrace<string>("Encoding: {0}", encoding);
}
}
internal void SetProxyOptions(Uri requestUri)
{
if (!_handler._useProxy)
{
// Explicitly disable the use of a proxy. This will prevent libcurl from using
// any proxy, including ones set via environment variable.
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
EventSourceTrace("UseProxy false, disabling proxy");
return;
}
if (_handler.Proxy == null)
{
// UseProxy was true, but Proxy was null. Let libcurl do its default handling,
// which includes checking the http_proxy environment variable.
EventSourceTrace("UseProxy true, Proxy null, using default proxy");
// Since that proxy set in an environment variable might require a username and password,
// use the default proxy credentials if there are any. Currently only NetworkCredentials
// are used, as we can't query by the proxy Uri, since we don't know it.
SetProxyCredentials(_handler.DefaultProxyCredentials as NetworkCredential);
return;
}
// Custom proxy specified.
Uri proxyUri;
try
{
// Should we bypass a proxy for this URI?
if (_handler.Proxy.IsBypassed(requestUri))
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
EventSourceTrace("Proxy's IsBypassed returned true, bypassing proxy");
return;
}
// Get the proxy Uri for this request.
proxyUri = _handler.Proxy.GetProxy(requestUri);
if (proxyUri == null)
{
EventSourceTrace("GetProxy returned null, using default.");
return;
}
}
catch (PlatformNotSupportedException)
{
// WebRequest.DefaultWebProxy throws PlatformNotSupportedException,
// in which case we should use the default rather than the custom proxy.
EventSourceTrace("PlatformNotSupportedException from proxy, using default");
return;
}
// Configure libcurl with the gathered proxy information
SetCurlOption(CURLoption.CURLOPT_PROXYTYPE, (long)CURLProxyType.CURLPROXY_HTTP);
SetCurlOption(CURLoption.CURLOPT_PROXY, proxyUri.AbsoluteUri);
SetCurlOption(CURLoption.CURLOPT_PROXYPORT, proxyUri.Port);
EventSourceTrace("Proxy: {0}", proxyUri);
KeyValuePair<NetworkCredential, CURLAUTH> credentialScheme = GetCredentials(
proxyUri, _handler.Proxy.Credentials, s_orderedAuthTypes);
SetProxyCredentials(credentialScheme.Key);
}
private void SetProxyCredentials(NetworkCredential credentials)
{
if (credentials == CredentialCache.DefaultCredentials)
{
// No "default credentials" on Unix; nop just like UseDefaultCredentials.
EventSourceTrace("DefaultCredentials set for proxy. Skipping.");
}
else if (credentials != null)
{
if (string.IsNullOrEmpty(credentials.UserName))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "UserName");
}
// Unlike normal credentials, proxy credentials are URL decoded by libcurl, so we URL encode
// them in order to allow, for example, a colon in the username.
string credentialText = string.IsNullOrEmpty(credentials.Domain) ?
string.Format("{0}:{1}", WebUtility.UrlEncode(credentials.UserName), WebUtility.UrlEncode(credentials.Password)) :
string.Format("{2}\\{0}:{1}", WebUtility.UrlEncode(credentials.UserName), WebUtility.UrlEncode(credentials.Password), WebUtility.UrlEncode(credentials.Domain));
EventSourceTrace("Proxy credentials set.");
SetCurlOption(CURLoption.CURLOPT_PROXYUSERPWD, credentialText);
}
}
internal void SetCredentialsOptions(KeyValuePair<NetworkCredential, CURLAUTH> credentialSchemePair)
{
if (credentialSchemePair.Key == null)
{
return;
}
NetworkCredential credentials = credentialSchemePair.Key;
CURLAUTH authScheme = credentialSchemePair.Value;
string userName = string.IsNullOrEmpty(credentials.Domain) ?
credentials.UserName :
string.Format("{0}\\{1}", credentials.Domain, credentials.UserName);
SetCurlOption(CURLoption.CURLOPT_USERNAME, userName);
SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, (long)authScheme);
if (credentials.Password != null)
{
SetCurlOption(CURLoption.CURLOPT_PASSWORD, credentials.Password);
}
EventSourceTrace("Credentials set.");
}
internal void SetCookieOption(Uri uri)
{
if (!_handler._useCookie)
{
return;
}
string cookieValues = _handler.CookieContainer.GetCookieHeader(uri);
if (!string.IsNullOrEmpty(cookieValues))
{
SetCurlOption(CURLoption.CURLOPT_COOKIE, cookieValues);
EventSourceTrace<string>("Cookies: {0}", cookieValues);
}
}
internal void SetRequestHeaders()
{
var slist = new SafeCurlSListHandle();
// Add content request headers
if (_requestMessage.Content != null)
{
SetChunkedModeForSend(_requestMessage);
_requestMessage.Content.Headers.Remove(HttpKnownHeaderNames.ContentLength); // avoid overriding libcurl's handling via INFILESIZE/POSTFIELDSIZE
AddRequestHeaders(_requestMessage.Content.Headers, slist);
if (_requestMessage.Content.Headers.ContentType == null)
{
// Remove the Content-Type header libcurl adds by default.
ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoContentType));
}
}
// Add request headers
AddRequestHeaders(_requestMessage.Headers, slist);
// Since libcurl always adds a Transfer-Encoding header, we need to explicitly block
// it if caller specifically does not want to set the header
if (_requestMessage.Headers.TransferEncodingChunked.HasValue &&
!_requestMessage.Headers.TransferEncodingChunked.Value)
{
ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoTransferEncoding));
}
if (!slist.IsInvalid)
{
SafeCurlSListHandle prevList = _requestHeaders;
_requestHeaders = slist;
SetCurlOption(CURLoption.CURLOPT_HTTPHEADER, slist);
prevList?.Dispose();
}
else
{
slist.Dispose();
}
}
private void SetSslOptions()
{
// SSL Options should be set regardless of the type of the original request,
// in case an http->https redirection occurs.
//
// While this does slow down the theoretical best path of the request the code
// to decide that we need to register the callback is more complicated than, and
// potentially more expensive than, just always setting the callback.
SslProvider.SetSslOptions(this, _handler.ClientCertificateOptions);
}
internal void SetCurlCallbacks(
IntPtr easyGCHandle,
ReadWriteCallback receiveHeadersCallback,
ReadWriteCallback sendCallback,
SeekCallback seekCallback,
ReadWriteCallback receiveBodyCallback,
DebugCallback debugCallback)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
// Add callback for processing headers
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Header,
receiveHeadersCallback,
easyGCHandle,
ref _callbackHandle);
// If we're sending data as part of the request, add callbacks for sending request data
if (_requestMessage.Content != null)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Read,
sendCallback,
easyGCHandle,
ref _callbackHandle);
Interop.Http.RegisterSeekCallback(
_easyHandle,
seekCallback,
easyGCHandle,
ref _callbackHandle);
}
// If we're expecting any data in response, add a callback for receiving body data
if (_requestMessage.Method != HttpMethod.Head)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Write,
receiveBodyCallback,
easyGCHandle,
ref _callbackHandle);
}
if (EventSourceTracingEnabled)
{
SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L);
CURLcode curlResult = Interop.Http.RegisterDebugCallback(
_easyHandle,
debugCallback,
easyGCHandle,
ref _callbackHandle);
if (curlResult != CURLcode.CURLE_OK)
{
EventSourceTrace("Failed to register debug callback.");
}
}
}
internal CURLcode SetSslCtxCallback(SslCtxCallback callback, IntPtr userPointer)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
CURLcode result = Interop.Http.RegisterSslCtxCallback(_easyHandle, callback, userPointer, ref _callbackHandle);
return result;
}
private static void AddRequestHeaders(HttpHeaders headers, SafeCurlSListHandle handle)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
{
string headerValue = headers.GetHeaderString(header.Key);
string headerKeyAndValue = string.IsNullOrEmpty(headerValue) ?
header.Key + ";" : // semicolon used by libcurl to denote empty value that should be sent
header.Key + ": " + headerValue;
ThrowOOMIfFalse(Interop.Http.SListAppend(handle, headerKeyAndValue));
}
}
internal void SetCurlOption(CURLoption option, string value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionString(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, long value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionLong(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, IntPtr value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, SafeHandle value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
private static void ThrowOOMIfFalse(bool appendResult)
{
if (!appendResult)
throw CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_OUT_OF_MEMORY, isMulti: false));
}
internal sealed class SendTransferState
{
internal readonly byte[] _buffer;
internal int _offset;
internal int _count;
internal Task<int> _task;
internal SendTransferState(int bufferLength)
{
Debug.Assert(bufferLength > 0 && bufferLength <= MaxRequestBufferSize, $"Expected 0 < bufferLength <= {MaxRequestBufferSize}, got {bufferLength}");
_buffer = new byte[bufferLength];
}
internal void SetTaskOffsetCount(Task<int> task, int offset, int count)
{
Debug.Assert(offset >= 0, "Offset should never be negative");
Debug.Assert(count >= 0, "Count should never be negative");
Debug.Assert(offset <= count, "Offset should never be greater than count");
_task = task;
_offset = offset;
_count = count;
}
}
internal void SetRedirectUri(Uri redirectUri)
{
_targetUri = _requestMessage.RequestUri;
_requestMessage.RequestUri = redirectUri;
}
private void EventSourceTrace<TArg0>(string formatMessage, TArg0 arg0, [CallerMemberName] string memberName = null)
{
CurlHandler.EventSourceTrace(formatMessage, arg0, easy: this, memberName: memberName);
}
private void EventSourceTrace(string message, [CallerMemberName] string memberName = null)
{
CurlHandler.EventSourceTrace(message, easy: this, memberName: memberName);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type float with 2 columns and 4 rows.
/// </summary>
[Serializable]
[DataContract(Namespace = "mat")]
[StructLayout(LayoutKind.Sequential)]
public struct mat2x4 : IReadOnlyList<float>, IEquatable<mat2x4>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
[DataMember]
public float m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
[DataMember]
public float m01;
/// <summary>
/// Column 0, Rows 2
/// </summary>
[DataMember]
public float m02;
/// <summary>
/// Column 0, Rows 3
/// </summary>
[DataMember]
public float m03;
/// <summary>
/// Column 1, Rows 0
/// </summary>
[DataMember]
public float m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
[DataMember]
public float m11;
/// <summary>
/// Column 1, Rows 2
/// </summary>
[DataMember]
public float m12;
/// <summary>
/// Column 1, Rows 3
/// </summary>
[DataMember]
public float m13;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public mat2x4(float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13)
{
this.m00 = m00;
this.m01 = m01;
this.m02 = m02;
this.m03 = m03;
this.m10 = m10;
this.m11 = m11;
this.m12 = m12;
this.m13 = m13;
}
/// <summary>
/// Constructs this matrix from a mat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0f;
this.m03 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0f;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0f;
this.m03 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0f;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0f;
this.m03 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0f;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = 0f;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a mat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a mat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a mat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(mat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m03 = m.m03;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m13 = m.m13;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(vec2 c0, vec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = 0f;
this.m03 = 0f;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = 0f;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(vec3 c0, vec3 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = 0f;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = 0f;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public mat2x4(vec4 c0, vec4 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m03 = c0.w;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m13 = c1.w;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public float[,] Values => new[,] { { m00, m01, m02, m03 }, { m10, m11, m12, m13 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public float[] Values1D => new[] { m00, m01, m02, m03, m10, m11, m12, m13 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public vec4 Column0
{
get
{
return new vec4(m00, m01, m02, m03);
}
set
{
m00 = value.x;
m01 = value.y;
m02 = value.z;
m03 = value.w;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public vec4 Column1
{
get
{
return new vec4(m10, m11, m12, m13);
}
set
{
m10 = value.x;
m11 = value.y;
m12 = value.z;
m13 = value.w;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public vec2 Row0
{
get
{
return new vec2(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public vec2 Row1
{
get
{
return new vec2(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 2
/// </summary>
public vec2 Row2
{
get
{
return new vec2(m02, m12);
}
set
{
m02 = value.x;
m12 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 3
/// </summary>
public vec2 Row3
{
get
{
return new vec2(m03, m13);
}
set
{
m03 = value.x;
m13 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static mat2x4 Zero { get; } = new mat2x4(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static mat2x4 Ones { get; } = new mat2x4(1f, 1f, 1f, 1f, 1f, 1f, 1f, 1f);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static mat2x4 Identity { get; } = new mat2x4(1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f);
/// <summary>
/// Predefined all-MaxValue matrix
/// </summary>
public static mat2x4 AllMaxValue { get; } = new mat2x4(float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue, float.MaxValue);
/// <summary>
/// Predefined diagonal-MaxValue matrix
/// </summary>
public static mat2x4 DiagonalMaxValue { get; } = new mat2x4(float.MaxValue, 0f, 0f, 0f, 0f, float.MaxValue, 0f, 0f);
/// <summary>
/// Predefined all-MinValue matrix
/// </summary>
public static mat2x4 AllMinValue { get; } = new mat2x4(float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue, float.MinValue);
/// <summary>
/// Predefined diagonal-MinValue matrix
/// </summary>
public static mat2x4 DiagonalMinValue { get; } = new mat2x4(float.MinValue, 0f, 0f, 0f, 0f, float.MinValue, 0f, 0f);
/// <summary>
/// Predefined all-Epsilon matrix
/// </summary>
public static mat2x4 AllEpsilon { get; } = new mat2x4(float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon, float.Epsilon);
/// <summary>
/// Predefined diagonal-Epsilon matrix
/// </summary>
public static mat2x4 DiagonalEpsilon { get; } = new mat2x4(float.Epsilon, 0f, 0f, 0f, 0f, float.Epsilon, 0f, 0f);
/// <summary>
/// Predefined all-NaN matrix
/// </summary>
public static mat2x4 AllNaN { get; } = new mat2x4(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN);
/// <summary>
/// Predefined diagonal-NaN matrix
/// </summary>
public static mat2x4 DiagonalNaN { get; } = new mat2x4(float.NaN, 0f, 0f, 0f, 0f, float.NaN, 0f, 0f);
/// <summary>
/// Predefined all-NegativeInfinity matrix
/// </summary>
public static mat2x4 AllNegativeInfinity { get; } = new mat2x4(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity);
/// <summary>
/// Predefined diagonal-NegativeInfinity matrix
/// </summary>
public static mat2x4 DiagonalNegativeInfinity { get; } = new mat2x4(float.NegativeInfinity, 0f, 0f, 0f, 0f, float.NegativeInfinity, 0f, 0f);
/// <summary>
/// Predefined all-PositiveInfinity matrix
/// </summary>
public static mat2x4 AllPositiveInfinity { get; } = new mat2x4(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
/// <summary>
/// Predefined diagonal-PositiveInfinity matrix
/// </summary>
public static mat2x4 DiagonalPositiveInfinity { get; } = new mat2x4(float.PositiveInfinity, 0f, 0f, 0f, 0f, float.PositiveInfinity, 0f, 0f);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<float> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m02;
yield return m03;
yield return m10;
yield return m11;
yield return m12;
yield return m13;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 4 = 8).
/// </summary>
public int Count => 8;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public float this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m02;
case 3: return m03;
case 4: return m10;
case 5: return m11;
case 6: return m12;
case 7: return m13;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m02 = value; break;
case 3: this.m03 = value; break;
case 4: this.m10 = value; break;
case 5: this.m11 = value; break;
case 6: this.m12 = value; break;
case 7: this.m13 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public float this[int col, int row]
{
get
{
return this[col * 4 + row];
}
set
{
this[col * 4 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(mat2x4 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m02.Equals(rhs.m02) && m03.Equals(rhs.m03))) && ((m10.Equals(rhs.m10) && m11.Equals(rhs.m11)) && (m12.Equals(rhs.m12) && m13.Equals(rhs.m13))));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is mat2x4 && Equals((mat2x4) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(mat2x4 lhs, mat2x4 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(mat2x4 lhs, mat2x4 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m03.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode()) * 397) ^ m13.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public mat4x2 Transposed => new mat4x2(m00, m10, m01, m11, m02, m12, m03, m13);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public float MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m02), m03), m10), m11), m12), m13);
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public float MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m02), m03), m10), m11), m12), m13);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public float Length => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))));
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public float LengthSqr => (((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public float Sum => (((m00 + m01) + (m02 + m03)) + ((m10 + m11) + (m12 + m13)));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public float Norm => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))));
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public float Norm1 => (((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m02) + Math.Abs(m03))) + ((Math.Abs(m10) + Math.Abs(m11)) + (Math.Abs(m12) + Math.Abs(m13))));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public float Norm2 => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))));
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public float NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m02)), Math.Abs(m03)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m12)), Math.Abs(m13));
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m02), p) + Math.Pow((double)Math.Abs(m03), p))) + ((Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p)) + (Math.Pow((double)Math.Abs(m12), p) + Math.Pow((double)Math.Abs(m13), p)))), 1 / p);
/// <summary>
/// Executes a matrix-matrix-multiplication mat2x4 * mat2 -> mat2x4.
/// </summary>
public static mat2x4 operator*(mat2x4 lhs, mat2 rhs) => new mat2x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11));
/// <summary>
/// Executes a matrix-matrix-multiplication mat2x4 * mat3x2 -> mat3x4.
/// </summary>
public static mat3x4 operator*(mat2x4 lhs, mat3x2 rhs) => new mat3x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21));
/// <summary>
/// Executes a matrix-matrix-multiplication mat2x4 * mat4x2 -> mat4.
/// </summary>
public static mat4 operator*(mat2x4 lhs, mat4x2 rhs) => new mat4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31), (lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31), (lhs.m03 * rhs.m30 + lhs.m13 * rhs.m31));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static vec4 operator*(mat2x4 m, vec2 v) => new vec4((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y), (m.m02 * v.x + m.m12 * v.y), (m.m03 * v.x + m.m13 * v.y));
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static mat2x4 CompMul(mat2x4 A, mat2x4 B) => new mat2x4(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m03 * B.m03, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12, A.m13 * B.m13);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static mat2x4 CompDiv(mat2x4 A, mat2x4 B) => new mat2x4(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m03 / B.m03, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12, A.m13 / B.m13);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static mat2x4 CompAdd(mat2x4 A, mat2x4 B) => new mat2x4(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m03 + B.m03, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12, A.m13 + B.m13);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static mat2x4 CompSub(mat2x4 A, mat2x4 B) => new mat2x4(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m03 - B.m03, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12, A.m13 - B.m13);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static mat2x4 operator+(mat2x4 lhs, mat2x4 rhs) => new mat2x4(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m03 + rhs.m03, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12, lhs.m13 + rhs.m13);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static mat2x4 operator+(mat2x4 lhs, float rhs) => new mat2x4(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m03 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs, lhs.m13 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static mat2x4 operator+(float lhs, mat2x4 rhs) => new mat2x4(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m03, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12, lhs + rhs.m13);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static mat2x4 operator-(mat2x4 lhs, mat2x4 rhs) => new mat2x4(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m03 - rhs.m03, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12, lhs.m13 - rhs.m13);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static mat2x4 operator-(mat2x4 lhs, float rhs) => new mat2x4(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m03 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs, lhs.m13 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static mat2x4 operator-(float lhs, mat2x4 rhs) => new mat2x4(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m03, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12, lhs - rhs.m13);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static mat2x4 operator/(mat2x4 lhs, float rhs) => new mat2x4(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m03 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs, lhs.m13 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static mat2x4 operator/(float lhs, mat2x4 rhs) => new mat2x4(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m03, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12, lhs / rhs.m13);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static mat2x4 operator*(mat2x4 lhs, float rhs) => new mat2x4(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m03 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs, lhs.m13 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static mat2x4 operator*(float lhs, mat2x4 rhs) => new mat2x4(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m03, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12, lhs * rhs.m13);
/// <summary>
/// Executes a component-wise lesser-than comparison.
/// </summary>
public static bmat2x4 operator<(mat2x4 lhs, mat2x4 rhs) => new bmat2x4(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m02 < rhs.m02, lhs.m03 < rhs.m03, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m12 < rhs.m12, lhs.m13 < rhs.m13);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator<(mat2x4 lhs, float rhs) => new bmat2x4(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m02 < rhs, lhs.m03 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m12 < rhs, lhs.m13 < rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator<(float lhs, mat2x4 rhs) => new bmat2x4(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m02, lhs < rhs.m03, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m12, lhs < rhs.m13);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison.
/// </summary>
public static bmat2x4 operator<=(mat2x4 lhs, mat2x4 rhs) => new bmat2x4(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m02 <= rhs.m02, lhs.m03 <= rhs.m03, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m12 <= rhs.m12, lhs.m13 <= rhs.m13);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator<=(mat2x4 lhs, float rhs) => new bmat2x4(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m02 <= rhs, lhs.m03 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m12 <= rhs, lhs.m13 <= rhs);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator<=(float lhs, mat2x4 rhs) => new bmat2x4(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m02, lhs <= rhs.m03, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m12, lhs <= rhs.m13);
/// <summary>
/// Executes a component-wise greater-than comparison.
/// </summary>
public static bmat2x4 operator>(mat2x4 lhs, mat2x4 rhs) => new bmat2x4(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m02 > rhs.m02, lhs.m03 > rhs.m03, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m12 > rhs.m12, lhs.m13 > rhs.m13);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator>(mat2x4 lhs, float rhs) => new bmat2x4(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m02 > rhs, lhs.m03 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m12 > rhs, lhs.m13 > rhs);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2x4 operator>(float lhs, mat2x4 rhs) => new bmat2x4(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m02, lhs > rhs.m03, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m12, lhs > rhs.m13);
/// <summary>
/// Executes a component-wise greater-or-equal comparison.
/// </summary>
public static bmat2x4 operator>=(mat2x4 lhs, mat2x4 rhs) => new bmat2x4(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m02 >= rhs.m02, lhs.m03 >= rhs.m03, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m12 >= rhs.m12, lhs.m13 >= rhs.m13);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator>=(mat2x4 lhs, float rhs) => new bmat2x4(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m02 >= rhs, lhs.m03 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m12 >= rhs, lhs.m13 >= rhs);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2x4 operator>=(float lhs, mat2x4 rhs) => new bmat2x4(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m02, lhs >= rhs.m03, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m12, lhs >= rhs.m13);
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, [email protected], FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections.Generic;
using log4net;
using FluorineFx.Messaging.Api;
using FluorineFx.Messaging.Api.Messaging;
using FluorineFx.Messaging.Api.Stream;
using FluorineFx.Messaging.Api.Statistics;
using FluorineFx.Messaging.Api.Event;
using FluorineFx.Messaging.Rtmp.Messaging;
using FluorineFx.Messaging.Rtmp.Event;
using FluorineFx.Messaging.Rtmp.Stream;
using FluorineFx.Messaging.Rtmp.Stream.Codec;
using FluorineFx.Messaging.Rtmp.Stream.Consumer;
using FluorineFx.Messaging.Rtmp.Stream.Messages;
using FluorineFx.Messaging.Messages;
using FluorineFx.Collections;
using FluorineFx.Collections.Generic;
namespace FluorineFx.Messaging.Rtmp.Stream
{
/// <summary>
/// An implementation of IBroadcastStream that allows connectionless providers to publish a stream.
/// </summary>
[CLSCompliant(false)]
public class BroadcastStream : AbstractStream, IBroadcastStream, IProvider, IPipeConnectionListener
{
private static ILog log = LogManager.GetLogger(typeof(BroadcastStream));
protected IPipe _livePipe;
/// <summary>
/// Factory object for video codecs.
/// </summary>
private VideoCodecFactory _videoCodecFactory = null;
/// <summary>
/// Listeners to get notified about received packets.
/// </summary>
private CopyOnWriteArraySet<IStreamListener> _listeners = new CopyOnWriteArraySet<IStreamListener>();
/// <summary>
/// Initializes a new instance of the <see cref="BroadcastStream"/> class.
/// </summary>
/// <param name="name">The stream name.</param>
/// <param name="scope">The stream scope.</param>
public BroadcastStream(String name, IScope scope)
{
_name = name;
_scope = scope;
_livePipe = null;
// We want to create a video codec when we get our first video packet.
_codecInfo = new StreamCodecInfo();
_creationTime = -1;
}
public override void Start()
{
try
{
_videoCodecFactory = this.Scope.GetService(typeof(VideoCodecFactory)) as VideoCodecFactory;
}
catch (Exception ex)
{
log.Warn("No video codec factory available.", ex);
}
}
#region IMessageComponent Members
/// <summary>
/// Handles out-of-band control message.
/// </summary>
/// <param name="source">Message component source.</param>
/// <param name="pipe">Connection pipe.</param>
/// <param name="oobCtrlMsg">Out-of-band control message</param>
public void OnOOBControlMessage(IMessageComponent source, IPipe pipe, OOBControlMessage oobCtrlMsg)
{
}
#endregion
#region IPipeConnectionListener Members
/// <summary>
/// Pipe connection event handler. There are two types of pipe connection events so far,
/// provider push connection event and provider disconnection event.
/// </summary>
/// <param name="evt"></param>
public void OnPipeConnectionEvent(PipeConnectionEvent evt)
{
switch (evt.Type)
{
case PipeConnectionEvent.PROVIDER_CONNECT_PUSH:
if (evt.Provider == this && (evt.ParameterMap == null || !evt.ParameterMap.ContainsKey("record")))
{
_livePipe = evt.Source as IPipe;
}
break;
case PipeConnectionEvent.PROVIDER_DISCONNECT:
if (_livePipe == evt.Source)
_livePipe = null;
break;
case PipeConnectionEvent.CONSUMER_CONNECT_PUSH:
break;
case PipeConnectionEvent.CONSUMER_DISCONNECT:
break;
default:
break;
}
}
#endregion
#region IBroadcastStream Members
public void SaveAs(string filePath, bool isAppend)
{
throw new NotImplementedException("The method or operation is not implemented.");
}
public string SaveFilename
{
get { throw new NotImplementedException("The method or operation is not implemented."); }
}
public string PublishedName
{
get
{
return this.Name;
}
set
{
this.Name = value;
}
}
public IProvider Provider
{
get { return this; }
}
public void AddStreamListener(IStreamListener listener)
{
_listeners.Add(listener);
}
public void RemoveStreamListener(IStreamListener listener)
{
_listeners.Remove(listener);
}
public System.Collections.ICollection GetStreamListeners()
{
return _listeners;
}
#endregion
public void DispatchEvent(IEvent @event)
{
try
{
if (@event is IRtmpEvent)
{
IRtmpEvent rtmpEvent = @event as IRtmpEvent;
if (_livePipe != null)
{
RtmpMessage msg = new RtmpMessage();
msg.body = rtmpEvent;
if (_creationTime == -1)
_creationTime = rtmpEvent.Timestamp;
try
{
if (@event is AudioData)
{
(_codecInfo as StreamCodecInfo).HasAudio = true;
}
else if (@event is VideoData)
{
IVideoStreamCodec videoStreamCodec = null;
if (_codecInfo.VideoCodec == null)
{
videoStreamCodec = _videoCodecFactory.GetVideoCodec((@event as VideoData).Data);
(_codecInfo as StreamCodecInfo).VideoCodec = videoStreamCodec;
}
else if (_codecInfo != null)
{
videoStreamCodec = _codecInfo.VideoCodec;
}
if (videoStreamCodec != null)
{
videoStreamCodec.AddData((rtmpEvent as VideoData).Data);
}
if (_codecInfo != null)
(_codecInfo as StreamCodecInfo).HasVideo = true;
}
_livePipe.PushMessage(msg);
// Notify listeners about received packet
if (rtmpEvent is IStreamPacket)
{
foreach (IStreamListener listener in GetStreamListeners())
{
try
{
listener.PacketReceived(this, rtmpEvent as IStreamPacket);
}
catch (Exception ex)
{
log.Error("Error while notifying listener " + listener, ex);
}
}
}
}
catch (Exception ex)
{
// ignore
log.Error("DispatchEvent exception", ex);
}
}
}
}
finally
{
}
}
}
}
| |
// 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightLogicalInt1616()
{
var test = new ImmUnaryOpTest__ShiftRightLogicalInt1616();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmUnaryOpTest__ShiftRightLogicalInt1616
{
private struct TestStruct
{
public Vector128<Int16> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalInt1616 testClass)
{
var result = Sse2.ShiftRightLogical(_fld, 16);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data = new Int16[Op1ElementCount];
private static Vector128<Int16> _clsVar;
private Vector128<Int16> _fld;
private SimpleUnaryOpTest__DataTable<Int16, Int16> _dataTable;
static ImmUnaryOpTest__ShiftRightLogicalInt1616()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public ImmUnaryOpTest__ShiftRightLogicalInt1616()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld), ref Unsafe.As<Int16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new SimpleUnaryOpTest__DataTable<Int16, Int16>(_data, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.ShiftRightLogical(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.ShiftRightLogical(
Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.ShiftRightLogical(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)),
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr)),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical), new Type[] { typeof(Vector128<Int16>), typeof(byte) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr)),
(byte)16
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.ShiftRightLogical(
_clsVar,
16
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<Int16>>(_dataTable.inArrayPtr);
var result = Sse2.ShiftRightLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((Int16*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArrayPtr));
var result = Sse2.ShiftRightLogical(firstOp, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmUnaryOpTest__ShiftRightLogicalInt1616();
var result = Sse2.ShiftRightLogical(test._fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.ShiftRightLogical(_fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.ShiftRightLogical(test._fld, 16);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int16> firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray = new Int16[Op1ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Int16[] firstOp, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (0 != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0 != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical)}<Int16>(Vector128<Int16><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Framework.Threading;
using osu.Game.Extensions;
using osu.Game.Graphics.Cursor;
using osu.Game.Graphics.UserInterface;
using osu.Game.Input.Bindings;
using osu.Game.Online.Rooms;
using osuTK;
namespace osu.Game.Screens.OnlinePlay.Lounge.Components
{
public class RoomsContainer : CompositeDrawable, IKeyBindingHandler<GlobalAction>
{
private readonly IBindableList<Room> rooms = new BindableList<Room>();
private readonly FillFlowContainer<DrawableRoom> roomFlow;
public IReadOnlyList<DrawableRoom> Rooms => roomFlow.FlowingChildren.Cast<DrawableRoom>().ToArray();
[Resolved(CanBeNull = true)]
private Bindable<FilterCriteria> filter { get; set; }
[Resolved]
private Bindable<Room> selectedRoom { get; set; }
[Resolved]
private IRoomManager roomManager { get; set; }
[Resolved(CanBeNull = true)]
private LoungeSubScreen loungeSubScreen { get; set; }
// handle deselection
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => true;
public RoomsContainer()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
// account for the fact we are in a scroll container and want a bit of spacing from the scroll bar.
Padding = new MarginPadding { Right = 5 };
InternalChild = new OsuContextMenuContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Child = roomFlow = new FillFlowContainer<DrawableRoom>
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(10),
}
};
}
protected override void LoadComplete()
{
rooms.CollectionChanged += roomsChanged;
roomManager.RoomsUpdated += updateSorting;
rooms.BindTo(roomManager.Rooms);
filter?.BindValueChanged(criteria => Filter(criteria.NewValue));
selectedRoom.BindValueChanged(selection =>
{
updateSelection();
}, true);
}
private void updateSelection() =>
roomFlow.Children.ForEach(r => r.State = r.Room == selectedRoom.Value ? SelectionState.Selected : SelectionState.NotSelected);
public void Filter(FilterCriteria criteria)
{
roomFlow.Children.ForEach(r =>
{
if (criteria == null)
r.MatchingFilter = true;
else
{
bool matchingFilter = true;
matchingFilter &= r.Room.Playlist.Count == 0 || criteria.Ruleset == null || r.Room.Playlist.Any(i => i.Ruleset.Value.Equals(criteria.Ruleset));
if (!string.IsNullOrEmpty(criteria.SearchString))
matchingFilter &= r.FilterTerms.Any(term => term.Contains(criteria.SearchString, StringComparison.InvariantCultureIgnoreCase));
r.MatchingFilter = matchingFilter;
}
});
}
private void roomsChanged(object sender, NotifyCollectionChangedEventArgs args)
{
switch (args.Action)
{
case NotifyCollectionChangedAction.Add:
addRooms(args.NewItems.Cast<Room>());
break;
case NotifyCollectionChangedAction.Remove:
removeRooms(args.OldItems.Cast<Room>());
break;
}
}
private void addRooms(IEnumerable<Room> rooms)
{
foreach (var room in rooms)
{
roomFlow.Add(new DrawableRoom(room));
}
Filter(filter?.Value);
updateSelection();
}
private void removeRooms(IEnumerable<Room> rooms)
{
foreach (var r in rooms)
{
var toRemove = roomFlow.Single(d => d.Room == r);
toRemove.Action = null;
roomFlow.Remove(toRemove);
// selection may have a lease due to being in a sub screen.
if (!selectedRoom.Disabled)
selectedRoom.Value = null;
}
}
private void updateSorting()
{
foreach (var room in roomFlow)
roomFlow.SetLayoutPosition(room, room.Room.Position.Value);
}
protected override bool OnClick(ClickEvent e)
{
if (!selectedRoom.Disabled)
selectedRoom.Value = null;
return base.OnClick(e);
}
#region Key selection logic (shared with BeatmapCarousel)
public bool OnPressed(GlobalAction action)
{
switch (action)
{
case GlobalAction.SelectNext:
beginRepeatSelection(() => selectNext(1), action);
return true;
case GlobalAction.SelectPrevious:
beginRepeatSelection(() => selectNext(-1), action);
return true;
}
return false;
}
public void OnReleased(GlobalAction action)
{
switch (action)
{
case GlobalAction.SelectNext:
case GlobalAction.SelectPrevious:
endRepeatSelection(action);
break;
}
}
private ScheduledDelegate repeatDelegate;
private object lastRepeatSource;
/// <summary>
/// Begin repeating the specified selection action.
/// </summary>
/// <param name="action">The action to perform.</param>
/// <param name="source">The source of the action. Used in conjunction with <see cref="endRepeatSelection"/> to only cancel the correct action (most recently pressed key).</param>
private void beginRepeatSelection(Action action, object source)
{
endRepeatSelection();
lastRepeatSource = source;
repeatDelegate = this.BeginKeyRepeat(Scheduler, action);
}
private void endRepeatSelection(object source = null)
{
// only the most recent source should be able to cancel the current action.
if (source != null && !EqualityComparer<object>.Default.Equals(lastRepeatSource, source))
return;
repeatDelegate?.Cancel();
repeatDelegate = null;
lastRepeatSource = null;
}
private void selectNext(int direction)
{
if (selectedRoom.Disabled)
return;
var visibleRooms = Rooms.AsEnumerable().Where(r => r.IsPresent);
Room room;
if (selectedRoom.Value == null)
room = visibleRooms.FirstOrDefault()?.Room;
else
{
if (direction < 0)
visibleRooms = visibleRooms.Reverse();
room = visibleRooms.SkipWhile(r => r.Room != selectedRoom.Value).Skip(1).FirstOrDefault()?.Room;
}
// we already have a valid selection only change selection if we still have a room to switch to.
if (room != null)
selectedRoom.Value = room;
}
#endregion
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
if (roomManager != null)
roomManager.RoomsUpdated -= updateSorting;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Searches for resources in Assembly manifest, used
** for assembly-based resource lookup.
**
**
===========================================================*/
namespace System.Resources
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Diagnostics;
using Microsoft.Win32;
//
// Note: this type is integral to the construction of exception objects,
// and sometimes this has to be done in low memory situtations (OOM) or
// to create TypeInitializationExceptions due to failure of a static class
// constructor. This type needs to be extremely careful and assume that
// any type it references may have previously failed to construct, so statics
// belonging to that type may not be initialized. FrameworkEventSource.Log
// is one such example.
//
internal class ManifestBasedResourceGroveler : IResourceGroveler
{
private ResourceManager.ResourceManagerMediator _mediator;
public ManifestBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator)
{
// here and below: convert asserts to preconditions where appropriate when we get
// contracts story in place.
Debug.Assert(mediator != null, "mediator shouldn't be null; check caller");
_mediator = mediator;
}
public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary<String, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists, ref StackCrawlMark stackMark)
{
Debug.Assert(culture != null, "culture shouldn't be null; check caller");
Debug.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller");
ResourceSet rs = null;
Stream stream = null;
RuntimeAssembly satellite = null;
// 1. Fixups for ultimate fallbacks
CultureInfo lookForCulture = UltimateFallbackFixup(culture);
// 2. Look for satellite assembly or main assembly, as appropriate
if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
{
// don't bother looking in satellites in this case
satellite = _mediator.MainAssembly;
}
#if RESOURCE_SATELLITE_CONFIG
// If our config file says the satellite isn't here, don't ask for it.
else if (!lookForCulture.HasInvariantCultureName && !_mediator.TryLookingForSatellite(lookForCulture))
{
satellite = null;
}
#endif
else
{
satellite = GetSatelliteAssembly(lookForCulture, ref stackMark);
if (satellite == null)
{
bool raiseException = (culture.HasInvariantCultureName && (_mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite));
// didn't find satellite, give error if necessary
if (raiseException)
{
HandleSatelliteMissing();
}
}
}
// get resource file name we'll search for. Note, be careful if you're moving this statement
// around because lookForCulture may be modified from originally requested culture above.
String fileName = _mediator.GetResourceFileName(lookForCulture);
// 3. If we identified an assembly to search; look in manifest resource stream for resource file
if (satellite != null)
{
// Handle case in here where someone added a callback for assembly load events.
// While no other threads have called into GetResourceSet, our own thread can!
// At that point, we could already have an RS in our hash table, and we don't
// want to add it twice.
lock (localResourceSets)
{
localResourceSets.TryGetValue(culture.Name, out rs);
}
stream = GetManifestResourceStream(satellite, fileName, ref stackMark);
}
// 4a. Found a stream; create a ResourceSet if possible
if (createIfNotExists && stream != null && rs == null)
{
rs = CreateResourceSet(stream, satellite);
}
else if (stream == null && tryParents)
{
// 4b. Didn't find stream; give error if necessary
bool raiseException = culture.HasInvariantCultureName;
if (raiseException)
{
HandleResourceStreamMissing(fileName);
}
}
return rs;
}
private CultureInfo UltimateFallbackFixup(CultureInfo lookForCulture)
{
CultureInfo returnCulture = lookForCulture;
// If our neutral resources were written in this culture AND we know the main assembly
// does NOT contain neutral resources, don't probe for this satellite.
if (lookForCulture.Name == _mediator.NeutralResourcesCulture.Name &&
_mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
{
returnCulture = CultureInfo.InvariantCulture;
}
else if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite)
{
returnCulture = _mediator.NeutralResourcesCulture;
}
return returnCulture;
}
internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, ref UltimateResourceFallbackLocation fallbackLocation)
{
Debug.Assert(a != null, "assembly != null");
string cultureName = null;
short fallback = 0;
if (GetNeutralResourcesLanguageAttribute(((RuntimeAssembly)a).GetNativeHandle(),
JitHelpers.GetStringHandleOnStack(ref cultureName),
out fallback))
{
if ((UltimateResourceFallbackLocation)fallback < UltimateResourceFallbackLocation.MainAssembly || (UltimateResourceFallbackLocation)fallback > UltimateResourceFallbackLocation.Satellite)
{
throw new ArgumentException(SR.Format(SR.Arg_InvalidNeutralResourcesLanguage_FallbackLoc, fallback));
}
fallbackLocation = (UltimateResourceFallbackLocation)fallback;
}
else
{
fallbackLocation = UltimateResourceFallbackLocation.MainAssembly;
return CultureInfo.InvariantCulture;
}
try
{
CultureInfo c = CultureInfo.GetCultureInfo(cultureName);
return c;
}
catch (ArgumentException e)
{ // we should catch ArgumentException only.
// Note we could go into infinite loops if mscorlib's
// NeutralResourcesLanguageAttribute is mangled. If this assert
// fires, please fix the build process for the BCL directory.
if (a == typeof(Object).Assembly)
{
Debug.Fail(System.CoreLib.Name + "'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + cultureName + "\" Exception: " + e);
return CultureInfo.InvariantCulture;
}
throw new ArgumentException(SR.Format(SR.Arg_InvalidNeutralResourcesLanguage_Asm_Culture, a.ToString(), cultureName), e);
}
}
// Constructs a new ResourceSet for a given file name.
// Use the assembly to resolve assembly manifest resource references.
// Note that is can be null, but probably shouldn't be.
// This method could use some refactoring. One thing at a time.
internal ResourceSet CreateResourceSet(Stream store, Assembly assembly)
{
Debug.Assert(store != null, "I need a Stream!");
// Check to see if this is a Stream the ResourceManager understands,
// and check for the correct resource reader type.
if (store.CanSeek && store.Length > 4)
{
long startPos = store.Position;
// not disposing because we want to leave stream open
BinaryReader br = new BinaryReader(store);
// Look for our magic number as a little endian Int32.
int bytes = br.ReadInt32();
if (bytes == ResourceManager.MagicNumber)
{
int resMgrHeaderVersion = br.ReadInt32();
String readerTypeName = null, resSetTypeName = null;
if (resMgrHeaderVersion == ResourceManager.HeaderVersionNumber)
{
br.ReadInt32(); // We don't want the number of bytes to skip.
readerTypeName = System.CoreLib.FixupCoreLibName(br.ReadString());
resSetTypeName = System.CoreLib.FixupCoreLibName(br.ReadString());
}
else if (resMgrHeaderVersion > ResourceManager.HeaderVersionNumber)
{
// Assume that the future ResourceManager headers will
// have two strings for us - the reader type name and
// resource set type name. Read those, then use the num
// bytes to skip field to correct our position.
int numBytesToSkip = br.ReadInt32();
long endPosition = br.BaseStream.Position + numBytesToSkip;
readerTypeName = System.CoreLib.FixupCoreLibName(br.ReadString());
resSetTypeName = System.CoreLib.FixupCoreLibName(br.ReadString());
br.BaseStream.Seek(endPosition, SeekOrigin.Begin);
}
else
{
// resMgrHeaderVersion is older than this ResMgr version.
// We should add in backwards compatibility support here.
throw new NotSupportedException(SR.Format(SR.NotSupported_ObsoleteResourcesFile, _mediator.MainAssembly.GetSimpleName()));
}
store.Position = startPos;
// Perf optimization - Don't use Reflection for our defaults.
// Note there are two different sets of strings here - the
// assembly qualified strings emitted by ResourceWriter, and
// the abbreviated ones emitted by InternalResGen.
if (CanUseDefaultResourceClasses(readerTypeName, resSetTypeName))
{
return new RuntimeResourceSet(store);
}
else
{
// we do not want to use partial binding here.
Type readerType = Type.GetType(readerTypeName, true);
Object[] args = new Object[1];
args[0] = store;
IResourceReader reader = (IResourceReader)Activator.CreateInstance(readerType, args);
Object[] resourceSetArgs = new Object[1];
resourceSetArgs[0] = reader;
Type resSetType;
if (_mediator.UserResourceSet == null)
{
Debug.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here.");
resSetType = Type.GetType(resSetTypeName, true, false);
}
else
resSetType = _mediator.UserResourceSet;
ResourceSet rs = (ResourceSet)Activator.CreateInstance(resSetType,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance,
null,
resourceSetArgs,
null,
null);
return rs;
}
}
else
{
store.Position = startPos;
}
}
if (_mediator.UserResourceSet == null)
{
return new RuntimeResourceSet(store);
}
else
{
Object[] args = new Object[2];
args[0] = store;
args[1] = assembly;
try
{
ResourceSet rs = null;
// Add in a check for a constructor taking in an assembly first.
try
{
rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args);
return rs;
}
catch (MissingMethodException) { }
args = new Object[1];
args[0] = store;
rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args);
return rs;
}
catch (MissingMethodException e)
{
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResMgrBadResSet_Type, _mediator.UserResourceSet.AssemblyQualifiedName), e);
}
}
}
private Stream GetManifestResourceStream(RuntimeAssembly satellite, String fileName, ref StackCrawlMark stackMark)
{
Debug.Assert(satellite != null, "satellite shouldn't be null; check caller");
Debug.Assert(fileName != null, "fileName shouldn't be null; check caller");
// If we're looking in the main assembly AND if the main assembly was the person who
// created the ResourceManager, skip a security check for private manifest resources.
bool canSkipSecurityCheck = (_mediator.MainAssembly == satellite)
&& (_mediator.CallingAssembly == _mediator.MainAssembly);
Stream stream = satellite.GetManifestResourceStream(_mediator.LocationInfo, fileName, canSkipSecurityCheck, ref stackMark);
if (stream == null)
{
stream = CaseInsensitiveManifestResourceStreamLookup(satellite, fileName);
}
return stream;
}
// Looks up a .resources file in the assembly manifest using
// case-insensitive lookup rules. Yes, this is slow. The metadata
// dev lead refuses to make all assembly manifest resource lookups case-insensitive,
// even optionally case-insensitive.
[System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
private Stream CaseInsensitiveManifestResourceStreamLookup(RuntimeAssembly satellite, String name)
{
Debug.Assert(satellite != null, "satellite shouldn't be null; check caller");
Debug.Assert(name != null, "name shouldn't be null; check caller");
StringBuilder sb = new StringBuilder();
if (_mediator.LocationInfo != null)
{
String nameSpace = _mediator.LocationInfo.Namespace;
if (nameSpace != null)
{
sb.Append(nameSpace);
if (name != null)
sb.Append(Type.Delimiter);
}
}
sb.Append(name);
String givenName = sb.ToString();
CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo;
String canonicalName = null;
foreach (String existingName in satellite.GetManifestResourceNames())
{
if (comparer.Compare(existingName, givenName, CompareOptions.IgnoreCase) == 0)
{
if (canonicalName == null)
{
canonicalName = existingName;
}
else
{
throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_MultipleBlobs, givenName, satellite.ToString()));
}
}
}
if (canonicalName == null)
{
return null;
}
// If we're looking in the main assembly AND if the main
// assembly was the person who created the ResourceManager,
// skip a security check for private manifest resources.
bool canSkipSecurityCheck = _mediator.MainAssembly == satellite && _mediator.CallingAssembly == _mediator.MainAssembly;
StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
return satellite.GetManifestResourceStream(canonicalName, ref stackMark, canSkipSecurityCheck);
}
private RuntimeAssembly GetSatelliteAssembly(CultureInfo lookForCulture, ref StackCrawlMark stackMark)
{
if (!_mediator.LookedForSatelliteContractVersion)
{
_mediator.SatelliteContractVersion = _mediator.ObtainSatelliteContractVersion(_mediator.MainAssembly);
_mediator.LookedForSatelliteContractVersion = true;
}
RuntimeAssembly satellite = null;
String satAssemblyName = GetSatelliteAssemblyName();
// Look up the satellite assembly, but don't let problems
// like a partially signed satellite assembly stop us from
// doing fallback and displaying something to the user.
// Yet also somehow log this error for a developer.
try
{
satellite = _mediator.MainAssembly.InternalGetSatelliteAssembly(satAssemblyName, lookForCulture, _mediator.SatelliteContractVersion, false, ref stackMark);
}
// Jun 08: for cases other than ACCESS_DENIED, we'll assert instead of throw to give release builds more opportunity to fallback.
catch (FileLoadException fle)
{
// Ignore cases where the loader gets an access
// denied back from the OS. This showed up for
// href-run exe's at one point.
int hr = fle._HResult;
if (hr != Win32Marshal.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED))
{
Debug.Fail("[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle);
}
}
// Don't throw for zero-length satellite assemblies, for compat with v1
catch (BadImageFormatException bife)
{
Debug.Fail("[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + Environment.NewLine + "Exception: " + bife);
}
return satellite;
}
// Perf optimization - Don't use Reflection for most cases with
// our .resources files. This makes our code run faster and we can
// creating a ResourceReader via Reflection. This would incur
// a security check (since the link-time check on the constructor that
// takes a String is turned into a full demand with a stack walk)
// and causes partially trusted localized apps to fail.
private bool CanUseDefaultResourceClasses(String readerTypeName, String resSetTypeName)
{
Debug.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller");
Debug.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller");
if (_mediator.UserResourceSet != null)
return false;
// Ignore the actual version of the ResourceReader and
// RuntimeResourceSet classes. Let those classes deal with
// versioning themselves.
AssemblyName mscorlib = new AssemblyName(ResourceManager.MscorlibName);
if (readerTypeName != null)
{
if (!ResourceManager.CompareNames(readerTypeName, ResourceManager.ResReaderTypeName, mscorlib))
return false;
}
if (resSetTypeName != null)
{
if (!ResourceManager.CompareNames(resSetTypeName, ResourceManager.ResSetTypeName, mscorlib))
return false;
}
return true;
}
private String GetSatelliteAssemblyName()
{
String satAssemblyName = _mediator.MainAssembly.GetSimpleName();
satAssemblyName += ".resources";
return satAssemblyName;
}
private void HandleSatelliteMissing()
{
String satAssemName = _mediator.MainAssembly.GetSimpleName() + ".resources.dll";
if (_mediator.SatelliteContractVersion != null)
{
satAssemName += ", Version=" + _mediator.SatelliteContractVersion.ToString();
}
AssemblyName an = new AssemblyName();
an.SetPublicKey(_mediator.MainAssembly.GetPublicKey());
byte[] token = an.GetPublicKeyToken();
int iLen = token.Length;
StringBuilder publicKeyTok = new StringBuilder(iLen * 2);
for (int i = 0; i < iLen; i++)
{
publicKeyTok.Append(token[i].ToString("x", CultureInfo.InvariantCulture));
}
satAssemName += ", PublicKeyToken=" + publicKeyTok;
String missingCultureName = _mediator.NeutralResourcesCulture.Name;
if (missingCultureName.Length == 0)
{
missingCultureName = "<invariant>";
}
throw new MissingSatelliteAssemblyException(SR.Format(SR.MissingSatelliteAssembly_Culture_Name, _mediator.NeutralResourcesCulture, satAssemName), missingCultureName);
}
private void HandleResourceStreamMissing(String fileName)
{
// Keep people from bothering me about resources problems
if (_mediator.MainAssembly == typeof(Object).Assembly && _mediator.BaseName.Equals(System.CoreLib.Name))
{
// This would break CultureInfo & all our exceptions.
Debug.Fail("Couldn't get " + System.CoreLib.Name + ResourceManager.ResFileExtension + " from " + System.CoreLib.Name + "'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug.");
// We cannot continue further - simply FailFast.
string mesgFailFast = System.CoreLib.Name + ResourceManager.ResFileExtension + " couldn't be found! Large parts of the BCL won't work!";
System.Environment.FailFast(mesgFailFast);
}
// We really don't think this should happen - we always
// expect the neutral locale's resources to be present.
String resName = String.Empty;
if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null)
resName = _mediator.LocationInfo.Namespace + Type.Delimiter;
resName += fileName;
throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_NoNeutralAsm, resName, _mediator.MainAssembly.GetSimpleName()));
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[System.Security.SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetNeutralResourcesLanguageAttribute(RuntimeAssembly assemblyHandle, StringHandleOnStack cultureName, out short fallbackLocation);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Roslyn.CSharp.Tests
{
public class IntellisenseFacts : AbstractAutoCompleteTestFixture
{
private readonly ILogger _logger;
public IntellisenseFacts(ITestOutputHelper output, SharedOmniSharpHostFixture sharedOmniSharpHostFixture)
: base(output, sharedOmniSharpHostFixture)
{
this._logger = this.LoggerFactory.CreateLogger<IntellisenseFacts>();
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task DisplayText_is_correct_for_property(string filename)
{
const string input =
@"public class Class1 {
public int Foo { get; set; }
public Class1()
{
Foo$$
}
}";
var completions = await FindCompletionsAsync(filename, input, wantSnippet: true);
ContainsCompletions(completions.Select(c => c.DisplayText).Take(1), "Foo");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task DisplayText_is_correct_for_variable(string filename)
{
const string input =
@"public class Class1 {
public Class1()
{
var foo = 1;
foo$$
}
}";
var completions = await FindCompletionsAsync(filename, input, wantSnippet: true);
ContainsCompletions(completions.Select(c => c.DisplayText).Take(1), "foo");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task DisplayText_matches_snippet_for_snippet_response(string filename)
{
const string input =
@"public class Class1 {
public Class1()
{
Foo$$
}
public void Foo(int bar = 1)
{
}
}";
var completions = await FindCompletionsAsync(filename, input, wantSnippet: true);
ContainsCompletions(completions.Select(c => c.DisplayText).Take(2), "Foo()", "Foo(int bar = 1)");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task DisplayText_matches_snippet_for_non_snippet_response(string filename)
{
const string input =
@"public class Class1 {
public Class1()
{
Foo$$
}
public void Foo(int bar = 1)
{
}
}";
var completions = await FindCompletionsAsync(filename, input, wantSnippet: false);
ContainsCompletions(completions.Select(c => c.DisplayText).Take(1), "Foo(int bar = 1)");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_camel_case_completions(string filename)
{
const string input =
@"public class Class1 {
public Class1()
{
System.Guid.tp$$
}
}";
var completions = await FindCompletionsAsync(filename, input);
ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "TryParse");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_sub_sequence_completions(string filename)
{
const string input =
@"public class Class1 {
public Class1()
{
System.Guid.ng$$
}
}";
var completions = await FindCompletionsAsync(filename, input);
ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "NewGuid");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_sub_sequence_completions_without_matching_firstletter(string filename)
{
const string input =
@"public class Class1 {
public Class1()
{
System.Guid.gu$$
}
}";
var completions = await FindCompletionsAsync(filename, input);
ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "NewGuid");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_method_header(string filename)
{
const string input =
@"public class Class1 {
public Class1()
{
System.Guid.ng$$
}
}";
var completions = await FindCompletionsAsync(filename, input);
ContainsCompletions(completions.Select(c => c.MethodHeader).Take(1), "NewGuid()");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_variable_before_class(string filename)
{
const string input =
@"public class MyClass1 {
public MyClass1()
{
var myvar = 1;
my$$
}
}";
var completions = await FindCompletionsAsync(filename, input);
ContainsCompletions(completions.Select(c => c.CompletionText), "myvar", "MyClass1");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_class_before_variable(string filename)
{
const string input =
@"public class MyClass1 {
public MyClass1()
{
var myvar = 1;
My$$
}
}";
var completions = await FindCompletionsAsync(filename, input);
ContainsCompletions(completions.Select(c => c.CompletionText), "MyClass1", "myvar");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_empty_sequence_in_invalid_context(string filename)
{
const string source =
@"public class MyClass1 {
public MyClass1()
{
var x$$
}
}";
var completions = await FindCompletionsAsync(filename, source);
ContainsCompletions(completions.Select(c => c.CompletionText), Array.Empty<string>());
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_attribute_without_attribute_suffix(string filename)
{
const string source =
@"using System;
public class BarAttribute : Attribute {}
[B$$
public class Foo {}";
var completions = await FindCompletionsAsync(filename, source);
ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "Bar");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_members_in_object_initializer_context(string filename)
{
const string source =
@"public class MyClass1 {
public string Foo {get; set;}
}
public class MyClass2 {
public MyClass2()
{
var c = new MyClass1 {
F$$
}
}
";
var completions = await FindCompletionsAsync(filename, source);
ContainsCompletions(completions.Select(c => c.CompletionText), "Foo");
ContainsCompletions(completions.Select(c => c.ReturnType), "string");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_parameter_name_inside_a_method(string filename)
{
const string source =
@"public class MyClass1 {
public void SayHi(string text) {}
}
public class MyClass2 {
public MyClass2()
{
var c = new MyClass1();
c.SayHi(te$$
}
}
";
var completions = await FindCompletionsAsync(filename, source);
ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "text");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_declaration_names(string filename)
{
const string source =
@"
public class MyClass
{
MyClass m$$
}
";
var completions = await FindCompletionsAsync(filename, source);
ContainsCompletions(completions.Select(c => c.CompletionText), "my", "myClass", "My", "MyClass");
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_override_signatures(string filename)
{
const string source =
@"class Foo
{
public virtual void Test(string text) {}
public virtual void Test(string text, string moreText) {}
}
class FooChild : Foo
{
override $$
}
";
var completions = await FindCompletionsAsync(filename, source);
#if NETCOREAPP
ContainsCompletions(completions.Select(c => c.CompletionText), "Equals(object? obj)", "GetHashCode()", "Test(string text)", "Test(string text, string moreText)", "ToString()");
#else
ContainsCompletions(completions.Select(c => c.CompletionText), "Equals(object obj)", "GetHashCode()", "Test(string text)", "Test(string text, string moreText)", "ToString()");
#endif
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Returns_cref_completion(string filename)
{
const string source =
@" /// <summary>
/// A comment. <see cref=""My$$"" /> for more details
/// </summary>
public class MyClass1 {
}
";
var completions = await FindCompletionsAsync(filename, source);
ContainsCompletions(completions.Select(c => c.CompletionText).Take(1), "MyClass1");
}
[Fact]
public async Task Returns_host_object_members_in_csx()
{
const string source =
"Prin$$";
var completions = await FindCompletionsAsync("dummy.csx", source);
ContainsCompletions(completions.Select(c => c.CompletionText), new[] { "Print", "PrintOptions" });
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Is_suggestion_mode_true_for_lambda_expression_position1(string filename)
{
const string source = @"
using System;
class C
{
int CallMe(int i) => 42;
void M(Func<int, int> a) { }
void M()
{
M(c$$
}
}
";
var completions = await FindCompletionsAsync(filename, source);
Assert.True(completions.All(c => c.IsSuggestionMode));
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Is_suggestion_mode_true_for_lambda_expression_position2(string filename)
{
const string source = @"
using System;
class C
{
int CallMe(int i) => 42;
void M()
{
Func<int, int> a = c$$
}
}
";
var completions = await FindCompletionsAsync(filename, source);
Assert.True(completions.All(c => c.IsSuggestionMode));
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Is_suggestion_mode_false_for_normal_position1(string filename)
{
const string source = @"
using System;
class C
{
int CallMe(int i) => 42;
void M(int a) { }
void M()
{
M(c$$
}
}
";
var completions = await FindCompletionsAsync(filename, source);
Assert.True(completions.All(c => !c.IsSuggestionMode));
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Is_suggestion_mode_false_for_normal_position2(string filename)
{
const string source = @"
using System;
class C
{
int CallMe(int i) => 42;
void M()
{
int a = c$$
}
}
";
var completions = await FindCompletionsAsync(filename, source);
Assert.True(completions.All(c => !c.IsSuggestionMode));
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Embedded_language_completion_provider_for_datetime_format(string filename)
{
const string source = @"
using System;
class C
{
void M()
{
var d = DateTime.Now.ToString(""$$""
}
}
";
var completions = await FindCompletionsAsync(filename, source);
Assert.NotEmpty(completions);
var gStandardCompletion = completions.FirstOrDefault(x => x.CompletionText == "G");
Assert.NotNull(gStandardCompletion);
Assert.Equal("general long date/time", gStandardCompletion.DisplayText);
Assert.Contains(@"The ""G"" standard format specifier", gStandardCompletion.Description);
}
[ConditionalTheory(typeof(WindowsOnly), typeof(DesktopRuntimeOnly))]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task Embedded_language_completion_provider_for_regex(string filename)
{
const string source = @"
using System;
using System.Text.RegularExpressions;
class C
{
void M()
{
var r = Regex.Match(""foo"", ""$$""
}
}
";
var completions = await FindCompletionsAsync(filename, source);
Assert.NotEmpty(completions);
var wCompletion = completions.FirstOrDefault(x => x.CompletionText == @"\w");
Assert.NotNull(wCompletion);
Assert.Equal("word character", wCompletion.DisplayText);
Assert.Contains(@"matches any word character", wCompletion.Description);
}
[Fact]
public async Task Scripting_by_default_returns_completions_for_CSharp7_1()
{
const string source =
@"
var number1 = 1;
var number2 = 2;
var tuple = (number1, number2);
tuple.n$$
";
var completions = await FindCompletionsAsync("dummy.csx", source);
ContainsCompletions(completions.Select(c => c.CompletionText), new[] { "number1", "number2" });
}
[Fact]
public async Task Scripting_by_default_returns_completions_for_CSharp7_2()
{
const string source =
@"
public class Foo { private protected int myValue = 0; }
public class Bar : Foo
{
public Bar()
{
var x = myv$$
}
}
";
var completions = await FindCompletionsAsync("dummy.csx", source);
ContainsCompletions(completions.Select(c => c.CompletionText), new[] { "myValue" });
}
[Fact]
public async Task Scripting_by_default_returns_completions_for_CSharp8_0()
{
const string source =
@"
class Point {
public Point(int x, int y) {
PositionX = x;
PositionY = y;
}
public int PositionX { get; }
public int PositionY { get; }
}
Point[] points = { new (1, 2), new (3, 4) };
points[0].Po$$
";
var completions = await FindCompletionsAsync("dummy.csx", source);
ContainsCompletions(completions.Select(c => c.CompletionText), new[] { "PositionX", "PositionY" });
}
private void ContainsCompletions(IEnumerable<string> completions, params string[] expected)
{
if (!completions.SequenceEqual(expected))
{
var builder = new StringBuilder();
builder.AppendLine("Expected");
builder.AppendLine("--------");
foreach (var completion in expected)
{
builder.AppendLine(completion);
}
builder.AppendLine();
builder.AppendLine("Found");
builder.AppendLine("-----");
foreach (var completion in completions)
{
builder.AppendLine(completion);
}
this._logger.LogError(builder.ToString());
}
Assert.Equal(expected, completions.ToArray());
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task TriggeredOnSpaceForObjectCreation(string filename)
{
const string input =
@"public class Class1 {
public M()
{
Class1 c = new $$
}
}";
var completions = await FindCompletionsAsync(filename, input, wantSnippet: true, triggerChar: " ");
Assert.NotEmpty(completions);
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task ReturnsAtleastOnePreselectOnNew(string filename)
{
const string input =
@"public class Class1 {
public M()
{
Class1 c = new $$
}
}";
var completions = await FindCompletionsAsync(filename, input, wantSnippet: true, triggerChar: " ");
Assert.NotEmpty(completions.Where(completion => completion.Preselect == true));
}
[Theory]
[InlineData("dummy.cs")]
[InlineData("dummy.csx")]
public async Task NotTriggeredOnSpaceWithoutObjectCreation(string filename)
{
const string input =
@"public class Class1 {
public M()
{
$$
}
}";
var completions = await FindCompletionsAsync(filename, input, wantSnippet: true, triggerChar: " ");
Assert.Empty(completions);
}
}
}
| |
// 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.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection.PortableExecutable;
namespace System.Reflection.Metadata.Ecma335
{
public sealed class StandaloneDebugMetadataSerializer : MetadataSerializer
{
private const string DebugMetadataVersionString = "PDB v1.0";
public ushort FormatVersion => 0x0100;
private Blob _pdbIdBlob;
private readonly MethodDefinitionHandle _entryPoint;
public Func<IEnumerable<Blob>, BlobContentId> IdProvider { get; }
public StandaloneDebugMetadataSerializer(
MetadataBuilder builder,
ImmutableArray<int> typeSystemRowCounts,
MethodDefinitionHandle entryPoint,
bool isMinimalDelta,
Func<IEnumerable<Blob>, BlobContentId> deterministicIdProvider = null)
: base(builder, CreateSizes(builder, typeSystemRowCounts, isMinimalDelta, isStandaloneDebugMetadata: true), DebugMetadataVersionString)
{
_entryPoint = entryPoint;
IdProvider = deterministicIdProvider ?? BlobContentId.GetTimeBasedProvider();
}
/// <summary>
/// Serialized #Pdb stream.
/// </summary>
protected override void SerializeStandalonePdbStream(BlobBuilder builder)
{
int startPosition = builder.Count;
// the id will be filled in later
_pdbIdBlob = builder.ReserveBytes(MetadataSizes.PdbIdSize);
builder.WriteInt32(_entryPoint.IsNil ? 0 : MetadataTokens.GetToken(_entryPoint));
builder.WriteUInt64(MetadataSizes.ExternalTablesMask);
MetadataWriterUtilities.SerializeRowCounts(builder, MetadataSizes.ExternalRowCounts);
int endPosition = builder.Count;
Debug.Assert(MetadataSizes.CalculateStandalonePdbStreamSize() == endPosition - startPosition);
}
public void SerializeMetadata(BlobBuilder builder, out BlobContentId contentId)
{
SerializeMetadataImpl(builder, methodBodyStreamRva: 0, mappedFieldDataStreamRva: 0);
contentId = IdProvider(builder.GetBlobs());
// fill in the id:
var idWriter = new BlobWriter(_pdbIdBlob);
idWriter.WriteGuid(contentId.Guid);
idWriter.WriteUInt32(contentId.Stamp);
Debug.Assert(idWriter.RemainingBytes == 0);
}
}
public sealed class TypeSystemMetadataSerializer : MetadataSerializer
{
private static readonly ImmutableArray<int> EmptyRowCounts = ImmutableArray.CreateRange(Enumerable.Repeat(0, MetadataTokens.TableCount));
public TypeSystemMetadataSerializer(
MetadataBuilder builder,
string metadataVersion,
bool isMinimalDelta)
: base(builder, CreateSizes(builder, EmptyRowCounts, isMinimalDelta, isStandaloneDebugMetadata: false), metadataVersion)
{
}
protected override void SerializeStandalonePdbStream(BlobBuilder builder)
{
// nop
}
public void SerializeMetadata(BlobBuilder builder, int methodBodyStreamRva, int mappedFieldDataStreamRva)
{
SerializeMetadataImpl(builder, methodBodyStreamRva, mappedFieldDataStreamRva);
}
}
public abstract class MetadataSerializer
{
protected readonly MetadataBuilder _builder;
private readonly MetadataSizes _sizes;
private readonly string _metadataVersion;
public MetadataSerializer(MetadataBuilder builder, MetadataSizes sizes, string metadataVersion)
{
_builder = builder;
_sizes = sizes;
_metadataVersion = metadataVersion;
}
internal static MetadataSizes CreateSizes(MetadataBuilder builder, ImmutableArray<int> externalRowCounts, bool isMinimalDelta, bool isStandaloneDebugMetadata)
{
builder.CompleteHeaps();
return new MetadataSizes(
builder.GetRowCounts(),
externalRowCounts,
builder.GetHeapSizes(),
isMinimalDelta,
isStandaloneDebugMetadata);
}
protected abstract void SerializeStandalonePdbStream(BlobBuilder builder);
public MetadataSizes MetadataSizes => _sizes;
protected void SerializeMetadataImpl(BlobBuilder builder, int methodBodyStreamRva, int mappedFieldDataStreamRva)
{
// header:
SerializeMetadataHeader(builder);
// #Pdb stream
SerializeStandalonePdbStream(builder);
// #~ or #- stream:
_builder.SerializeMetadataTables(builder, _sizes, methodBodyStreamRva, mappedFieldDataStreamRva);
// #Strings, #US, #Guid and #Blob streams:
_builder.WriteHeapsTo(builder);
}
private void SerializeMetadataHeader(BlobBuilder builder)
{
int startOffset = builder.Count;
// signature
builder.WriteUInt32(0x424A5342);
// major version
builder.WriteUInt16(1);
// minor version
builder.WriteUInt16(1);
// reserved
builder.WriteUInt32(0);
// metadata version length
builder.WriteUInt32(MetadataSizes.MetadataVersionPaddedLength);
int n = Math.Min(MetadataSizes.MetadataVersionPaddedLength, _metadataVersion.Length);
for (int i = 0; i < n; i++)
{
builder.WriteByte((byte)_metadataVersion[i]);
}
for (int i = n; i < MetadataSizes.MetadataVersionPaddedLength; i++)
{
builder.WriteByte(0);
}
// reserved
builder.WriteUInt16(0);
// number of streams
builder.WriteUInt16((ushort)(5 + (_sizes.IsMinimalDelta ? 1 : 0) + (_sizes.IsStandaloneDebugMetadata ? 1 : 0)));
// stream headers
int offsetFromStartOfMetadata = _sizes.MetadataHeaderSize;
// emit the #Pdb stream first so that only a single page has to be read in order to find out PDB ID
if (_sizes.IsStandaloneDebugMetadata)
{
SerializeStreamHeader(ref offsetFromStartOfMetadata, _sizes.StandalonePdbStreamSize, "#Pdb", builder);
}
// Spec: Some compilers store metadata in a #- stream, which holds an uncompressed, or non-optimized, representation of metadata tables;
// this includes extra metadata -Ptr tables. Such PE files do not form part of ECMA-335 standard.
//
// Note: EnC delta is stored as uncompressed metadata stream.
SerializeStreamHeader(ref offsetFromStartOfMetadata, _sizes.MetadataTableStreamSize, (_sizes.IsMetadataTableStreamCompressed ? "#~" : "#-"), builder);
SerializeStreamHeader(ref offsetFromStartOfMetadata, _sizes.GetAlignedHeapSize(HeapIndex.String), "#Strings", builder);
SerializeStreamHeader(ref offsetFromStartOfMetadata, _sizes.GetAlignedHeapSize(HeapIndex.UserString), "#US", builder);
SerializeStreamHeader(ref offsetFromStartOfMetadata, _sizes.GetAlignedHeapSize(HeapIndex.Guid), "#GUID", builder);
SerializeStreamHeader(ref offsetFromStartOfMetadata, _sizes.GetAlignedHeapSize(HeapIndex.Blob), "#Blob", builder);
if (_sizes.IsMinimalDelta)
{
SerializeStreamHeader(ref offsetFromStartOfMetadata, 0, "#JTD", builder);
}
int endOffset = builder.Count;
Debug.Assert(endOffset - startOffset == _sizes.MetadataHeaderSize);
}
private static void SerializeStreamHeader(ref int offsetFromStartOfMetadata, int alignedStreamSize, string streamName, BlobBuilder builder)
{
// 4 for the first uint (offset), 4 for the second uint (padded size), length of stream name + 1 for null terminator (then padded)
int sizeOfStreamHeader = MetadataSizes.GetMetadataStreamHeaderSize(streamName);
builder.WriteInt32(offsetFromStartOfMetadata);
builder.WriteInt32(alignedStreamSize);
foreach (char ch in streamName)
{
builder.WriteByte((byte)ch);
}
// After offset, size, and stream name, write 0-bytes until we reach our padded size.
for (uint i = 8 + (uint)streamName.Length; i < sizeOfStreamHeader; i++)
{
builder.WriteByte(0);
}
offsetFromStartOfMetadata += alignedStreamSize;
}
}
}
| |
// CodeContracts
//
// 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.
// File System.Windows.Media.Media3D.Visual3D.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media.Media3D
{
abstract public partial class Visual3D : System.Windows.DependencyObject, System.Windows.Media.Composition.DUCE.IResource, MS.Internal.IVisual3DContainer, System.Windows.Media.Animation.IAnimatable
{
#region Methods and constructors
protected void AddVisual3DChild(Visual3D child)
{
}
public void ApplyAnimationClock(System.Windows.DependencyProperty dp, System.Windows.Media.Animation.AnimationClock clock)
{
}
public void ApplyAnimationClock(System.Windows.DependencyProperty dp, System.Windows.Media.Animation.AnimationClock clock, System.Windows.Media.Animation.HandoffBehavior handoffBehavior)
{
}
public void BeginAnimation(System.Windows.DependencyProperty dp, System.Windows.Media.Animation.AnimationTimeline animation, System.Windows.Media.Animation.HandoffBehavior handoffBehavior)
{
}
public void BeginAnimation(System.Windows.DependencyProperty dp, System.Windows.Media.Animation.AnimationTimeline animation)
{
}
public System.Windows.DependencyObject FindCommonVisualAncestor(System.Windows.DependencyObject otherVisual)
{
return default(System.Windows.DependencyObject);
}
public Object GetAnimationBaseValue(System.Windows.DependencyProperty dp)
{
return default(Object);
}
protected virtual new Visual3D GetVisual3DChild(int index)
{
return default(Visual3D);
}
public bool IsAncestorOf(System.Windows.DependencyObject descendant)
{
return default(bool);
}
public bool IsDescendantOf(System.Windows.DependencyObject ancestor)
{
return default(bool);
}
void MS.Internal.IVisual3DContainer.AddChild(Visual3D child)
{
}
Visual3D MS.Internal.IVisual3DContainer.GetChild(int index)
{
return default(Visual3D);
}
int MS.Internal.IVisual3DContainer.GetChildrenCount()
{
return default(int);
}
void MS.Internal.IVisual3DContainer.RemoveChild(Visual3D child)
{
}
void MS.Internal.IVisual3DContainer.VerifyAPIReadOnly()
{
}
void MS.Internal.IVisual3DContainer.VerifyAPIReadOnly(System.Windows.DependencyObject other)
{
}
void MS.Internal.IVisual3DContainer.VerifyAPIReadWrite()
{
}
void MS.Internal.IVisual3DContainer.VerifyAPIReadWrite(System.Windows.DependencyObject other)
{
}
protected internal virtual new void OnVisualChildrenChanged(System.Windows.DependencyObject visualAdded, System.Windows.DependencyObject visualRemoved)
{
}
protected internal virtual new void OnVisualParentChanged(System.Windows.DependencyObject oldParent)
{
}
protected void RemoveVisual3DChild(Visual3D child)
{
}
int System.Windows.Media.Composition.DUCE.IResource.GetChannelCount()
{
return default(int);
}
public GeneralTransform3D TransformToAncestor(Visual3D ancestor)
{
return default(GeneralTransform3D);
}
public GeneralTransform3DTo2D TransformToAncestor(System.Windows.Media.Visual ancestor)
{
return default(GeneralTransform3DTo2D);
}
public GeneralTransform3D TransformToDescendant(Visual3D descendant)
{
return default(GeneralTransform3D);
}
internal Visual3D()
{
}
#endregion
#region Properties and indexers
public bool HasAnimatedProperties
{
get
{
return default(bool);
}
}
public Transform3D Transform
{
get
{
return default(Transform3D);
}
set
{
}
}
protected virtual new int Visual3DChildrenCount
{
get
{
return default(int);
}
}
protected Model3D Visual3DModel
{
get
{
return default(Model3D);
}
set
{
}
}
#endregion
#region Fields
public readonly static System.Windows.DependencyProperty TransformProperty;
#endregion
}
}
| |
/*
Copyright (c) 2005, Marc Clifton
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 Marc Clifton 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.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Xml;
using Clifton.Tools.Strings;
namespace Clifton.Tools.Xml
{
public delegate void InstantiateClassDlgt(object sender, ClassEventArgs cea);
public delegate void AssignPropertyDlgt(object sender, PropertyEventArgs pea);
public delegate void UnknownPropertyDlgt(object sender, UnknownPropertyEventArgs pea);
public delegate void CustomAssignPropertyDlgt(object sender, CustomPropertyEventArgs pea);
public delegate void AssignEventDlgt(object sender, EventEventArgs eea);
public delegate void SupportInitializeDlgt(object sender, SupportInitializeEventArgs siea);
public delegate void AddToCollectionDlgt(object sender, CollectionEventArgs cea);
public delegate void UseReferenceDlgt(object sender, UseReferenceEventArgs urea);
public delegate void AssignReferenceDlgt(object sender, AssignReferenceEventArgs area);
public delegate void CommentDlgt(object sender, CommentEventArgs cea);
public class HandledEventArgs : EventArgs
{
protected bool handled;
public bool Handled
{
get { return handled; }
set { handled = value; }
}
}
public class ClassEventArgs : HandledEventArgs
{
protected Type t;
protected XmlNode node;
protected object result;
public Type Type
{
get { return t; }
}
public XmlNode Node
{
get { return node; }
}
public object Result
{
get { return result; }
set { result = value; }
}
public ClassEventArgs(Type t, XmlNode node)
{
this.t = t;
this.node = node;
result = null;
handled = false;
}
}
public class PropertyEventArgs : HandledEventArgs
{
protected PropertyInfo pi;
protected object src;
protected object val;
protected string valStr;
public PropertyInfo PropertyInfo
{
get { return pi; }
}
public object Source
{
get { return src; }
}
public object Value
{
get { return val; }
}
public string AsString
{
get { return valStr; }
}
public PropertyEventArgs(PropertyInfo pi, object src, object val, string valStr)
{
this.pi = pi;
this.src = src;
this.val = val;
this.valStr = valStr;
handled = false;
}
}
public class CustomPropertyEventArgs : HandledEventArgs
{
protected PropertyInfo pi;
protected object src;
protected object val;
public PropertyInfo PropertyInfo
{
get { return pi; }
}
public object Source
{
get { return src; }
}
public object Value
{
get { return val; }
}
public CustomPropertyEventArgs(PropertyInfo pi, object src, object val)
{
this.pi = pi;
this.src = src;
this.val = val;
}
}
public class UnknownPropertyEventArgs : HandledEventArgs
{
protected string propertyName;
protected object src;
protected string propertyValue;
public string PropertyName
{
get { return propertyName; }
}
public object Source
{
get { return src; }
}
public string PropertyValue
{
get { return propertyValue; }
}
public UnknownPropertyEventArgs(string pname, object src, string pvalue)
{
this.propertyName = pname;
this.src = src;
this.propertyValue = pvalue;
}
}
public class EventEventArgs : HandledEventArgs
{
protected EventInfo ei;
protected object ret;
protected object sink;
protected string srcName;
protected string methodName;
public EventInfo EventInfo
{
get { return ei; }
}
public object Return
{
get { return ret; }
}
public object Sink
{
get { return sink; }
}
public string SourceName
{
get { return srcName; }
}
public string MethodName
{
get { return methodName; }
}
public EventEventArgs(EventInfo ei, object ret, object sink, string srcName, string methodName)
{
this.ei = ei;
this.ret = ret;
this.sink = sink;
this.srcName = srcName;
this.methodName = methodName;
}
}
public class SupportInitializeEventArgs : HandledEventArgs
{
protected Type t;
protected object obj;
public object Object
{
get { return obj; }
}
public Type Type
{
get { return t; }
}
public SupportInitializeEventArgs(Type t, object obj)
{
this.t = t;
this.obj = obj;
}
}
public class CollectionEventArgs : HandledEventArgs
{
protected PropertyInfo pi;
protected Type instanceType;
protected Type parentType;
public PropertyInfo PropertyInfo
{
get { return pi; }
}
public Type InstanceType
{
get { return instanceType; }
}
public Type ParentType
{
get { return parentType; }
}
public CollectionEventArgs(PropertyInfo pi, Type instanceType, Type parentType)
{
this.pi = pi;
this.instanceType = instanceType;
this.parentType = parentType;
}
}
public class UseReferenceEventArgs : HandledEventArgs
{
protected Type t;
protected string refName;
protected object ret;
public Type Type
{
get { return t; }
}
public string RefName
{
get { return refName; }
}
public object Return
{
get { return ret; }
set { ret = value; }
}
public UseReferenceEventArgs(Type t, string refName)
{
this.t = t;
this.refName = refName;
ret = null;
}
}
public class AssignReferenceEventArgs : HandledEventArgs
{
protected PropertyInfo pi;
protected string refName;
protected object obj;
public PropertyInfo PropertyInfo
{
get { return pi; }
}
public string RefName
{
get { return refName; }
}
public object Object
{
get { return obj; }
}
public AssignReferenceEventArgs(PropertyInfo pi, string refName, object obj)
{
this.pi = pi;
this.refName = refName;
this.obj = obj;
}
}
public class CommentEventArgs
{
protected string comment;
public string Comment
{
get { return comment; }
}
public CommentEventArgs(string comment)
{
this.comment = comment;
}
}
// public interface IMycroXaml
// {
// void Initialize(object parent);
// object ReturnedObject
// {
// get;
// }
// }
public class MycroParser
{
protected List<Tuple<Type, object>> objectsToEndInit;
protected Dictionary<string, object> nsMap;
protected Dictionary<string, object> objectCollection;
protected object eventSink;
protected XmlNode baseNode;
public event InstantiateClassDlgt InstantiateClass;
public event AssignPropertyDlgt AssignProperty;
public event UnknownPropertyDlgt UnknownProperty;
public event CustomAssignPropertyDlgt CustomAssignProperty;
public event AssignEventDlgt AssignEvent;
public event SupportInitializeDlgt BeginInitCheck;
public event SupportInitializeDlgt EndInitCheck;
public event EventHandler EndChildProcessing;
public event AddToCollectionDlgt AddToCollection;
public event UseReferenceDlgt UseReference;
public event AssignReferenceDlgt AssignReference;
public event CommentDlgt Comment;
public Dictionary<string, object> NamespaceMap
{
get { return nsMap; }
}
public Dictionary<string, object> ObjectCollection
{
get { return objectCollection; }
}
public MycroParser()
{
objectCollection = new Dictionary<string, object>();
objectsToEndInit = new List<Tuple<Type, object>>();
}
public void Load(XmlDocument doc, string objectName, object eventSink)
{
this.eventSink = eventSink;
XmlNode node;
if (objectName != null)
{
node = doc.SelectSingleNode("//MycroXaml[@Name='" + objectName + "']");
Trace.Assert(node != null, "Couldn't find MycroXaml element " + objectName);
Trace.Assert(node.ChildNodes.Count <= 1, "Only one child of the root is allowed.");
// The last valid node instantiated is returned.
// The xml root should only have one child.
ProcessNamespaces(node);
if (node.ChildNodes.Count == 1)
{
baseNode = node.ChildNodes[0];
}
}
else
{
node = doc.DocumentElement;
baseNode = node;
ProcessNamespaces(node);
}
}
public object Process()
{
object ret = null;
if (baseNode != null)
{
Type t;
ret = ProcessNode(baseNode, null, out t);
}
DoEndInit();
return ret;
}
public bool HasInstance(string name)
{
return objectCollection.ContainsKey(name);
}
public object GetInstance(string name)
{
Trace.Assert(objectCollection.ContainsKey(name), "The object collection does not have an entry for " + name);
return objectCollection[name];
}
public void AddInstance(string name, object obj)
{
// We don't care if we overwrite an existing object.
objectCollection[name] = obj;
}
protected void DoEndInit()
{
foreach (var endInit in objectsToEndInit)
{
OnEndInitCheck(endInit.Item1, endInit.Item2);
}
}
protected void ProcessNamespaces(XmlNode node)
{
nsMap = new Dictionary<string, object>();
foreach (XmlAttribute attr in node.Attributes)
{
if (attr.Prefix == "xmlns")
{
nsMap[attr.LocalName] = attr.Value;
}
}
}
protected virtual object OnInstantiateClass(Type t, XmlNode node)
{
object ret = null;
ClassEventArgs args = new ClassEventArgs(t, node);
if (InstantiateClass != null)
{
InstantiateClass(this, args);
ret = args.Result;
}
if (!args.Handled)
{
ret = Activator.CreateInstance(t);
}
return ret;
}
protected virtual void OnAssignProperty(PropertyInfo pi, object ret, object val, string origVal)
{
PropertyEventArgs args = new PropertyEventArgs(pi, ret, val, origVal);
if (AssignProperty != null)
{
AssignProperty(this, args);
}
if (!args.Handled)
{
pi.SetValue(ret, val, null);
}
}
protected virtual bool OnCustomAssignProperty(PropertyInfo pi, object ret, object val)
{
CustomPropertyEventArgs args = new CustomPropertyEventArgs(pi, ret, val);
if (CustomAssignProperty != null)
{
CustomAssignProperty(this, args);
}
return args.Handled;
}
protected virtual bool OnUnknownProperty(string pname, object ret, string pvalue)
{
UnknownPropertyEventArgs args = new UnknownPropertyEventArgs(pname, ret, pvalue);
if (UnknownProperty != null)
{
UnknownProperty(this, args);
}
return args.Handled;
}
protected virtual void OnAssignEvent(EventInfo ei, object ret, object sink, string srcName, string methodName)
{
EventEventArgs args = new EventEventArgs(ei, ret, sink, srcName, methodName);
if (AssignEvent != null)
{
AssignEvent(this, args);
}
if (!args.Handled)
{
Delegate dlgt = null;
try
{
MethodInfo mi = sink.GetType().GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
dlgt = Delegate.CreateDelegate(ei.EventHandlerType, sink, mi.Name);
}
catch (Exception e)
{
Trace.Fail("Couldn't create a delegate for the event " + srcName + "." + methodName + ":\r\n" + e.Message);
}
try
{
ei.AddEventHandler(ret, dlgt);
}
catch (Exception e)
{
Trace.Fail("Binding to event " + ei.Name + " failed: " + e.Message);
}
}
}
protected virtual void OnBeginInitCheck(Type t, object obj)
{
SupportInitializeEventArgs args = new SupportInitializeEventArgs(t, obj);
if (BeginInitCheck != null)
{
BeginInitCheck(this, args);
}
if (!args.Handled)
{
// support the ISupportInitialize interface
if (obj is ISupportInitialize)
{
((ISupportInitialize)obj).BeginInit();
}
}
}
protected virtual void OnEndInitCheck(Type t, object obj)
{
SupportInitializeEventArgs args = new SupportInitializeEventArgs(t, obj);
if (EndInitCheck != null)
{
EndInitCheck(this, args);
}
if (!args.Handled)
{
// support the ISupportInitialize interface
if (obj is ISupportInitialize)
{
((ISupportInitialize)obj).EndInit();
}
}
}
protected virtual void OnEndChildProcessing()
{
if (EndChildProcessing != null)
{
EndChildProcessing(this, EventArgs.Empty);
}
}
protected virtual object OnUseReference(Type t, string refVar)
{
object ret = null;
UseReferenceEventArgs args = new UseReferenceEventArgs(t, refVar);
if (UseReference != null)
{
UseReference(this, args);
}
if (!args.Handled)
{
if (HasInstance(refVar))
{
ret = GetInstance(refVar);
}
}
else
{
ret = args.Return;
}
return ret;
}
protected virtual void OnAssignReference(PropertyInfo pi, string refName, object obj)
{
AssignReferenceEventArgs args = new AssignReferenceEventArgs(pi, refName, obj);
if (AssignReference != null)
{
AssignReference(this, args);
}
if (!args.Handled)
{
object val = GetInstance(refName);
try
{
pi.SetValue(obj, val, null);
}
catch (Exception e)
{
if (!OnCustomAssignProperty(pi, obj, val))
{
Trace.Fail("Couldn't set property " + pi.Name + " to an instance of " + refName + ":\r\n" + e.Message);
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="pi">The PropertyInfo of the collection property.</param>
/// <param name="propObject">The instance of the collection.</param>
/// <param name="obj">The instance to add to the collection.</param>
/// <param name="t">The instance type (being added to the collection).</param>
/// <param name="parentType">The parent type.</param>
/// <param name="parent">The parent instance.</param>
protected virtual void OnAddToCollection(PropertyInfo pi, object propObject, object obj, Type t, Type parentType, object parent)
{
CollectionEventArgs args = new CollectionEventArgs(pi, t, parentType);
if (AddToCollection != null)
{
AddToCollection(this, args);
}
if (!args.Handled)
{
// A null return is valid in cases where a class implementing the IMicroXaml interface
// might want to take care of managing the instance it creates itself. See DataBinding
if (obj != null)
{
// support for ICollection and IList objects.
// If the object is a collection or list, then even if it's writeable, treat as a list.
if ( (!pi.CanWrite) || (propObject is ICollection) || (propObject is IList) )
{
if (propObject is ICollection)
{
MethodInfo mi = propObject.GetType().GetMethod("Add", new Type[] { obj.GetType() });
if (mi != null)
{
try
{
mi.Invoke(propObject, new object[] { obj });
}
catch (Exception e)
{
Trace.Fail("Adding to collection failed:\r\n" + e.Message);
}
}
else if (propObject is IList)
{
try
{
((IList)propObject).Add(obj);
}
catch (Exception e)
{
Trace.Fail("List/Collection add failed:\r\n" + e.Message);
}
}
}
else
{
Trace.Fail("Unsupported read-only property: " + pi.Name);
}
}
else
{
// direct assignment if not a collection
try
{
pi.SetValue(parent, obj, null);
}
catch (Exception e)
{
Trace.Fail("Property setter for " + pi.Name + " failed:\r\n" + e.Message);
}
}
}
}
}
protected virtual void OnComment(string text)
{
if (Comment != null)
{
CommentEventArgs args = new CommentEventArgs(text);
Comment(this, args);
}
}
protected object ProcessNode(XmlNode node, object parent, out Type t)
{
t = null;
object ret = null;
// Special case for String objects
if (node.LocalName == "String")
{
return node.InnerText;
}
bool useRef = false;
int attributeCount = 0;
string ns = node.Prefix;
string cname = node.LocalName;
Trace.Assert(nsMap.ContainsKey(ns), "Namespace '" + ns + "' has not been declared.");
string asyName = (string)nsMap[ns];
string qname = StringHelpers.LeftOf(asyName, ',') + "." + cname + ", " + StringHelpers.RightOf(asyName, ',');
t = Type.GetType(qname, false);
Trace.Assert(t != null, "Type " + qname + " could not be determined.");
// Do ref:Name check here and call OnReferenceInstance if appropriate.
if (node.Attributes != null)
{
attributeCount = node.Attributes.Count;
if (attributeCount > 0)
{
// We're making a blatant assumption that the ref:Name is going to be
// the first attribute in the node.
if (node.Attributes[0].Name == "ref:Name")
{
string refVar = node.Attributes[0].Value;
ret = OnUseReference(t, refVar);
useRef = true;
}
}
}
if (!useRef)
{
// instantiate the class
try
{
ret = OnInstantiateClass(t, node);
AddToInstanceCollection(node, ret); // Allows for reference of the node by any child nodes.
}
catch (Exception e)
{
while (e.InnerException != null)
{
e = e.InnerException;
}
Trace.Fail("Type " + qname + " could not be instantiated:\r\n" + e.Message);
}
}
// Optimization, to remove SuspendLayout followed by ResumeLayout when no
// properties are being set (the ref only has a Name attribute).
// If the referenced object has additional properties that have been set (attributeCount > 1, as the first attribute is the ref:),
// then we call EndInit again because the object might need to do initialization with the attribute values that have now been assigned.
// Unfortunately, we leave it up to the object to determine how to handle potential multiple inits!
if (!useRef)
{
OnBeginInitCheck(t, ret);
}
// If the instance implements the IMicroXaml interface, then it may need
// access to the parser.
// if (ret is IMycroXaml)
// {
// ((IMycroXaml)ret).Initialize(parent);
// }
// implements the class-property-class model
ProcessChildProperties(node, ret, t);
OnEndChildProcessing();
string refName = ProcessAttributes(node, ret, t);
// Optimization, to remove SuspendLayout followed by ResumeLayout when no
// properties are being set (the ref only has a Name attribute).
// If the referenced object has additional properties that have been set (attributeCount > 1, as the first attribute is the ref:),
// then we call EndInit again because the object might need to do initialization with the attribute values that have now been assigned.
// Unfortunately, we leave it up to the object to determine how to handle potential multiple inits!
if (!useRef)
{
objectsToEndInit.Add(new Tuple<Type, object>(t, ret));
}
// If the instance implements the IMicroXaml interface, then it has the option
// to return an object that replaces the instance created by the parser.
// if (ret is IMycroXaml)
// {
// ret=((IMycroXaml)ret).ReturnedObject;
//
// if ( (ret != null) && (refName != String.Empty) )
// {
// AddInstance(refName, ret);
// }
// }
return ret;
}
protected void ProcessChildProperties(XmlNode node, object parent, Type parentType)
{
Type t;
object obj;
// children of a class must always be properties
foreach (XmlNode child in node.ChildNodes)
{
if (child is XmlComment)
{
OnComment(child.Value);
}
else
if (child is XmlElement)
{
string pname = child.LocalName;
PropertyInfo pi = parentType.GetProperty(pname); //, BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.NonPublic);
if ((pi == null)) // || (node.Prefix != child.Prefix))
{
// Special case--we're going to assume that the child is a class instance
// not associated with the parent object
ProcessNode(child, null, out t);
continue;
}
// a property can only have one child node unless it's a collection
foreach (XmlNode grandChild in child.ChildNodes)
{
if (grandChild is XmlComment)
{
OnComment(grandChild.Value);
}
else
if (grandChild is XmlElement)
{
object propObject = null;
if (parent != null)
{
propObject = pi.GetValue(parent, null);
if (propObject == null)
{
// The grandChild type is a property of the child, which is itself a property/instance of the parent.
// Instantiate the child and assign it to the parent, then process the grandchild as a collection property.
// TODO: This could be iterated more levels!
obj = ProcessNode(child, null, out t);
pi.SetValue(parent, obj, null);
continue;
}
}
obj = ProcessNode(grandChild, propObject, out t);
OnAddToCollection(pi, propObject, obj, t, parentType, parent);
}
}
}
}
}
protected void AddToInstanceCollection(XmlNode node, object ret)
{
foreach (XmlAttribute attr in node.Attributes)
{
string pname = attr.Name;
string pvalue = attr.Value;
// auto-add to our object collection
if ((pname == "Name") || (pname == "def:Name"))
{
AddInstance(pvalue, ret);
}
}
}
protected string ProcessAttributes(XmlNode node, object ret, Type t)
{
string refName = String.Empty;
// process attributes
foreach (XmlAttribute attr in node.Attributes)
{
string pname = attr.Name;
string pvalue = attr.Value;
// it's either a property or an event. Allow assignment to protected / private properties.
PropertyInfo pi = t.GetProperty(pname, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
EventInfo ei = t.GetEvent(pname);
if (pi != null)
{
// it's a property!
if (pvalue.StartsWith("{") && pvalue.EndsWith("}"))
{
// And the value is a reference to an instance!
// Get the referenced object. Late binding is not supported!
OnAssignReference(pi, StringHelpers.Between(pvalue, '{', '}'), ret);
}
else
{
// it's string, so use a type converter.
if (pi.PropertyType.FullName == "System.Object")
{
OnAssignProperty(pi, ret, pvalue, pvalue);
}
else
{
TypeConverter tc = TypeDescriptor.GetConverter(pi.PropertyType);
if (tc.CanConvertFrom(typeof(string)))
{
object val = tc.ConvertFrom(pvalue);
try
{
OnAssignProperty(pi, ret, val, pvalue);
}
catch (Exception e)
{
Trace.Fail("Property setter for " + pname + " failed:\r\n" + e.Message);
}
}
else
{
if (!OnCustomAssignProperty(pi, ret, pvalue))
{
Trace.Fail("Property setter for " + pname + " cannot be converted to property type " + pi.PropertyType.FullName + ".");
}
}
}
}
// auto-add to our object collection
if ((pname == "Name") || (pname == "def:Name"))
{
refName = pvalue;
// AddInstance(pvalue, ret);
}
}
else if (ei != null)
{
// it's an event!
string src = pvalue;
string methodName = String.Empty;
object sink = eventSink;
if ((StringHelpers.BeginsWith(src, '{')) && (StringHelpers.EndsWith(src, '}')))
{
src = StringHelpers.Between(src, '{', '}');
}
if (src.IndexOf('.') != -1)
{
string[] handler = src.Split('.');
src = handler[0];
methodName = handler[1];
sink = GetInstance(src);
}
else
{
methodName = src;
}
OnAssignEvent(ei, ret, sink, src, methodName);
}
else
{
// auto-add to our object collection
if ((pname == "Name") || (pname == "def:Name"))
{
refName = pvalue;
// AddInstance(pvalue, ret);
}
else if (pname == "ref:Name")
{
// Do nothing.
}
else
{
if (!OnUnknownProperty(pname, ret, pvalue))
{
// who knows what it is???
Trace.Fail("Failed acquiring property information for '" + pname + "' with value '"+pvalue+"'");
}
}
}
}
return refName;
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.GoToDefinition;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Undo;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices
{
[Export(typeof(VisualStudioWorkspace))]
[Export(typeof(VisualStudioWorkspaceImpl))]
internal class RoslynVisualStudioWorkspace : VisualStudioWorkspaceImpl
{
private readonly IEnumerable<Lazy<IStreamingFindUsagesPresenter>> _streamingPresenters;
private readonly IEnumerable<Lazy<IDefinitionsAndReferencesPresenter>> _referencedSymbolsPresenters;
[ImportingConstructor]
private RoslynVisualStudioWorkspace(
SVsServiceProvider serviceProvider,
SaveEventsService saveEventsService,
[ImportMany] IEnumerable<Lazy<IStreamingFindUsagesPresenter>> streamingPresenters,
[ImportMany] IEnumerable<Lazy<IDefinitionsAndReferencesPresenter>> referencedSymbolsPresenters,
[ImportMany] IEnumerable<IDocumentOptionsProviderFactory> documentOptionsProviderFactories)
: base(
serviceProvider,
backgroundWork: WorkspaceBackgroundWork.ParseAndCompile)
{
PrimaryWorkspace.Register(this);
InitializeStandardVisualStudioWorkspace(serviceProvider, saveEventsService);
_streamingPresenters = streamingPresenters;
_referencedSymbolsPresenters = referencedSymbolsPresenters;
foreach (var providerFactory in documentOptionsProviderFactories)
{
Services.GetRequiredService<IOptionService>().RegisterDocumentOptionsProvider(providerFactory.Create(this));
}
}
public override EnvDTE.FileCodeModel GetFileCodeModel(DocumentId documentId)
{
if (documentId == null)
{
throw new ArgumentNullException(nameof(documentId));
}
var project = ProjectTracker.GetProject(documentId.ProjectId);
if (project == null)
{
throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId));
}
var document = project.GetDocumentOrAdditionalDocument(documentId);
if (document == null)
{
throw new ArgumentException(ServicesVSResources.The_given_DocumentId_did_not_come_from_the_Visual_Studio_workspace, nameof(documentId));
}
var provider = project as IProjectCodeModelProvider;
if (provider != null)
{
var projectCodeModel = provider.ProjectCodeModel;
if (projectCodeModel.CanCreateFileCodeModelThroughProject(document.FilePath))
{
return (EnvDTE.FileCodeModel)projectCodeModel.CreateFileCodeModelThroughProject(document.FilePath);
}
}
return null;
}
internal override bool RenameFileCodeModelInstance(DocumentId documentId, string newFilePath)
{
if (documentId == null)
{
return false;
}
var project = ProjectTracker.GetProject(documentId.ProjectId);
if (project == null)
{
return false;
}
var document = project.GetDocumentOrAdditionalDocument(documentId);
if (document == null)
{
return false;
}
var codeModelProvider = project as IProjectCodeModelProvider;
if (codeModelProvider == null)
{
return false;
}
var codeModelCache = codeModelProvider.ProjectCodeModel.GetCodeModelCache();
if (codeModelCache == null)
{
return false;
}
codeModelCache.OnSourceFileRenaming(document.FilePath, newFilePath);
return true;
}
internal override IInvisibleEditor OpenInvisibleEditor(DocumentId documentId)
{
var hostDocument = GetHostDocument(documentId);
return OpenInvisibleEditor(hostDocument);
}
internal override IInvisibleEditor OpenInvisibleEditor(IVisualStudioHostDocument hostDocument)
{
var globalUndoService = this.Services.GetService<IGlobalUndoService>();
var needsUndoDisabled = false;
// Do not save the file if is open and there is not a global undo transaction.
var needsSave = globalUndoService.IsGlobalTransactionOpen(this) || !hostDocument.IsOpen;
if (needsSave)
{
if (this.CurrentSolution.ContainsDocument(hostDocument.Id))
{
// Disable undo on generated documents
needsUndoDisabled = this.CurrentSolution.GetDocument(hostDocument.Id).IsGeneratedCode();
}
else
{
// Enable undo on "additional documents" or if no document can be found.
needsUndoDisabled = false;
}
}
return new InvisibleEditor(ServiceProvider, hostDocument.FilePath, needsSave, needsUndoDisabled);
}
private static bool TryResolveSymbol(ISymbol symbol, Project project, CancellationToken cancellationToken, out ISymbol resolvedSymbol, out Project resolvedProject)
{
resolvedSymbol = null;
resolvedProject = null;
var currentProject = project.Solution.Workspace.CurrentSolution.GetProject(project.Id);
if (currentProject == null)
{
return false;
}
var originalCompilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var symbolId = SymbolKey.Create(symbol, cancellationToken);
var currentCompilation = currentProject.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var symbolInfo = symbolId.Resolve(currentCompilation, cancellationToken: cancellationToken);
if (symbolInfo.Symbol == null)
{
return false;
}
resolvedSymbol = symbolInfo.Symbol;
resolvedProject = currentProject;
return true;
}
public override bool TryGoToDefinition(
ISymbol symbol, Project project, CancellationToken cancellationToken)
{
if (!_streamingPresenters.Any())
{
return false;
}
if (!TryResolveSymbol(symbol, project, cancellationToken,
out var searchSymbol, out var searchProject))
{
return false;
}
return GoToDefinitionHelpers.TryGoToDefinition(
searchSymbol, searchProject,
_streamingPresenters, cancellationToken);
}
public override bool TryFindAllReferences(ISymbol symbol, Project project, CancellationToken cancellationToken)
{
if (!_referencedSymbolsPresenters.Any())
{
return false;
}
if (!TryResolveSymbol(symbol, project, cancellationToken, out var searchSymbol, out var searchProject))
{
return false;
}
var searchSolution = searchProject.Solution;
var result = SymbolFinder
.FindReferencesAsync(searchSymbol, searchSolution, cancellationToken)
.WaitAndGetResult(cancellationToken).ToList();
if (result != null)
{
DisplayReferencedSymbols(searchSolution, result);
return true;
}
return false;
}
public override void DisplayReferencedSymbols(
Solution solution, IEnumerable<ReferencedSymbol> referencedSymbols)
{
var service = this.Services.GetService<IDefinitionsAndReferencesFactory>();
var definitionsAndReferences = service.CreateDefinitionsAndReferences(
solution, referencedSymbols, includeHiddenLocations: false);
foreach (var presenter in _referencedSymbolsPresenters)
{
presenter.Value.DisplayResult(definitionsAndReferences);
return;
}
}
internal override object GetBrowseObject(SymbolListItem symbolListItem)
{
var compilation = symbolListItem.GetCompilation(this);
if (compilation == null)
{
return null;
}
var symbol = symbolListItem.ResolveSymbol(compilation);
var sourceLocation = symbol.Locations.Where(l => l.IsInSource).FirstOrDefault();
if (sourceLocation == null)
{
return null;
}
var projectId = symbolListItem.ProjectId;
if (projectId == null)
{
return null;
}
var project = this.CurrentSolution.GetProject(projectId);
if (project == null)
{
return null;
}
var codeModelService = project.LanguageServices.GetService<ICodeModelService>();
if (codeModelService == null)
{
return null;
}
var tree = sourceLocation.SourceTree;
var document = project.GetDocument(tree);
var vsFileCodeModel = this.GetFileCodeModel(document.Id);
var fileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(vsFileCodeModel);
if (fileCodeModel != null)
{
var syntaxNode = tree.GetRoot().FindNode(sourceLocation.SourceSpan);
while (syntaxNode != null)
{
if (!codeModelService.TryGetNodeKey(syntaxNode).IsEmpty)
{
break;
}
syntaxNode = syntaxNode.Parent;
}
if (syntaxNode != null)
{
var codeElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(syntaxNode);
if (codeElement != null)
{
return codeElement;
}
}
}
return null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace AutoMapperSample.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//! \file ImageTLG.cs
//! \date Thu Jul 17 21:31:39 2014
//! \brief KiriKiri TLG image implementation.
//---------------------------------------------------------------------------
// TLG5/6 decoder
// Copyright (C) 2000-2005 W.Dee <[email protected]> and contributors
//
// C# port by morkt
//
using System;
using System.IO;
using System.ComponentModel.Composition;
using System.Windows.Media;
using GameRes.Utility;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace GameRes.Formats.KiriKiri
{
internal class TlgMetaData : ImageMetaData
{
public int Version;
public int DataOffset;
}
[Export(typeof(ImageFormat))]
public class TlgFormat : ImageFormat
{
public override string Tag { get { return "TLG"; } }
public override string Description { get { return "KiriKiri game engine image format"; } }
public override uint Signature { get { return 0x30474c54; } } // "TLG0"
public TlgFormat ()
{
Extensions = new string[] { "tlg", "tlg5", "tlg6" };
Signatures = new uint[] { 0x30474C54, 0x35474C54, 0x36474C54, 0x35474CAB, 0x584D4B4A };
}
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
var header = stream.ReadHeader (0x26);
int offset = 0xf;
if (!header.AsciiEqual ("TLG0.0\x00sds\x1a"))
offset = 0;
int version;
if (!header.AsciiEqual (offset+6, "\x00raw\x1a"))
return null;
if (0xAB == header[offset])
header[offset] = (byte)'T';
if (header.AsciiEqual (offset, "TLG6.0"))
version = 6;
else if (header.AsciiEqual (offset, "TLG5.0"))
version = 5;
else if (header.AsciiEqual (offset, "XXXYYY"))
{
version = 5;
header[offset+0x0C] ^= 0xAB;
header[offset+0x10] ^= 0xAC;
}
else if (header.AsciiEqual (offset, "XXXZZZ"))
{
version = 6;
header[offset+0x0F] ^= 0xAB;
header[offset+0x13] ^= 0xAC;
}
else if (header.AsciiEqual (offset, "JKMXE8"))
{
version = 5;
header[offset+0x0C] ^= 0x1A;
header[offset+0x10] ^= 0x1C;
}
else
return null;
int colors = header[offset+11];
if (6 == version)
{
if (1 != colors && 4 != colors && 3 != colors)
return null;
if (header[offset+12] != 0 || header[offset+13] != 0 || header[offset+14] != 0)
return null;
offset += 15;
}
else
{
if (4 != colors && 3 != colors)
return null;
offset += 12;
}
return new TlgMetaData
{
Width = header.ToUInt32 (offset),
Height = header.ToUInt32 (offset+4),
BPP = colors*8,
Version = version,
DataOffset = offset+8,
};
}
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var meta = (TlgMetaData)info;
var image = ReadTlg (file, meta);
int tail_size = (int)Math.Min (file.Length - file.Position, 512);
if (tail_size > 8)
{
var tail = file.ReadBytes (tail_size);
try
{
var blended_image = ApplyTags (image, meta, tail);
if (null != blended_image)
return blended_image;
}
catch (FileNotFoundException X)
{
Trace.WriteLine (string.Format ("{0}: {1}", X.Message, X.FileName), "[TlgFormat.Read]");
}
catch (Exception X)
{
Trace.WriteLine (X.Message, "[TlgFormat.Read]");
}
}
PixelFormat format = 32 == meta.BPP ? PixelFormats.Bgra32 : PixelFormats.Bgr32;
return ImageData.Create (meta, format, null, image, (int)meta.Width * 4);
}
public override void Write (Stream file, ImageData image)
{
throw new NotImplementedException ("TlgFormat.Write not implemented");
}
byte[] ReadTlg (IBinaryStream src, TlgMetaData info)
{
src.Position = info.DataOffset;
if (6 == info.Version)
return ReadV6 (src, info);
else
return ReadV5 (src, info);
}
ImageData ApplyTags (byte[] image, TlgMetaData meta, byte[] tail)
{
int i = tail.Length - 8;
while (i >= 0)
{
if ('s' == tail[i+3] && 'g' == tail[i+2] && 'a' == tail[i+1] && 't' == tail[i])
break;
--i;
}
if (i < 0)
return null;
var tags = new TagsParser (tail, i+4);
if (!tags.Parse())
return null;
var base_name = tags.GetString (1);
meta.OffsetX = tags.GetInt (2) & 0xFFFF;
meta.OffsetY = tags.GetInt (3) & 0xFFFF;
if (string.IsNullOrEmpty (base_name))
return null;
int method = 1;
if (tags.HasKey (4))
method = tags.GetInt (4);
base_name = VFS.CombinePath (VFS.GetDirectoryName (meta.FileName), base_name);
if (base_name == meta.FileName)
return null;
TlgMetaData base_info;
byte[] base_image;
using (var base_file = VFS.OpenBinaryStream (base_name))
{
base_info = ReadMetaData (base_file) as TlgMetaData;
if (null == base_info)
return null;
base_info.FileName = base_name;
base_image = ReadTlg (base_file, base_info);
}
var pixels = BlendImage (base_image, base_info, image, meta, method);
PixelFormat format = 32 == base_info.BPP ? PixelFormats.Bgra32 : PixelFormats.Bgr32;
return ImageData.Create (base_info, format, null, pixels, (int)base_info.Width*4);
}
byte[] BlendImage (byte[] base_image, ImageMetaData base_info, byte[] overlay, ImageMetaData overlay_info, int method)
{
int dst_stride = (int)base_info.Width * 4;
int src_stride = (int)overlay_info.Width * 4;
int dst = overlay_info.OffsetY * dst_stride + overlay_info.OffsetX * 4;
int src = 0;
int gap = dst_stride - src_stride;
for (uint y = 0; y < overlay_info.Height; ++y)
{
for (uint x = 0; x < overlay_info.Width; ++x)
{
byte src_alpha = overlay[src+3];
if (2 == method)
{
base_image[dst] ^= overlay[src];
base_image[dst+1] ^= overlay[src+1];
base_image[dst+2] ^= overlay[src+2];
base_image[dst+3] ^= src_alpha;
}
else if (src_alpha != 0)
{
if (0xFF == src_alpha || 0 == base_image[dst+3])
{
base_image[dst] = overlay[src];
base_image[dst+1] = overlay[src+1];
base_image[dst+2] = overlay[src+2];
base_image[dst+3] = src_alpha;
}
else
{
// FIXME this blending algorithm is oversimplified.
base_image[dst+0] = (byte)((overlay[src+0] * src_alpha
+ base_image[dst+0] * (0xFF - src_alpha)) / 0xFF);
base_image[dst+1] = (byte)((overlay[src+1] * src_alpha
+ base_image[dst+1] * (0xFF - src_alpha)) / 0xFF);
base_image[dst+2] = (byte)((overlay[src+2] * src_alpha
+ base_image[dst+2] * (0xFF - src_alpha)) / 0xFF);
base_image[dst+3] = (byte)Math.Max (src_alpha, base_image[dst+3]);
}
}
dst += 4;
src += 4;
}
dst += gap;
}
return base_image;
}
const int TVP_TLG6_H_BLOCK_SIZE = 8;
const int TVP_TLG6_W_BLOCK_SIZE = 8;
const int TVP_TLG6_GOLOMB_N_COUNT = 4;
const int TVP_TLG6_LeadingZeroTable_BITS = 12;
const int TVP_TLG6_LeadingZeroTable_SIZE = (1<<TVP_TLG6_LeadingZeroTable_BITS);
byte[] ReadV6 (IBinaryStream src, TlgMetaData info)
{
int width = (int)info.Width;
int height = (int)info.Height;
int colors = info.BPP / 8;
int max_bit_length = src.ReadInt32();
int x_block_count = ((width - 1)/ TVP_TLG6_W_BLOCK_SIZE) + 1;
int y_block_count = ((height - 1)/ TVP_TLG6_H_BLOCK_SIZE) + 1;
int main_count = width / TVP_TLG6_W_BLOCK_SIZE;
int fraction = width - main_count * TVP_TLG6_W_BLOCK_SIZE;
var image_bits = new uint[height * width];
var bit_pool = new byte[max_bit_length / 8 + 5];
var pixelbuf = new uint[width * TVP_TLG6_H_BLOCK_SIZE + 1];
var filter_types = new byte[x_block_count * y_block_count];
var zeroline = new uint[width];
var LZSS_text = new byte[4096];
// initialize zero line (virtual y=-1 line)
uint zerocolor = 3 == colors ? 0xff000000 : 0x00000000;
for (var i = 0; i < width; ++i)
zeroline[i] = zerocolor;
uint[] prevline = zeroline;
int prevline_index = 0;
// initialize LZSS text (used by chroma filter type codes)
int p = 0;
for (uint i = 0; i < 32*0x01010101; i += 0x01010101)
{
for (uint j = 0; j < 16*0x01010101; j += 0x01010101)
{
LZSS_text[p++] = (byte)(i & 0xff);
LZSS_text[p++] = (byte)(i >> 8 & 0xff);
LZSS_text[p++] = (byte)(i >> 16 & 0xff);
LZSS_text[p++] = (byte)(i >> 24 & 0xff);
LZSS_text[p++] = (byte)(j & 0xff);
LZSS_text[p++] = (byte)(j >> 8 & 0xff);
LZSS_text[p++] = (byte)(j >> 16 & 0xff);
LZSS_text[p++] = (byte)(j >> 24 & 0xff);
}
}
// read chroma filter types.
// chroma filter types are compressed via LZSS as used by TLG5.
{
int inbuf_size = src.ReadInt32();
byte[] inbuf = src.ReadBytes (inbuf_size);
if (inbuf_size != inbuf.Length)
return null;
TVPTLG5DecompressSlide (filter_types, inbuf, inbuf_size, LZSS_text, 0);
}
// for each horizontal block group ...
for (int y = 0; y < height; y += TVP_TLG6_H_BLOCK_SIZE)
{
int ylim = y + TVP_TLG6_H_BLOCK_SIZE;
if (ylim >= height) ylim = height;
int pixel_count = (ylim - y) * width;
// decode values
for (int c = 0; c < colors; c++)
{
// read bit length
int bit_length = src.ReadInt32();
// get compress method
int method = (bit_length >> 30) & 3;
bit_length &= 0x3fffffff;
// compute byte length
int byte_length = bit_length / 8;
if (0 != (bit_length % 8)) byte_length++;
// read source from input
src.Read (bit_pool, 0, byte_length);
// decode values
// two most significant bits of bitlength are
// entropy coding method;
// 00 means Golomb method,
// 01 means Gamma method (not yet suppoted),
// 10 means modified LZSS method (not yet supported),
// 11 means raw (uncompressed) data (not yet supported).
switch (method)
{
case 0:
if (c == 0 && colors != 1)
TVPTLG6DecodeGolombValuesForFirst (pixelbuf, pixel_count, bit_pool);
else
TVPTLG6DecodeGolombValues (pixelbuf, c*8, pixel_count, bit_pool);
break;
default:
throw new InvalidFormatException ("Unsupported entropy coding method");
}
}
// for each line
int ft = (y / TVP_TLG6_H_BLOCK_SIZE) * x_block_count; // within filter_types
int skipbytes = (ylim - y) * TVP_TLG6_W_BLOCK_SIZE;
for (int yy = y; yy < ylim; yy++)
{
int curline = yy*width;
int dir = (yy&1)^1;
int oddskip = ((ylim - yy -1) - (yy-y));
if (0 != main_count)
{
int start =
((width < TVP_TLG6_W_BLOCK_SIZE) ? width : TVP_TLG6_W_BLOCK_SIZE) *
(yy - y);
TVPTLG6DecodeLineGeneric (
prevline, prevline_index,
image_bits, curline,
width, 0, main_count,
filter_types, ft,
skipbytes,
pixelbuf, start,
zerocolor, oddskip, dir);
}
if (main_count != x_block_count)
{
int ww = fraction;
if (ww > TVP_TLG6_W_BLOCK_SIZE) ww = TVP_TLG6_W_BLOCK_SIZE;
int start = ww * (yy - y);
TVPTLG6DecodeLineGeneric (
prevline, prevline_index,
image_bits, curline,
width, main_count, x_block_count,
filter_types, ft,
skipbytes,
pixelbuf, start,
zerocolor, oddskip, dir);
}
prevline = image_bits;
prevline_index = curline;
}
}
int stride = width * 4;
var pixels = new byte[height * stride];
Buffer.BlockCopy (image_bits, 0, pixels, 0, pixels.Length);
return pixels;
}
byte[] ReadV5 (IBinaryStream src, TlgMetaData info)
{
int width = (int)info.Width;
int height = (int)info.Height;
int colors = info.BPP / 8;
int blockheight = src.ReadInt32();
int blockcount = (height - 1) / blockheight + 1;
// skip block size section
src.Seek (blockcount * 4, SeekOrigin.Current);
int stride = width * 4;
var image_bits = new byte[height * stride];
var text = new byte[4096];
for (int i = 0; i < 4096; ++i)
text[i] = 0;
var inbuf = new byte[blockheight * width + 10];
byte [][] outbuf = new byte[4][];
for (int i = 0; i < colors; i++)
outbuf[i] = new byte[blockheight * width + 10];
int z = 0;
int prevline = -1;
for (int y_blk = 0; y_blk < height; y_blk += blockheight)
{
// read file and decompress
for (int c = 0; c < colors; c++)
{
byte mark = src.ReadUInt8();
int size;
size = src.ReadInt32();
if (mark == 0)
{
// modified LZSS compressed data
if (size != src.Read (inbuf, 0, size))
return null;
z = TVPTLG5DecompressSlide (outbuf[c], inbuf, size, text, z);
}
else
{
// raw data
src.Read (outbuf[c], 0, size);
}
}
// compose colors and store
int y_lim = y_blk + blockheight;
if (y_lim > height) y_lim = height;
int outbuf_pos = 0;
for (int y = y_blk; y < y_lim; y++)
{
int current = y * stride;
int current_org = current;
if (prevline >= 0)
{
// not first line
switch(colors)
{
case 3:
TVPTLG5ComposeColors3To4 (image_bits, current, prevline,
outbuf, outbuf_pos, width);
break;
case 4:
TVPTLG5ComposeColors4To4 (image_bits, current, prevline,
outbuf, outbuf_pos, width);
break;
}
}
else
{
// first line
switch(colors)
{
case 3:
for (int pr = 0, pg = 0, pb = 0, x = 0;
x < width; x++)
{
int b = outbuf[0][outbuf_pos+x];
int g = outbuf[1][outbuf_pos+x];
int r = outbuf[2][outbuf_pos+x];
b += g; r += g;
image_bits[current++] = (byte)(pb += b);
image_bits[current++] = (byte)(pg += g);
image_bits[current++] = (byte)(pr += r);
image_bits[current++] = 0xff;
}
break;
case 4:
for (int pr = 0, pg = 0, pb = 0, pa = 0, x = 0;
x < width; x++)
{
int b = outbuf[0][outbuf_pos+x];
int g = outbuf[1][outbuf_pos+x];
int r = outbuf[2][outbuf_pos+x];
int a = outbuf[3][outbuf_pos+x];
b += g; r += g;
image_bits[current++] = (byte)(pb += b);
image_bits[current++] = (byte)(pg += g);
image_bits[current++] = (byte)(pr += r);
image_bits[current++] = (byte)(pa += a);
}
break;
}
}
outbuf_pos += width;
prevline = current_org;
}
}
return image_bits;
}
void TVPTLG5ComposeColors3To4 (byte[] outp, int outp_index, int upper,
byte[][] buf, int bufpos, int width)
{
byte pc0 = 0, pc1 = 0, pc2 = 0;
byte c0, c1, c2;
for (int x = 0; x < width; x++)
{
c0 = buf[0][bufpos+x];
c1 = buf[1][bufpos+x];
c2 = buf[2][bufpos+x];
c0 += c1; c2 += c1;
outp[outp_index++] = (byte)(((pc0 += c0) + outp[upper+0]) & 0xff);
outp[outp_index++] = (byte)(((pc1 += c1) + outp[upper+1]) & 0xff);
outp[outp_index++] = (byte)(((pc2 += c2) + outp[upper+2]) & 0xff);
outp[outp_index++] = 0xff;
upper += 4;
}
}
void TVPTLG5ComposeColors4To4 (byte[] outp, int outp_index, int upper,
byte[][] buf, int bufpos, int width)
{
byte pc0 = 0, pc1 = 0, pc2 = 0, pc3 = 0;
byte c0, c1, c2, c3;
for (int x = 0; x < width; x++)
{
c0 = buf[0][bufpos+x];
c1 = buf[1][bufpos+x];
c2 = buf[2][bufpos+x];
c3 = buf[3][bufpos+x];
c0 += c1; c2 += c1;
outp[outp_index++] = (byte)(((pc0 += c0) + outp[upper+0]) & 0xff);
outp[outp_index++] = (byte)(((pc1 += c1) + outp[upper+1]) & 0xff);
outp[outp_index++] = (byte)(((pc2 += c2) + outp[upper+2]) & 0xff);
outp[outp_index++] = (byte)(((pc3 += c3) + outp[upper+3]) & 0xff);
upper += 4;
}
}
int TVPTLG5DecompressSlide (byte[] outbuf, byte[] inbuf, int inbuf_size, byte[] text, int initialr)
{
int r = initialr;
uint flags = 0;
int o = 0;
for (int i = 0; i < inbuf_size; )
{
if (((flags >>= 1) & 256) == 0)
{
flags = (uint)(inbuf[i++] | 0xff00);
}
if (0 != (flags & 1))
{
int mpos = inbuf[i] | ((inbuf[i+1] & 0xf) << 8);
int mlen = (inbuf[i+1] & 0xf0) >> 4;
i += 2;
mlen += 3;
if (mlen == 18) mlen += inbuf[i++];
while (0 != mlen--)
{
outbuf[o++] = text[r++] = text[mpos++];
mpos &= (4096 - 1);
r &= (4096 - 1);
}
}
else
{
byte c = inbuf[i++];
outbuf[o++] = c;
text[r++] = c;
r &= (4096 - 1);
}
}
return r;
}
static uint tvp_make_gt_mask (uint a, uint b)
{
uint tmp2 = ~b;
uint tmp = ((a & tmp2) + (((a ^ tmp2) >> 1) & 0x7f7f7f7f) ) & 0x80808080;
tmp = ((tmp >> 7) + 0x7f7f7f7f) ^ 0x7f7f7f7f;
return tmp;
}
static uint tvp_packed_bytes_add (uint a, uint b)
{
uint tmp = (uint)((((a & b)<<1) + ((a ^ b) & 0xfefefefe) ) & 0x01010100);
return a+b-tmp;
}
static uint tvp_med2 (uint a, uint b, uint c)
{
/* do Median Edge Detector thx, Mr. sugi at kirikiri.info */
uint aa_gt_bb = tvp_make_gt_mask(a, b);
uint a_xor_b_and_aa_gt_bb = ((a ^ b) & aa_gt_bb);
uint aa = a_xor_b_and_aa_gt_bb ^ a;
uint bb = a_xor_b_and_aa_gt_bb ^ b;
uint n = tvp_make_gt_mask(c, bb);
uint nn = tvp_make_gt_mask(aa, c);
uint m = ~(n | nn);
return (n & aa) | (nn & bb) | ((bb & m) - (c & m) + (aa & m));
}
static uint tvp_med (uint a, uint b, uint c, uint v)
{
return tvp_packed_bytes_add (tvp_med2 (a, b, c), v);
}
static uint tvp_avg (uint a, uint b, uint c, uint v)
{
return tvp_packed_bytes_add ((((a&b) + (((a^b) & 0xfefefefe) >> 1)) + ((a^b)&0x01010101)), v);
}
delegate uint tvp_decoder (uint a, uint b, uint c, uint v);
void TVPTLG6DecodeLineGeneric (uint[] prevline, int prevline_index,
uint[] curline, int curline_index,
int width, int start_block, int block_limit,
byte[] filtertypes, int filtertypes_index,
int skipblockbytes,
uint[] inbuf, int inbuf_index,
uint initialp, int oddskip, int dir)
{
/*
chroma/luminosity decoding
(this does reordering, color correlation filter, MED/AVG at a time)
*/
uint p, up;
if (0 != start_block)
{
prevline_index += start_block * TVP_TLG6_W_BLOCK_SIZE;
curline_index += start_block * TVP_TLG6_W_BLOCK_SIZE;
p = curline[curline_index-1];
up = prevline[prevline_index-1];
}
else
{
p = up = initialp;
}
inbuf_index += skipblockbytes * start_block;
int step = 0 != (dir & 1) ? 1 : -1;
for (int i = start_block; i < block_limit; i++)
{
int w = width - i*TVP_TLG6_W_BLOCK_SIZE;
if (w > TVP_TLG6_W_BLOCK_SIZE) w = TVP_TLG6_W_BLOCK_SIZE;
int ww = w;
if (step == -1) inbuf_index += ww-1;
if (0 != (i & 1)) inbuf_index += oddskip * ww;
tvp_decoder decoder;
switch (filtertypes[filtertypes_index+i])
{
case 0:
decoder = (a, b, c, v) => tvp_med (a, b, c, v);
break;
case 1:
decoder = (a, b, c, v) => tvp_avg (a, b, c, v);
break;
case 2:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+((v>>8)&0xff))<<16)) + (((v>>8)&0xff)<<8) + (0xff & ((v&0xff)+((v>>8)&0xff))) + ((v&0xff000000))));
break;
case 3:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+((v>>8)&0xff))<<16)) + (((v>>8)&0xff)<<8) + (0xff & ((v&0xff)+((v>>8)&0xff))) + ((v&0xff000000))));
break;
case 4:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+(v&0xff)+((v>>8)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+(v&0xff))<<8)) + (0xff & ((v&0xff))) + ((v&0xff000000))));
break;
case 5:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+(v&0xff)+((v>>8)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+(v&0xff))<<8)) + (0xff & ((v&0xff))) + ((v&0xff000000))));
break;
case 6:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+((v>>16)&0xff))<<8)) + (0xff & ((v&0xff)+((v>>16)&0xff)+((v>>8)&0xff))) + ((v&0xff000000))));
break;
case 7:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+((v>>16)&0xff))<<8)) + (0xff & ((v&0xff)+((v>>16)&0xff)+((v>>8)&0xff))) + ((v&0xff000000))));
break;
case 8:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+(v&0xff)+((v>>16)&0xff)+((v>>8)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+(v&0xff)+((v>>16)&0xff))<<8)) + (0xff & ((v&0xff)+((v>>16)&0xff))) + ((v&0xff000000))));
break;
case 9:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+(v&0xff)+((v>>16)&0xff)+((v>>8)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+(v&0xff)+((v>>16)&0xff))<<8)) + (0xff & ((v&0xff)+((v>>16)&0xff))) + ((v&0xff000000))));
break;
case 10:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+(v&0xff)+((v>>16)&0xff))<<8)) + (0xff & ((v&0xff)+((v>>16)&0xff))) + ((v&0xff000000))));
break;
case 11:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+(v&0xff)+((v>>16)&0xff))<<8)) + (0xff & ((v&0xff)+((v>>16)&0xff))) + ((v&0xff000000))));
break;
case 12:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff))<<8)) + (0xff & ((v&0xff)+((v>>8)&0xff))) + ((v&0xff000000))));
break;
case 13:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff))<<8)) + (0xff & ((v&0xff)+((v>>8)&0xff))) + ((v&0xff000000))));
break;
case 14:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+(v&0xff))<<8)) + (0xff & ((v&0xff))) + ((v&0xff000000))));
break;
case 15:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+(v&0xff))<<8)) + (0xff & ((v&0xff))) + ((v&0xff000000))));
break;
case 16:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+((v>>8)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff))<<8)) + (0xff & ((v&0xff))) + ((v&0xff000000))));
break;
case 17:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+((v>>8)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff))<<8)) + (0xff & ((v&0xff))) + ((v&0xff000000))));
break;
case 18:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+(v&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+((v>>16)&0xff)+(v&0xff))<<8)) + (0xff & ((v&0xff)+((v>>8)&0xff)+((v>>16)&0xff)+(v&0xff))) + ((v&0xff000000))));
break;
case 19:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+(v&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+((v>>16)&0xff)+(v&0xff))<<8)) + (0xff & ((v&0xff)+((v>>8)&0xff)+((v>>16)&0xff)+(v&0xff))) + ((v&0xff000000))));
break;
case 20:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+((v>>16)&0xff))<<8)) + (0xff & ((v&0xff)+((v>>16)&0xff))) + ((v&0xff000000))));
break;
case 21:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+((v>>16)&0xff))<<8)) + (0xff & ((v&0xff)+((v>>16)&0xff))) + ((v&0xff000000))));
break;
case 22:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+(v&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+(v&0xff))<<8)) + (0xff & ((v&0xff))) + ((v&0xff000000))));
break;
case 23:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+(v&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+(v&0xff))<<8)) + (0xff & ((v&0xff))) + ((v&0xff000000))));
break;
case 24:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+(v&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+((v>>16)&0xff)+(v&0xff))<<8)) + (0xff & ((v&0xff))) + ((v&0xff000000))));
break;
case 25:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+(v&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+((v>>16)&0xff)+(v&0xff))<<8)) + (0xff & ((v&0xff))) + ((v&0xff000000))));
break;
case 26:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+(v&0xff)+((v>>8)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+((v>>16)&0xff)+(v&0xff)+((v>>8)&0xff))<<8)) + (0xff & ((v&0xff)+((v>>8)&0xff))) + ((v&0xff000000))));
break;
case 27:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+(v&0xff)+((v>>8)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+((v>>16)&0xff)+(v&0xff)+((v>>8)&0xff))<<8)) + (0xff & ((v&0xff)+((v>>8)&0xff))) + ((v&0xff000000))));
break;
case 28:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+(v&0xff)+((v>>8)&0xff)+((v>>16)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+((v>>16)&0xff))<<8)) + (0xff & ((v&0xff)+((v>>8)&0xff)+((v>>16)&0xff))) + ((v&0xff000000))));
break;
case 29:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+(v&0xff)+((v>>8)&0xff)+((v>>16)&0xff))<<16)) + (0xff00 & ((((v>>8)&0xff)+((v>>16)&0xff))<<8)) + (0xff & ((v&0xff)+((v>>8)&0xff)+((v>>16)&0xff))) + ((v&0xff000000))));
break;
case 30:
decoder = (a, b, c, v) => tvp_med (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+((v&0xff)<<1))<<16)) + (0xff00 & ((((v>>8)&0xff)+((v&0xff)<<1))<<8)) + (0xff & ((v&0xff))) + ((v&0xff000000))));
break;
case 31:
decoder = (a, b, c, v) => tvp_avg (a, b, c, (uint)
((0xff0000 & ((((v>>16)&0xff)+((v&0xff)<<1))<<16)) + (0xff00 & ((((v>>8)&0xff)+((v&0xff)<<1))<<8)) + (0xff & ((v&0xff))) + ((v&0xff000000))));
break;
default: return;
}
do {
uint u = prevline[prevline_index];
p = decoder (p, u, up, inbuf[inbuf_index]);
up = u;
curline[curline_index] = p;
curline_index++;
prevline_index++;
inbuf_index += step;
} while (0 != --w);
if (step == 1)
inbuf_index += skipblockbytes - ww;
else
inbuf_index += skipblockbytes + 1;
if (0 != (i&1)) inbuf_index -= oddskip * ww;
}
}
static class TVP_Tables
{
public static byte[] TVPTLG6LeadingZeroTable = new byte[TVP_TLG6_LeadingZeroTable_SIZE];
public static sbyte[,] TVPTLG6GolombBitLengthTable = new sbyte
[TVP_TLG6_GOLOMB_N_COUNT*2*128, TVP_TLG6_GOLOMB_N_COUNT];
static short[,] TVPTLG6GolombCompressed = new short[TVP_TLG6_GOLOMB_N_COUNT,9] {
{3,7,15,27,63,108,223,448,130,},
{3,5,13,24,51,95,192,384,257,},
{2,5,12,21,39,86,155,320,384,},
{2,3,9,18,33,61,129,258,511,},
/* Tuned by W.Dee, 2004/03/25 */
};
static TVP_Tables ()
{
TVPTLG6InitLeadingZeroTable();
TVPTLG6InitGolombTable();
}
static void TVPTLG6InitLeadingZeroTable ()
{
/* table which indicates first set bit position + 1. */
/* this may be replaced by BSF (IA32 instrcution). */
for (int i = 0; i < TVP_TLG6_LeadingZeroTable_SIZE; i++)
{
int cnt = 0;
int j;
for(j = 1; j != TVP_TLG6_LeadingZeroTable_SIZE && 0 == (i & j);
j <<= 1, cnt++);
cnt++;
if (j == TVP_TLG6_LeadingZeroTable_SIZE) cnt = 0;
TVPTLG6LeadingZeroTable[i] = (byte)cnt;
}
}
static void TVPTLG6InitGolombTable()
{
for (int n = 0; n < TVP_TLG6_GOLOMB_N_COUNT; n++)
{
int a = 0;
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < TVPTLG6GolombCompressed[n,i]; j++)
TVPTLG6GolombBitLengthTable[a++,n] = (sbyte)i;
}
if(a != TVP_TLG6_GOLOMB_N_COUNT*2*128)
throw new Exception ("Invalid data initialization"); /* THIS MUST NOT BE EXECUETED! */
/* (this is for compressed table data check) */
}
}
}
void TVPTLG6DecodeGolombValuesForFirst (uint[] pixelbuf, int pixel_count, byte[] bit_pool)
{
/*
decode values packed in "bit_pool".
values are coded using golomb code.
"ForFirst" function do dword access to pixelbuf,
clearing with zero except for blue (least siginificant byte).
*/
int bit_pool_index = 0;
int n = TVP_TLG6_GOLOMB_N_COUNT - 1; /* output counter */
int a = 0; /* summary of absolute values of errors */
int bit_pos = 1;
bool zero = 0 == (bit_pool[bit_pool_index] & 1);
for (int pixel = 0; pixel < pixel_count; )
{
/* get running count */
int count;
{
uint t = LittleEndian.ToUInt32 (bit_pool, bit_pool_index) >> bit_pos;
int b = TVP_Tables.TVPTLG6LeadingZeroTable[t & (TVP_TLG6_LeadingZeroTable_SIZE-1)];
int bit_count = b;
while (0 == b)
{
bit_count += TVP_TLG6_LeadingZeroTable_BITS;
bit_pos += TVP_TLG6_LeadingZeroTable_BITS;
bit_pool_index += bit_pos >> 3;
bit_pos &= 7;
t = LittleEndian.ToUInt32 (bit_pool, bit_pool_index) >> bit_pos;
b = TVP_Tables.TVPTLG6LeadingZeroTable[t&(TVP_TLG6_LeadingZeroTable_SIZE-1)];
bit_count += b;
}
bit_pos += b;
bit_pool_index += bit_pos >> 3;
bit_pos &= 7;
bit_count --;
count = 1 << bit_count;
count += ((LittleEndian.ToInt32 (bit_pool, bit_pool_index) >> (bit_pos)) & (count-1));
bit_pos += bit_count;
bit_pool_index += bit_pos >> 3;
bit_pos &= 7;
}
if (zero)
{
/* zero values */
/* fill distination with zero */
do { pixelbuf[pixel++] = 0; } while (0 != --count);
zero = !zero;
}
else
{
/* non-zero values */
/* fill distination with glomb code */
do
{
int k = TVP_Tables.TVPTLG6GolombBitLengthTable[a,n];
int v, sign;
uint t = LittleEndian.ToUInt32 (bit_pool, bit_pool_index) >> bit_pos;
int bit_count;
int b;
if (0 != t)
{
b = TVP_Tables.TVPTLG6LeadingZeroTable[t&(TVP_TLG6_LeadingZeroTable_SIZE-1)];
bit_count = b;
while (0 == b)
{
bit_count += TVP_TLG6_LeadingZeroTable_BITS;
bit_pos += TVP_TLG6_LeadingZeroTable_BITS;
bit_pool_index += bit_pos >> 3;
bit_pos &= 7;
t = LittleEndian.ToUInt32 (bit_pool, bit_pool_index) >> bit_pos;
b = TVP_Tables.TVPTLG6LeadingZeroTable[t&(TVP_TLG6_LeadingZeroTable_SIZE-1)];
bit_count += b;
}
bit_count --;
}
else
{
bit_pool_index += 5;
bit_count = bit_pool[bit_pool_index-1];
bit_pos = 0;
t = LittleEndian.ToUInt32 (bit_pool, bit_pool_index);
b = 0;
}
v = (int)((bit_count << k) + ((t >> b) & ((1<<k)-1)));
sign = (v & 1) - 1;
v >>= 1;
a += v;
pixelbuf[pixel++] = (byte)((v ^ sign) + sign + 1);
bit_pos += b;
bit_pos += k;
bit_pool_index += bit_pos >> 3;
bit_pos &= 7;
if (--n < 0)
{
a >>= 1;
n = TVP_TLG6_GOLOMB_N_COUNT - 1;
}
} while (0 != --count);
zero = !zero;
}
}
}
void TVPTLG6DecodeGolombValues (uint[] pixelbuf, int offset, int pixel_count, byte[] bit_pool)
{
/*
decode values packed in "bit_pool".
values are coded using golomb code.
*/
uint mask = (uint)~(0xff << offset);
int bit_pool_index = 0;
int n = TVP_TLG6_GOLOMB_N_COUNT - 1; /* output counter */
int a = 0; /* summary of absolute values of errors */
int bit_pos = 1;
bool zero = 0 == (bit_pool[bit_pool_index] & 1);
for (int pixel = 0; pixel < pixel_count; )
{
/* get running count */
int count;
{
uint t = LittleEndian.ToUInt32 (bit_pool, bit_pool_index) >> bit_pos;
int b = TVP_Tables.TVPTLG6LeadingZeroTable[t&(TVP_TLG6_LeadingZeroTable_SIZE-1)];
int bit_count = b;
while (0 == b)
{
bit_count += TVP_TLG6_LeadingZeroTable_BITS;
bit_pos += TVP_TLG6_LeadingZeroTable_BITS;
bit_pool_index += bit_pos >> 3;
bit_pos &= 7;
t = LittleEndian.ToUInt32 (bit_pool, bit_pool_index) >> bit_pos;
b = TVP_Tables.TVPTLG6LeadingZeroTable[t&(TVP_TLG6_LeadingZeroTable_SIZE-1)];
bit_count += b;
}
bit_pos += b;
bit_pool_index += bit_pos >> 3;
bit_pos &= 7;
bit_count --;
count = 1 << bit_count;
count += (int)((LittleEndian.ToUInt32 (bit_pool, bit_pool_index) >> (bit_pos)) & (count-1));
bit_pos += bit_count;
bit_pool_index += bit_pos >> 3;
bit_pos &= 7;
}
if (zero)
{
/* zero values */
/* fill distination with zero */
do { pixelbuf[pixel++] &= mask; } while (0 != --count);
zero = !zero;
}
else
{
/* non-zero values */
/* fill distination with glomb code */
do
{
int k = TVP_Tables.TVPTLG6GolombBitLengthTable[a,n];
int v, sign;
uint t = LittleEndian.ToUInt32 (bit_pool, bit_pool_index) >> bit_pos;
int bit_count;
int b;
if (0 != t)
{
b = TVP_Tables.TVPTLG6LeadingZeroTable[t&(TVP_TLG6_LeadingZeroTable_SIZE-1)];
bit_count = b;
while (0 == b)
{
bit_count += TVP_TLG6_LeadingZeroTable_BITS;
bit_pos += TVP_TLG6_LeadingZeroTable_BITS;
bit_pool_index += bit_pos >> 3;
bit_pos &= 7;
t = LittleEndian.ToUInt32 (bit_pool, bit_pool_index) >> bit_pos;
b = TVP_Tables.TVPTLG6LeadingZeroTable[t&(TVP_TLG6_LeadingZeroTable_SIZE-1)];
bit_count += b;
}
bit_count --;
}
else
{
bit_pool_index += 5;
bit_count = bit_pool[bit_pool_index-1];
bit_pos = 0;
t = LittleEndian.ToUInt32 (bit_pool, bit_pool_index);
b = 0;
}
v = (int)((bit_count << k) + ((t >> b) & ((1<<k)-1)));
sign = (v & 1) - 1;
v >>= 1;
a += v;
uint c = (uint)((pixelbuf[pixel] & mask) | (uint)((byte)((v ^ sign) + sign + 1) << offset));
pixelbuf[pixel++] = c;
bit_pos += b;
bit_pos += k;
bit_pool_index += bit_pos >> 3;
bit_pos &= 7;
if (--n < 0)
{
a >>= 1;
n = TVP_TLG6_GOLOMB_N_COUNT - 1;
}
} while (0 != --count);
zero = !zero;
}
}
}
}
internal class TagsParser
{
byte[] m_tags;
Dictionary<int, Tuple<int, int>> m_map = new Dictionary<int, Tuple<int, int>>();
int m_offset;
public TagsParser (byte[] tags, int offset)
{
m_tags = tags;
m_offset = offset;
}
public bool Parse ()
{
int length = LittleEndian.ToInt32 (m_tags, m_offset);
m_offset += 4;
if (length <= 0 || length > m_tags.Length - m_offset)
return false;
while (m_offset < m_tags.Length)
{
int key_len = ParseInt();
if (key_len < 0)
return false;
int key;
switch (key_len)
{
case 1:
key = m_tags[m_offset];
break;
case 2:
key = LittleEndian.ToUInt16 (m_tags, m_offset);
break;
case 4:
key = LittleEndian.ToInt32 (m_tags, m_offset);
break;
default:
return false;
}
m_offset += key_len + 1;
int value_len = ParseInt();
if (value_len < 0)
return false;
m_map[key] = Tuple.Create (m_offset, value_len);
m_offset += value_len + 1;
}
return m_map.Count > 0;
}
int ParseInt ()
{
int colon = Array.IndexOf (m_tags, (byte)':', m_offset);
if (-1 == colon)
return -1;
var len_str = Encoding.ASCII.GetString (m_tags, m_offset, colon-m_offset);
m_offset = colon + 1;
return Int32.Parse (len_str);
}
public bool HasKey (int key)
{
return m_map.ContainsKey (key);
}
public int GetInt (int key)
{
var val = m_map[key];
switch (val.Item2)
{
case 0: return 0;
case 1: return m_tags[val.Item1];
case 2: return LittleEndian.ToUInt16 (m_tags, val.Item1);
case 4: return LittleEndian.ToInt32 (m_tags, val.Item1);
default: throw new InvalidFormatException();
}
}
public string GetString (int key)
{
var val = m_map[key];
return Encodings.cp932.GetString (m_tags, val.Item1, val.Item2);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ImageListStreamer.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.Windows.Forms {
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Diagnostics;
using System;
using System.Drawing;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;
using System.Globalization;
using System.Security.Permissions;
/// <include file='doc\ImageListStreamer.uex' path='docs/doc[@for="ImageListStreamer"]/*' />
/// <devdoc>
/// </devdoc>
[Serializable]
public sealed class ImageListStreamer : ISerializable, IDisposable {
// compressed magic header. If we see this, the image stream is compressed.
// (unicode for MSFT).
//
private static readonly byte[] HEADER_MAGIC = new byte[] {0x4D, 0x53, 0x46, 0X74};
private static object internalSyncObject = new object();
private ImageList imageList;
private ImageList.NativeImageList nativeImageList;
internal ImageListStreamer(ImageList il) {
imageList = il;
}
/**
* Constructor used in deserialization
*/
private ImageListStreamer(SerializationInfo info, StreamingContext context)
{
SerializationInfoEnumerator sie = info.GetEnumerator();
if (sie == null)
{
return;
}
while (sie.MoveNext())
{
if (String.Equals(sie.Name, "Data", StringComparison.OrdinalIgnoreCase))
{
#if DEBUG
try {
#endif
byte[] dat = (byte[])sie.Value;
if (dat != null)
{
//VSW #123063: We enclose this imagelist handle create in a theming scope. This is a temporary
// solution till we tackle the bigger issue tracked by VSW #95247
IntPtr userCookie = UnsafeNativeMethods.ThemingScope.Activate();
try
{
MemoryStream ms = new MemoryStream(Decompress(dat));
lock (internalSyncObject) {
SafeNativeMethods.InitCommonControls();
nativeImageList = new ImageList.NativeImageList(
SafeNativeMethods.ImageList_Read(new UnsafeNativeMethods.ComStreamFromDataStream(ms)));
}
}
finally
{
UnsafeNativeMethods.ThemingScope.Deactivate(userCookie);
}
if (nativeImageList.Handle == IntPtr.Zero)
{
throw new InvalidOperationException(SR.GetString(SR.ImageListStreamerLoadFailed));
}
}
#if DEBUG
}
catch (Exception e) {
Debug.Fail("ImageList serialization failure: " + e.ToString());
throw;
}
#endif
}
}
}
/// <devdoc>
/// Compresses the given input, returning a new array that represents
/// the compressed data.
/// </devdoc>
private byte[] Compress(byte[] input) {
int finalLength = 0;
int idx = 0;
int compressedIdx = 0;
while(idx < input.Length) {
byte current = input[idx++];
byte runLength = 1;
while(idx < input.Length && input[idx] == current && runLength < 0xFF) {
runLength++;
idx++;
}
finalLength += 2;
}
byte[] output = new byte[finalLength + HEADER_MAGIC.Length];
Buffer.BlockCopy(HEADER_MAGIC, 0, output, 0, HEADER_MAGIC.Length);
int idxOffset = HEADER_MAGIC.Length;
idx = 0;
while(idx < input.Length) {
byte current = input[idx++];
byte runLength = 1;
while(idx < input.Length && input[idx] == current && runLength < 0xFF) {
runLength++;
idx++;
}
output[idxOffset + compressedIdx++] = runLength;
output[idxOffset + compressedIdx++] = current;
}
Debug.Assert(idxOffset + compressedIdx == output.Length, "RLE Compression failure in ImageListStreamer -- didn't fill array");
// Validate that our compression routine works
#if DEBUG
byte[] debugCompare = Decompress(output);
Debug.Assert(debugCompare.Length == input.Length, "RLE Compression in ImageListStreamer is broken.");
int debugMaxCompare = input.Length;
for(int debugIdx = 0; debugIdx < debugMaxCompare; debugIdx++) {
if (debugCompare[debugIdx] != input[debugIdx]) {
Debug.Fail("RLE Compression failure in ImageListStreamer at byte offset " + debugIdx);
break;
}
}
#endif // DEBUG
return output;
}
/// <devdoc>
/// Decompresses the given input, returning a new array that represents
/// the uncompressed data.
/// </devdoc>
private byte[] Decompress(byte[] input) {
int finalLength = 0;
int idx = 0;
int outputIdx = 0;
// Check for our header. If we don't have one,
// we're not actually decompressed, so just return
// the original.
//
if (input.Length < HEADER_MAGIC.Length) {
return input;
}
for(idx = 0; idx < HEADER_MAGIC.Length; idx++) {
if (input[idx] != HEADER_MAGIC[idx]) {
return input;
}
}
// Ok, we passed the magic header test.
for (idx = HEADER_MAGIC.Length; idx < input.Length; idx+=2) {
finalLength += input[idx];
}
byte[] output = new byte[finalLength];
idx = HEADER_MAGIC.Length;
while(idx < input.Length) {
byte runLength = input[idx++];
byte current = input[idx++];
int startIdx = outputIdx;
int endIdx = outputIdx + runLength;
while(startIdx < endIdx) {
output[startIdx++] = current;
}
outputIdx += runLength;
}
return output;
}
/// <include file='doc\ImageListStreamer.uex' path='docs/doc[@for="ImageListStreamer.GetObjectData"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter)]
public void /*cpr: ISerializable*/GetObjectData(SerializationInfo si, StreamingContext context) {
MemoryStream stream = new MemoryStream();
IntPtr handle = IntPtr.Zero;
if (imageList != null) {
handle = imageList.Handle;
}
else if (nativeImageList != null) {
handle = nativeImageList.Handle;
}
if (handle == IntPtr.Zero || !WriteImageList(handle, stream))
throw new InvalidOperationException(SR.GetString(SR.ImageListStreamerSaveFailed));
si.AddValue("Data", Compress(stream.ToArray()));
}
/// <include file='doc\ImageListStreamer.uex' path='docs/doc[@for="ImageListStreamer.GetNativeImageList"]/*' />
/// <internalonly/>
internal ImageList.NativeImageList GetNativeImageList() {
return nativeImageList;
}
private bool WriteImageList(IntPtr imagelistHandle, Stream stream) {
// What we need to do here is use WriteEx if comctl 6 or above, and Write otherwise. However, till we can fix
// VSWhidbey #248889, there isn't a reliable way to tell which version of comctl fusion is binding to.
// So for now, we try to bind to WriteEx, and if that entry point isn't found, we use Write.
try {
int hResult = SafeNativeMethods.ImageList_WriteEx(new HandleRef(this, imagelistHandle), NativeMethods.ILP_DOWNLEVEL, new UnsafeNativeMethods.ComStreamFromDataStream(stream));
return (hResult == NativeMethods.S_OK);
}
catch (EntryPointNotFoundException) {
// WriteEx wasn't found - that's fine - we will use Write.
}
return SafeNativeMethods.ImageList_Write(new HandleRef(this, imagelistHandle), new UnsafeNativeMethods.ComStreamFromDataStream(stream));
}
/// <include file='doc\ImageListStreamer.uex' path='docs/doc[@for="ImageListStreamer.GetNativeImageList"]/*' />
/// <devdoc>
/// Disposes the native image list handle.
/// </devdoc>
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing) {
if (disposing) {
if (nativeImageList != null) {
nativeImageList.Dispose();
nativeImageList = null;
}
}
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// GST Percentages Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class KGSTDataSet : EduHubDataSet<KGST>
{
/// <inheritdoc />
public override string Name { get { return "KGST"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal KGSTDataSet(EduHubContext Context)
: base(Context)
{
Index_GLGST_CODE = new Lazy<NullDictionary<string, IReadOnlyList<KGST>>>(() => this.ToGroupedNullDictionary(i => i.GLGST_CODE));
Index_KGSTKEY = new Lazy<Dictionary<string, KGST>>(() => this.ToDictionary(i => i.KGSTKEY));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="KGST" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="KGST" /> fields for each CSV column header</returns>
internal override Action<KGST, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<KGST, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "KGSTKEY":
mapper[i] = (e, v) => e.KGSTKEY = v;
break;
case "DESCRIPTION":
mapper[i] = (e, v) => e.DESCRIPTION = v;
break;
case "SALE_PURCH":
mapper[i] = (e, v) => e.SALE_PURCH = v;
break;
case "GST_RATE":
mapper[i] = (e, v) => e.GST_RATE = v == null ? (double?)null : double.Parse(v);
break;
case "GST_BOX":
mapper[i] = (e, v) => e.GST_BOX = v;
break;
case "GLGST_CODE":
mapper[i] = (e, v) => e.GLGST_CODE = v;
break;
case "GST_RECLAIM":
mapper[i] = (e, v) => e.GST_RECLAIM = v;
break;
case "PRIOR_PERIOD_GST":
mapper[i] = (e, v) => e.PRIOR_PERIOD_GST = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="KGST" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="KGST" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="KGST" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{KGST}"/> of entities</returns>
internal override IEnumerable<KGST> ApplyDeltaEntities(IEnumerable<KGST> Entities, List<KGST> DeltaEntities)
{
HashSet<string> Index_KGSTKEY = new HashSet<string>(DeltaEntities.Select(i => i.KGSTKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.KGSTKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_KGSTKEY.Remove(entity.KGSTKEY);
if (entity.KGSTKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<string, IReadOnlyList<KGST>>> Index_GLGST_CODE;
private Lazy<Dictionary<string, KGST>> Index_KGSTKEY;
#endregion
#region Index Methods
/// <summary>
/// Find KGST by GLGST_CODE field
/// </summary>
/// <param name="GLGST_CODE">GLGST_CODE value used to find KGST</param>
/// <returns>List of related KGST entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<KGST> FindByGLGST_CODE(string GLGST_CODE)
{
return Index_GLGST_CODE.Value[GLGST_CODE];
}
/// <summary>
/// Attempt to find KGST by GLGST_CODE field
/// </summary>
/// <param name="GLGST_CODE">GLGST_CODE value used to find KGST</param>
/// <param name="Value">List of related KGST entities</param>
/// <returns>True if the list of related KGST entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByGLGST_CODE(string GLGST_CODE, out IReadOnlyList<KGST> Value)
{
return Index_GLGST_CODE.Value.TryGetValue(GLGST_CODE, out Value);
}
/// <summary>
/// Attempt to find KGST by GLGST_CODE field
/// </summary>
/// <param name="GLGST_CODE">GLGST_CODE value used to find KGST</param>
/// <returns>List of related KGST entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<KGST> TryFindByGLGST_CODE(string GLGST_CODE)
{
IReadOnlyList<KGST> value;
if (Index_GLGST_CODE.Value.TryGetValue(GLGST_CODE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find KGST by KGSTKEY field
/// </summary>
/// <param name="KGSTKEY">KGSTKEY value used to find KGST</param>
/// <returns>Related KGST entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KGST FindByKGSTKEY(string KGSTKEY)
{
return Index_KGSTKEY.Value[KGSTKEY];
}
/// <summary>
/// Attempt to find KGST by KGSTKEY field
/// </summary>
/// <param name="KGSTKEY">KGSTKEY value used to find KGST</param>
/// <param name="Value">Related KGST entity</param>
/// <returns>True if the related KGST entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByKGSTKEY(string KGSTKEY, out KGST Value)
{
return Index_KGSTKEY.Value.TryGetValue(KGSTKEY, out Value);
}
/// <summary>
/// Attempt to find KGST by KGSTKEY field
/// </summary>
/// <param name="KGSTKEY">KGSTKEY value used to find KGST</param>
/// <returns>Related KGST entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public KGST TryFindByKGSTKEY(string KGSTKEY)
{
KGST value;
if (Index_KGSTKEY.Value.TryGetValue(KGSTKEY, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a KGST table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KGST]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[KGST](
[KGSTKEY] varchar(4) NOT NULL,
[DESCRIPTION] varchar(40) NULL,
[SALE_PURCH] varchar(2) NULL,
[GST_RATE] float NULL,
[GST_BOX] varchar(3) NULL,
[GLGST_CODE] varchar(10) NULL,
[GST_RECLAIM] varchar(1) NULL,
[PRIOR_PERIOD_GST] varchar(4) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [KGST_Index_KGSTKEY] PRIMARY KEY CLUSTERED (
[KGSTKEY] ASC
)
);
CREATE NONCLUSTERED INDEX [KGST_Index_GLGST_CODE] ON [dbo].[KGST]
(
[GLGST_CODE] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGST]') AND name = N'KGST_Index_GLGST_CODE')
ALTER INDEX [KGST_Index_GLGST_CODE] ON [dbo].[KGST] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGST]') AND name = N'KGST_Index_GLGST_CODE')
ALTER INDEX [KGST_Index_GLGST_CODE] ON [dbo].[KGST] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KGST"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="KGST"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KGST> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_KGSTKEY = new List<string>();
foreach (var entity in Entities)
{
Index_KGSTKEY.Add(entity.KGSTKEY);
}
builder.AppendLine("DELETE [dbo].[KGST] WHERE");
// Index_KGSTKEY
builder.Append("[KGSTKEY] IN (");
for (int index = 0; index < Index_KGSTKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// KGSTKEY
var parameterKGSTKEY = $"@p{parameterIndex++}";
builder.Append(parameterKGSTKEY);
command.Parameters.Add(parameterKGSTKEY, SqlDbType.VarChar, 4).Value = Index_KGSTKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KGST data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KGST data set</returns>
public override EduHubDataSetDataReader<KGST> GetDataSetDataReader()
{
return new KGSTDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the KGST data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the KGST data set</returns>
public override EduHubDataSetDataReader<KGST> GetDataSetDataReader(List<KGST> Entities)
{
return new KGSTDataReader(new EduHubDataSetLoadedReader<KGST>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class KGSTDataReader : EduHubDataSetDataReader<KGST>
{
public KGSTDataReader(IEduHubDataSetReader<KGST> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 11; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // KGSTKEY
return Current.KGSTKEY;
case 1: // DESCRIPTION
return Current.DESCRIPTION;
case 2: // SALE_PURCH
return Current.SALE_PURCH;
case 3: // GST_RATE
return Current.GST_RATE;
case 4: // GST_BOX
return Current.GST_BOX;
case 5: // GLGST_CODE
return Current.GLGST_CODE;
case 6: // GST_RECLAIM
return Current.GST_RECLAIM;
case 7: // PRIOR_PERIOD_GST
return Current.PRIOR_PERIOD_GST;
case 8: // LW_DATE
return Current.LW_DATE;
case 9: // LW_TIME
return Current.LW_TIME;
case 10: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // DESCRIPTION
return Current.DESCRIPTION == null;
case 2: // SALE_PURCH
return Current.SALE_PURCH == null;
case 3: // GST_RATE
return Current.GST_RATE == null;
case 4: // GST_BOX
return Current.GST_BOX == null;
case 5: // GLGST_CODE
return Current.GLGST_CODE == null;
case 6: // GST_RECLAIM
return Current.GST_RECLAIM == null;
case 7: // PRIOR_PERIOD_GST
return Current.PRIOR_PERIOD_GST == null;
case 8: // LW_DATE
return Current.LW_DATE == null;
case 9: // LW_TIME
return Current.LW_TIME == null;
case 10: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // KGSTKEY
return "KGSTKEY";
case 1: // DESCRIPTION
return "DESCRIPTION";
case 2: // SALE_PURCH
return "SALE_PURCH";
case 3: // GST_RATE
return "GST_RATE";
case 4: // GST_BOX
return "GST_BOX";
case 5: // GLGST_CODE
return "GLGST_CODE";
case 6: // GST_RECLAIM
return "GST_RECLAIM";
case 7: // PRIOR_PERIOD_GST
return "PRIOR_PERIOD_GST";
case 8: // LW_DATE
return "LW_DATE";
case 9: // LW_TIME
return "LW_TIME";
case 10: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "KGSTKEY":
return 0;
case "DESCRIPTION":
return 1;
case "SALE_PURCH":
return 2;
case "GST_RATE":
return 3;
case "GST_BOX":
return 4;
case "GLGST_CODE":
return 5;
case "GST_RECLAIM":
return 6;
case "PRIOR_PERIOD_GST":
return 7;
case "LW_DATE":
return 8;
case "LW_TIME":
return 9;
case "LW_USER":
return 10;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using VelcroPhysics.Extensions.DebugView;
using VelcroPhysics.MonoGame.Samples.Demo.MediaSystem;
namespace VelcroPhysics.MonoGame.Samples.Demo.ScreenSystem
{
/// <summary>
/// Base class for screens that contain a menu of options. The user can
/// move up and down to select an entry, or cancel to back out of the screen.
/// </summary>
public class OptionsScreen : GameScreen
{
private const float HorizontalPadding = 24f;
private const float VerticalPadding = 24f;
private const int EntrySpacer = 5;
private readonly List<OptionEntry> _optionEntries = new List<OptionEntry>();
private Vector2 _bottomRight;
private Texture2D _checkmark;
private SpriteFont _font;
private int _hoverEntry;
private Vector2 _optionCheckOffset;
private Vector2 _optionEntrySize;
private float _optionSpacing;
private float _optionStart;
private Vector2 _optionTextOffset;
private Vector2 _topLeft;
/// <summary>
/// Constructor.
/// </summary>
public OptionsScreen()
{
IsPopup = true;
HasCursor = true;
TransitionOnTime = TimeSpan.FromSeconds(0.4);
TransitionOffTime = TimeSpan.FromSeconds(0.4);
_optionEntrySize = Vector2.Zero;
_hoverEntry = -1;
}
private void LoadOptions()
{
_optionEntries.Add(new OptionEntry("Show debug view", PhysicsDemoScreen.RenderDebug));
_optionEntries.Add(new OptionEntry("Debug draw data panel", (PhysicsDemoScreen.Flags & DebugViewFlags.DebugPanel) == DebugViewFlags.DebugPanel));
_optionEntries.Add(new OptionEntry("Debug draw performance graph", (PhysicsDemoScreen.Flags & DebugViewFlags.PerformanceGraph) == DebugViewFlags.PerformanceGraph));
_optionEntries.Add(new OptionEntry("Debug draw shapes", (PhysicsDemoScreen.Flags & DebugViewFlags.Shape) == DebugViewFlags.Shape));
_optionEntries.Add(new OptionEntry("Debug draw polygon vertices", (PhysicsDemoScreen.Flags & DebugViewFlags.PolygonPoints) == DebugViewFlags.PolygonPoints));
_optionEntries.Add(new OptionEntry("Debug draw joint connections", (PhysicsDemoScreen.Flags & DebugViewFlags.Joint) == DebugViewFlags.Joint));
_optionEntries.Add(new OptionEntry("Debug draw axis aligned bounding boxes", (PhysicsDemoScreen.Flags & DebugViewFlags.AABB) == DebugViewFlags.AABB));
_optionEntries.Add(new OptionEntry("Debug draw center of mass", (PhysicsDemoScreen.Flags & DebugViewFlags.CenterOfMass) == DebugViewFlags.CenterOfMass));
_optionEntries.Add(new OptionEntry("Debug draw contact points", (PhysicsDemoScreen.Flags & DebugViewFlags.ContactPoints) == DebugViewFlags.ContactPoints));
_optionEntries.Add(new OptionEntry("Debug draw contact normals", (PhysicsDemoScreen.Flags & DebugViewFlags.ContactNormals) == DebugViewFlags.ContactNormals));
_optionEntries.Add(new OptionEntry("Debug draw controllers", (PhysicsDemoScreen.Flags & DebugViewFlags.Controllers) == DebugViewFlags.Controllers));
_optionEntries.Add(new OptionEntry("Play sound effects", ContentWrapper.SoundVolume == 100));
for (int i = 0; i < _optionEntries.Count; i++)
{
_optionEntrySize.X = Math.Max(_optionEntrySize.X, _optionEntries[i].Size.X);
_optionEntrySize.Y = Math.Max(_optionEntrySize.Y, _optionEntries[i].Size.Y);
}
_optionEntrySize.X += 20f + _optionEntrySize.Y;
_optionTextOffset = new Vector2(-_optionEntrySize.Y / 2f, 0f);
_optionCheckOffset = new Vector2(_optionEntrySize.X - _optionEntrySize.Y, 0f);
}
public override void LoadContent()
{
base.LoadContent();
LoadOptions();
Viewport viewport = Framework.GraphicsDevice.Viewport;
_font = ContentWrapper.GetFont("MenuFont");
_checkmark = ContentWrapper.GetTexture("Checkmark");
_optionStart = (viewport.Height - (_optionEntries.Count - 1) * (_optionEntrySize.Y + EntrySpacer)) / 2f;
_optionSpacing = _optionEntrySize.Y + EntrySpacer;
for (int i = 0; i < _optionEntries.Count; i++)
{
_optionEntries[i].InitializePosition(new Vector2(viewport.Width / 2f, _optionStart + _optionSpacing * i));
}
// The background includes a border somewhat larger than the text itself.
_topLeft.X = viewport.Width / 2f - _optionEntrySize.X / 2f - HorizontalPadding;
_topLeft.Y = _optionStart - _optionEntrySize.Y / 2f - VerticalPadding;
_bottomRight.X = viewport.Width / 2f + _optionEntrySize.X / 2f + HorizontalPadding;
_bottomRight.Y = _optionStart + (_optionEntries.Count - 1) * _optionSpacing + _optionEntrySize.Y / 2f + VerticalPadding;
}
/// <summary>
/// Returns the index of the menu entry at the position of the given mouse state.
/// </summary>
/// <returns>Index of menu entry if valid, -1 otherwise</returns>
private int GetOptionEntryAt(Vector2 position)
{
for (int i = 0; i < _optionEntries.Count; i++)
{
Rectangle boundingBox = new Rectangle((int)(_optionEntries[i].Position.X - _optionEntrySize.X / 2f), (int)(_optionEntries[i].Position.Y - _optionEntrySize.Y / 2f), (int)_optionEntrySize.X, (int)_optionEntrySize.Y);
if (boundingBox.Contains((int)position.X, (int)position.Y))
{
return i;
}
}
return -1;
}
/// <summary>
/// Responds to user input, changing the selected entry and accepting
/// or cancelling the menu.
/// </summary>
public override void HandleInput(InputHelper input, GameTime gameTime)
{
// Mouse on a menu item
_hoverEntry = GetOptionEntryAt(input.Cursor);
// Accept or cancel the menu?
if (input.IsMenuSelect())
{
if (_hoverEntry != -1)
{
_optionEntries[_hoverEntry].Switch();
switch (_hoverEntry)
{
case 0:
PhysicsDemoScreen.RenderDebug = _optionEntries[_hoverEntry].IsChecked;
break;
case 1:
PhysicsDemoScreen.Flags = _optionEntries[_hoverEntry].IsChecked ? PhysicsDemoScreen.Flags | DebugViewFlags.DebugPanel : PhysicsDemoScreen.Flags & ~DebugViewFlags.DebugPanel;
break;
case 2:
PhysicsDemoScreen.Flags = _optionEntries[_hoverEntry].IsChecked ? PhysicsDemoScreen.Flags | DebugViewFlags.PerformanceGraph : PhysicsDemoScreen.Flags & ~DebugViewFlags.PerformanceGraph;
break;
case 3:
PhysicsDemoScreen.Flags = _optionEntries[_hoverEntry].IsChecked ? PhysicsDemoScreen.Flags | DebugViewFlags.Shape : PhysicsDemoScreen.Flags & ~DebugViewFlags.Shape;
break;
case 4:
PhysicsDemoScreen.Flags = _optionEntries[_hoverEntry].IsChecked ? PhysicsDemoScreen.Flags | DebugViewFlags.PolygonPoints : PhysicsDemoScreen.Flags & ~DebugViewFlags.PolygonPoints;
break;
case 5:
PhysicsDemoScreen.Flags = _optionEntries[_hoverEntry].IsChecked ? PhysicsDemoScreen.Flags | DebugViewFlags.Joint : PhysicsDemoScreen.Flags & ~DebugViewFlags.Joint;
break;
case 6:
PhysicsDemoScreen.Flags = _optionEntries[_hoverEntry].IsChecked ? PhysicsDemoScreen.Flags | DebugViewFlags.AABB : PhysicsDemoScreen.Flags & ~DebugViewFlags.AABB;
break;
case 7:
PhysicsDemoScreen.Flags = _optionEntries[_hoverEntry].IsChecked ? PhysicsDemoScreen.Flags | DebugViewFlags.CenterOfMass : PhysicsDemoScreen.Flags & ~DebugViewFlags.CenterOfMass;
break;
case 8:
PhysicsDemoScreen.Flags = _optionEntries[_hoverEntry].IsChecked ? PhysicsDemoScreen.Flags | DebugViewFlags.ContactPoints : PhysicsDemoScreen.Flags & ~DebugViewFlags.ContactPoints;
break;
case 9:
PhysicsDemoScreen.Flags = _optionEntries[_hoverEntry].IsChecked ? PhysicsDemoScreen.Flags | DebugViewFlags.ContactNormals : PhysicsDemoScreen.Flags & ~DebugViewFlags.ContactNormals;
break;
case 10:
PhysicsDemoScreen.Flags = _optionEntries[_hoverEntry].IsChecked ? PhysicsDemoScreen.Flags | DebugViewFlags.Controllers : PhysicsDemoScreen.Flags & ~DebugViewFlags.Controllers;
break;
case 11:
ContentWrapper.SoundVolume = _optionEntries[_hoverEntry].IsChecked ? 100 : 0;
break;
}
ContentWrapper.PlaySoundEffect("Click");
}
}
if (input.IsScreenExit())
ExitScreen();
}
/// <summary>
/// Updates the menu.
/// </summary>
public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
// Update each nested MenuEntry object.
for (int i = 0; i < _optionEntries.Count; i++)
{
bool isHovered = IsActive && i == _hoverEntry;
_optionEntries[i].Update(isHovered, gameTime);
}
}
/// <summary>
/// Draws the menu.
/// </summary>
public override void Draw(GameTime gameTime)
{
Quads.Begin();
Quads.Render(_topLeft, _bottomRight, null, true, ContentWrapper.Black, ContentWrapper.Grey * 0.95f);
Quads.End();
// Draw each menu entry in turn.
Quads.Begin();
foreach (OptionEntry entry in _optionEntries)
{
Quads.Render(entry.Position - _optionEntrySize / 2f, entry.Position + _optionEntrySize / 2f, null, true, ContentWrapper.Black * TransitionAlpha, entry.TileColor * TransitionAlpha);
Quads.Render(entry.Position - _optionEntrySize / 2f + _optionCheckOffset, entry.Position + _optionEntrySize / 2f, null, true, ContentWrapper.Black * TransitionAlpha, entry.TileColor * TransitionAlpha);
}
Quads.End();
Sprites.Begin();
foreach (OptionEntry entry in _optionEntries)
{
Sprites.DrawString(_font, entry.Text, entry.Position + Vector2.One + _optionTextOffset, ContentWrapper.Black * TransitionAlpha, 0f, entry.Origin, entry.Scale, SpriteEffects.None, 0f);
Sprites.DrawString(_font, entry.Text, entry.Position + _optionTextOffset, entry.TextColor * TransitionAlpha, 0f, entry.Origin, entry.Scale, SpriteEffects.None, 0f);
Sprites.Draw(_checkmark, entry.Position - _optionEntrySize / 2f + _optionCheckOffset, Color.White * entry.CheckedFade);
}
Sprites.End();
}
}
}
| |
using System;
using Jint.Native;
using Jint.Native.Array;
using Jint.Runtime;
using Jint.Runtime.Interop;
using Xunit;
namespace Jint.Tests.Runtime
{
public class FunctionTests
{
[Fact]
public void BindCombinesBoundArgumentsToCallArgumentsCorrectly()
{
var e = new Engine();
e.Evaluate("var testFunc = function (a, b, c) { return a + ', ' + b + ', ' + c + ', ' + JSON.stringify(arguments); }");
Assert.Equal("a, 1, a, {\"0\":\"a\",\"1\":1,\"2\":\"a\"}", e.Evaluate("testFunc('a', 1, 'a');").AsString());
Assert.Equal("a, 1, a, {\"0\":\"a\",\"1\":1,\"2\":\"a\"}", e.Evaluate("testFunc.bind('anything')('a', 1, 'a');").AsString());
}
[Fact]
public void ProxyCanBeRevokedWithoutContext()
{
new Engine()
.Execute(@"
var revocable = Proxy.revocable({}, {});
var revoke = revocable.revoke;
revoke.call(null);
");
}
[Fact]
public void ArrowFunctionShouldBeExtensible()
{
new Engine()
.SetValue("assert", new Action<bool>(Assert.True))
.Execute(@"
var a = () => null
Object.defineProperty(a, 'hello', { enumerable: true, get: () => 'world' })
assert(a.hello === 'world')
a.foo = 'bar';
assert(a.foo === 'bar');
");
}
[Fact]
public void BlockScopeFunctionShouldWork()
{
const string script = @"
function execute(doc, args){
var i = doc;
{
function doSomething() {
return 'ayende';
}
i.Name = doSomething();
}
}
";
var engine = new Engine(options =>
{
options.Strict();
});
engine.Execute(script);
var obj = engine.Evaluate("var obj = {}; execute(obj); return obj;").AsObject();
Assert.Equal("ayende", obj.Get("Name").AsString());
}
[Fact]
public void ObjectCoercibleForCallable()
{
const string script = @"
var booleanCount = 0;
Boolean.prototype.then = function() {
booleanCount += 1;
};
function test() {
this.then();
}
testFunction.call(true);
assertEqual(booleanCount, 1);
";
var engine = new Engine();
engine
.SetValue("testFunction", new ClrFunctionInstance(engine, "testFunction", (thisValue, args) =>
{
return engine.Invoke(thisValue, "then", new[] { Undefined.Instance, args.At(0) });
}))
.SetValue("assertEqual", new Action<object, object>((a, b) => Assert.Equal(b, a)))
.Execute(script);
}
[Fact]
public void AnonymousLambdaShouldHaveNameDefined()
{
var engine = new Engine();
Assert.True(engine.Evaluate("(()=>{}).hasOwnProperty('name')").AsBoolean());
}
[Fact]
public void CanInvokeConstructorsFromEngine()
{
var engine = new Engine();
engine.Evaluate("class TestClass { constructor(a, b) { this.a = a; this.b = b; }}");
engine.Evaluate("function TestFunction(a, b) { this.a = a; this.b = b; }");
var instanceFromClass = engine.Construct("TestClass", "abc", 123).AsObject();
Assert.Equal("abc", instanceFromClass.Get("a"));
Assert.Equal(123, instanceFromClass.Get("b"));
var instanceFromFunction = engine.Construct("TestFunction", "abc", 123).AsObject();
Assert.Equal("abc", instanceFromFunction.Get("a"));
Assert.Equal(123, instanceFromFunction.Get("b"));
var arrayInstance = (ArrayInstance) engine.Construct("Array", "abc", 123).AsObject();
Assert.Equal((uint) 2, arrayInstance.Length);
Assert.Equal("abc", arrayInstance[0]);
Assert.Equal(123, arrayInstance[1]);
}
[Fact]
public void FunctionInstancesCanBePassedToHost()
{
var engine = new Engine();
Func<JsValue, JsValue[], JsValue> ev = null;
void addListener(Func<JsValue, JsValue[], JsValue> callback)
{
ev = callback;
}
engine.SetValue("addListener", new Action<Func<JsValue, JsValue[], JsValue>>(addListener));
engine.Execute(@"
var a = 5;
(function() {
var acc = 10;
addListener(function (val) {
a = (val || 0) + acc;
});
})();
");
Assert.Equal(5, engine.Evaluate("a"));
ev(null, new JsValue[0]);
Assert.Equal(10, engine.Evaluate("a"));
ev(null, new JsValue[] { 20 });
Assert.Equal(30, engine.Evaluate("a"));
}
[Fact]
public void BoundFunctionsCanBePassedToHost()
{
var engine = new Engine();
Func<JsValue, JsValue[], JsValue> ev = null;
void addListener(Func<JsValue, JsValue[], JsValue> callback)
{
ev = callback;
}
engine.SetValue("addListener", new Action<Func<JsValue, JsValue[], JsValue>>(addListener));
engine.Execute(@"
var a = 5;
(function() {
addListener(function (acc, val) {
a = (val || 0) + acc;
}.bind(null, 10));
})();
");
Assert.Equal(5, engine.Evaluate("a"));
ev(null, new JsValue[0]);
Assert.Equal(10, engine.Evaluate("a"));
ev(null, new JsValue[] { 20 });
Assert.Equal(30, engine.Evaluate("a"));
}
[Fact]
public void ConstructorsCanBePassedToHost()
{
var engine = new Engine();
Func<JsValue, JsValue[], JsValue> ev = null;
void addListener(Func<JsValue, JsValue[], JsValue> callback)
{
ev = callback;
}
engine.SetValue("addListener", new Action<Func<JsValue, JsValue[], JsValue>>(addListener));
engine.Execute(@"addListener(Boolean)");
Assert.Equal(true, ev(JsValue.Undefined, new JsValue[] { "test" }));
Assert.Equal(true, ev(JsValue.Undefined, new JsValue[] { 5 }));
Assert.Equal(false, ev(JsValue.Undefined, new JsValue[] { false }));
Assert.Equal(false, ev(JsValue.Undefined, new JsValue[] { 0}));
Assert.Equal(false, ev(JsValue.Undefined, new JsValue[] { JsValue.Undefined }));
}
[Fact]
public void FunctionsShouldResolveToSameReference()
{
var engine = new Engine();
engine.SetValue("equal", new Action<object, object>(Assert.Equal));
engine.Execute(@"
function testFn() {}
equal(testFn, testFn);
");
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.Network.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions;
using Microsoft.Azure.Management.Samples.Common;
using System;
using System.Collections.Generic;
namespace CreateVirtualMachinesInParallel
{
public class Program
{
private const string Username = "tirekicker";
private const string Password = "12NewPA$$w0rd!";
/**
* Azure compute sample for creating multiple virtual machines in parallel.
* - Define 1 virtual network per region
* - Define 1 storage account per region
* - Create 5 virtual machines in 2 regions using defined virtual network and storage account
* - Create a traffic manager to route traffic across the virtual machines
*/
public static void RunSample(IAzure azure)
{
string rgName = SdkContext.RandomResourceName("rgCOMV", 10);
IDictionary<Region, int> virtualMachinesByLocation = new Dictionary<Region, int>();
virtualMachinesByLocation.Add(Region.USEast, 5);
virtualMachinesByLocation.Add(Region.USSouthCentral, 5);
try
{
//=============================================================
// Create a resource group (Where all resources gets created)
//
var resourceGroup = azure.ResourceGroups.Define(rgName)
.WithRegion(Region.USWest)
.Create();
Utilities.Log($"Created a new resource group - {resourceGroup.Id}");
var publicIpCreatableKeys = new List<string>();
// Prepare a batch of Creatable definitions
//
var creatableVirtualMachines = new List<ICreatable<IVirtualMachine>>();
foreach (var entry in virtualMachinesByLocation)
{
var region = entry.Key;
var vmCount = entry.Value;
//=============================================================
// Create 1 network creatable per region
// Prepare Creatable Network definition (Where all the virtual machines get added to)
//
var networkName = SdkContext.RandomResourceName("vnetCOPD-", 20);
var networkCreatable = azure.Networks
.Define(networkName)
.WithRegion(region)
.WithExistingResourceGroup(resourceGroup)
.WithAddressSpace("172.16.0.0/16");
//=============================================================
// Create 1 storage creatable per region (For storing VMs disk)
//
var storageAccountName = SdkContext.RandomResourceName("stgcopd", 20);
var storageAccountCreatable = azure.StorageAccounts
.Define(storageAccountName)
.WithRegion(region)
.WithExistingResourceGroup(resourceGroup);
var linuxVMNamePrefix = SdkContext.RandomResourceName("vm-", 15);
for (int i = 1; i <= vmCount; i++)
{
//=============================================================
// Create 1 public IP address creatable
//
var publicIpAddressCreatable = azure.PublicIPAddresses
.Define($"{linuxVMNamePrefix}-{i}")
.WithRegion(region)
.WithExistingResourceGroup(resourceGroup)
.WithLeafDomainLabel($"{linuxVMNamePrefix}-{i}");
publicIpCreatableKeys.Add(publicIpAddressCreatable.Key);
//=============================================================
// Create 1 virtual machine creatable
var virtualMachineCreatable = azure.VirtualMachines
.Define($"{linuxVMNamePrefix}-{i}")
.WithRegion(region)
.WithExistingResourceGroup(resourceGroup)
.WithNewPrimaryNetwork(networkCreatable)
.WithPrimaryPrivateIPAddressDynamic()
.WithNewPrimaryPublicIPAddress(publicIpAddressCreatable)
.WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
.WithRootUsername(Username)
.WithRootPassword(Password)
.WithSize(VirtualMachineSizeTypes.StandardDS3V2)
.WithNewStorageAccount(storageAccountCreatable);
creatableVirtualMachines.Add(virtualMachineCreatable);
}
}
//=============================================================
// Create !!
var t1 = DateTimeOffset.Now.UtcDateTime;
Utilities.Log("Creating the virtual machines");
var virtualMachines = azure.VirtualMachines.Create(creatableVirtualMachines.ToArray());
var t2 = DateTimeOffset.Now.UtcDateTime;
Utilities.Log("Created virtual machines");
foreach (var virtualMachine in virtualMachines)
{
Utilities.Log(virtualMachine.Id);
}
Utilities.Log($"Virtual machines create: took {(t2 - t1).TotalSeconds } seconds to create == " + creatableVirtualMachines.Count + " == virtual machines");
var publicIpResourceIds = new List<string>();
foreach (string publicIpCreatableKey in publicIpCreatableKeys)
{
var pip = (IPublicIPAddress)virtualMachines.CreatedRelatedResource(publicIpCreatableKey);
publicIpResourceIds.Add(pip.Id);
}
//=============================================================
// Create 1 Traffic Manager Profile
//
var trafficManagerName = SdkContext.RandomResourceName("tra", 15);
var profileWithEndpoint = azure.TrafficManagerProfiles.Define(trafficManagerName)
.WithExistingResourceGroup(resourceGroup)
.WithLeafDomainLabel(trafficManagerName)
.WithPerformanceBasedRouting();
int endpointPriority = 1;
Microsoft.Azure.Management.TrafficManager.Fluent.TrafficManagerProfile.Definition.IWithCreate profileWithCreate = null;
foreach (var publicIpResourceId in publicIpResourceIds)
{
var endpointName = $"azendpoint-{endpointPriority}";
if (endpointPriority == 1)
{
profileWithCreate = profileWithEndpoint.DefineAzureTargetEndpoint(endpointName)
.ToResourceId(publicIpResourceId)
.WithRoutingPriority(endpointPriority)
.Attach();
}
else
{
profileWithCreate = profileWithCreate.DefineAzureTargetEndpoint(endpointName)
.ToResourceId(publicIpResourceId)
.WithRoutingPriority(endpointPriority)
.Attach();
}
endpointPriority++;
}
var trafficManagerProfile = profileWithCreate.Create();
Utilities.Log("Created a traffic manager profile - " + trafficManagerProfile.Id);
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + rgName);
azure.ResourceGroups.DeleteByName(rgName);
Utilities.Log("Deleted Resource Group: " + rgName);
}
catch (Exception)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
}
}
public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
RunSample(azure);
}
catch (Exception e)
{
Utilities.Log(e);
}
}
}
}
| |
/*
* Infoplus API
*
* Infoplus API.
*
* OpenAPI spec version: v1.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
/// BillingCode
/// </summary>
[DataContract]
public partial class BillingCode : IEquatable<BillingCode>
{
/// <summary>
/// Initializes a new instance of the <see cref="BillingCode" /> class.
/// </summary>
[JsonConstructorAttribute]
protected BillingCode() { }
/// <summary>
/// Initializes a new instance of the <see cref="BillingCode" /> class.
/// </summary>
/// <param name="Quantity">Quantity (required).</param>
/// <param name="UserId">UserId (required).</param>
/// <param name="LobId">LobId (required).</param>
/// <param name="BillingCodeTypeId">BillingCodeTypeId (required).</param>
/// <param name="Note">Note.</param>
public BillingCode(int? Quantity = null, int? UserId = null, int? LobId = null, int? BillingCodeTypeId = null, string Note = null)
{
// to ensure "Quantity" is required (not null)
if (Quantity == null)
{
throw new InvalidDataException("Quantity is a required property for BillingCode and cannot be null");
}
else
{
this.Quantity = Quantity;
}
// to ensure "UserId" is required (not null)
if (UserId == null)
{
throw new InvalidDataException("UserId is a required property for BillingCode and cannot be null");
}
else
{
this.UserId = UserId;
}
// to ensure "LobId" is required (not null)
if (LobId == null)
{
throw new InvalidDataException("LobId is a required property for BillingCode and cannot be null");
}
else
{
this.LobId = LobId;
}
// to ensure "BillingCodeTypeId" is required (not null)
if (BillingCodeTypeId == null)
{
throw new InvalidDataException("BillingCodeTypeId is a required property for BillingCode and cannot be null");
}
else
{
this.BillingCodeTypeId = BillingCodeTypeId;
}
this.Note = Note;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets CreateDate
/// </summary>
[DataMember(Name="createDate", EmitDefaultValue=false)]
public DateTime? CreateDate { get; private set; }
/// <summary>
/// Gets or Sets ModifyDate
/// </summary>
[DataMember(Name="modifyDate", EmitDefaultValue=false)]
public DateTime? ModifyDate { get; private set; }
/// <summary>
/// Gets or Sets Quantity
/// </summary>
[DataMember(Name="quantity", EmitDefaultValue=false)]
public int? Quantity { get; set; }
/// <summary>
/// Gets or Sets Date
/// </summary>
[DataMember(Name="date", EmitDefaultValue=false)]
public DateTime? Date { get; private set; }
/// <summary>
/// Gets or Sets UserId
/// </summary>
[DataMember(Name="userId", EmitDefaultValue=false)]
public int? UserId { get; set; }
/// <summary>
/// Gets or Sets LobId
/// </summary>
[DataMember(Name="lobId", EmitDefaultValue=false)]
public int? LobId { get; set; }
/// <summary>
/// Gets or Sets BillingCodeTypeId
/// </summary>
[DataMember(Name="billingCodeTypeId", EmitDefaultValue=false)]
public int? BillingCodeTypeId { get; set; }
/// <summary>
/// Gets or Sets Note
/// </summary>
[DataMember(Name="note", EmitDefaultValue=false)]
public string Note { 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 BillingCode {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" CreateDate: ").Append(CreateDate).Append("\n");
sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n");
sb.Append(" Quantity: ").Append(Quantity).Append("\n");
sb.Append(" Date: ").Append(Date).Append("\n");
sb.Append(" UserId: ").Append(UserId).Append("\n");
sb.Append(" LobId: ").Append(LobId).Append("\n");
sb.Append(" BillingCodeTypeId: ").Append(BillingCodeTypeId).Append("\n");
sb.Append(" Note: ").Append(Note).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 BillingCode);
}
/// <summary>
/// Returns true if BillingCode instances are equal
/// </summary>
/// <param name="other">Instance of BillingCode to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BillingCode other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.CreateDate == other.CreateDate ||
this.CreateDate != null &&
this.CreateDate.Equals(other.CreateDate)
) &&
(
this.ModifyDate == other.ModifyDate ||
this.ModifyDate != null &&
this.ModifyDate.Equals(other.ModifyDate)
) &&
(
this.Quantity == other.Quantity ||
this.Quantity != null &&
this.Quantity.Equals(other.Quantity)
) &&
(
this.Date == other.Date ||
this.Date != null &&
this.Date.Equals(other.Date)
) &&
(
this.UserId == other.UserId ||
this.UserId != null &&
this.UserId.Equals(other.UserId)
) &&
(
this.LobId == other.LobId ||
this.LobId != null &&
this.LobId.Equals(other.LobId)
) &&
(
this.BillingCodeTypeId == other.BillingCodeTypeId ||
this.BillingCodeTypeId != null &&
this.BillingCodeTypeId.Equals(other.BillingCodeTypeId)
) &&
(
this.Note == other.Note ||
this.Note != null &&
this.Note.Equals(other.Note)
);
}
/// <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.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.CreateDate != null)
hash = hash * 59 + this.CreateDate.GetHashCode();
if (this.ModifyDate != null)
hash = hash * 59 + this.ModifyDate.GetHashCode();
if (this.Quantity != null)
hash = hash * 59 + this.Quantity.GetHashCode();
if (this.Date != null)
hash = hash * 59 + this.Date.GetHashCode();
if (this.UserId != null)
hash = hash * 59 + this.UserId.GetHashCode();
if (this.LobId != null)
hash = hash * 59 + this.LobId.GetHashCode();
if (this.BillingCodeTypeId != null)
hash = hash * 59 + this.BillingCodeTypeId.GetHashCode();
if (this.Note != null)
hash = hash * 59 + this.Note.GetHashCode();
return hash;
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using DemoGame.DbObjs;
using log4net;
using NetGore.World;
using SFML.Graphics;
namespace DemoGame.Server
{
/// <summary>
/// Describes a rectangle that describes the area in a Map where spawning will take place.
/// </summary>
[TypeConverter(typeof(MapSpawnRectEditor))]
public struct MapSpawnRect
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
ushort? _height;
ushort? _width;
ushort? _x;
ushort? _y;
/// <summary>
/// Initializes a new instance of the <see cref="MapSpawnRect"/> struct.
/// </summary>
/// <param name="mapSpawnTable">The map spawn table.</param>
public MapSpawnRect(IMapSpawnTable mapSpawnTable)
: this(mapSpawnTable.X, mapSpawnTable.Y, mapSpawnTable.Width, mapSpawnTable.Height)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MapSpawnRect"/> struct.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
public MapSpawnRect(ushort? x, ushort? y, ushort? width, ushort? height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
/// <summary>
/// Gets or sets the height of the rectangle. If null, the rectangle will be stretched to fit the height of the Map.
/// </summary>
[DisplayName("Height")]
[Browsable(true)]
[DefaultValue(null)]
[Description("The height of the spawn rectangle. If null, the rectangle will be stretched to fit the height of the Map.")]
public ushort? Height
{
get { return _height; }
set { _height = value; }
}
/// <summary>
/// Gets or sets the width of the rectangle. If null, the rectangle will be stretched to fit the width of the Map.
/// </summary>
[DisplayName("Width")]
[Browsable(true)]
[DefaultValue(null)]
[Description("The width of the spawn rectangle. If null, the rectangle will be stretched to fit the height of the Map.")]
public ushort? Width
{
get { return _width; }
set { _width = value; }
}
/// <summary>
/// Gets or sets the X co-ordinate of the rectangle. If null, the rectangle will be located at the left side of the Map.
/// </summary>
[DisplayName("X")]
[Browsable(true)]
[DefaultValue(null)]
[Description(
"The X-coordinate of the spawn rectangle. If null, the rectangle will be located at the left side of the Map.")]
public ushort? X
{
get { return _x; }
set { _x = value; }
}
/// <summary>
/// Gets or sets the Y co-ordinate of the rectangle. If null, the rectangle will be located at the top side of the Map.
/// </summary>
[DisplayName("Y")]
[Browsable(true)]
[DefaultValue(null)]
[Description("The Y-coordinate of the spawn rectangle. If null, the rectangle will be located at the top side of the Map."
)]
public ushort? Y
{
get { return _y; }
set { _y = value; }
}
/// <summary>
/// Equalses the specified other.
/// </summary>
/// <param name="other">The other.</param>
public bool Equals(MapSpawnRect other)
{
return other.X.Equals(X) && other.Y.Equals(Y) && other.Width.Equals(Width) && other.Height.Equals(Height);
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <returns>
/// true if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
/// <param name="obj">Another object to compare to.</param>
public override bool Equals(object obj)
{
return obj is MapSpawnRect && this == (MapSpawnRect)obj;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>
/// A 32-bit signed integer that is the hash code for this instance.
/// </returns>
public override int GetHashCode()
{
unchecked
{
var result = (X.HasValue ? X.Value.GetHashCode() : 0);
result = (result * 397) ^ (Y.HasValue ? Y.Value.GetHashCode() : 0);
result = (result * 397) ^ (Width.HasValue ? Width.Value.GetHashCode() : 0);
result = (result * 397) ^ (Height.HasValue ? Height.Value.GetHashCode() : 0);
return result;
}
}
/// <summary>
/// Gets the string to use for a nullable ushort.
/// </summary>
/// <param name="value">The value to get the string for.</param>
/// <returns>The string to use for the <paramref name="value"/>.</returns>
static string GetString(ushort? value)
{
const string nullStr = "?";
if (!value.HasValue)
return nullStr;
return value.Value.ToString();
}
/// <summary>
/// Gets the <see cref="MapSpawnRect"/> as a <see cref="Rectangle"/>.
/// </summary>
/// <param name="map">The <see cref="IMap"/> used to resolve any null values.</param>
/// <returns>The <see cref="MapSpawnRect"/> as a <see cref="Rectangle"/>.</returns>
public Rectangle ToRectangle(IMap map)
{
int x = X.HasValue ? (int)X.Value : 0;
int y = Y.HasValue ? (int)Y.Value : 0;
int width = Width.HasValue ? (int)Width.Value : (int)Math.Round(map.Width) - x;
int height = Height.HasValue ? (int)Height.Value : (int)Math.Round(map.Height) - y;
const string errmsgMoved =
"A spawn rectangle was being drawn off of the map." +
" Its previous {0} location was {1} and has been moved to {2}.";
const string errmsgSize =
"A spawn rectangle was to big on the {0} axis" + " and has been resized to fit into the map.";
if (x > map.Width)
{
int t = x;
x = (int)(map.Height - width);
log.FatalFormat(errmsgMoved, "X", t, x);
Debug.Fail(string.Format(errmsgMoved, "X", t, x));
}
if (x < 0)
{
log.FatalFormat(errmsgMoved, "X", x, 0);
Debug.Fail(string.Format(errmsgMoved, "X", x, 0));
x = 0;
}
if (y > map.Height)
{
int t = y;
y = (int)(map.Height - height);
log.FatalFormat(errmsgMoved, "Y", t, y);
Debug.Fail(string.Format(errmsgMoved, "Y", t, y));
}
if (y < 0)
{
log.FatalFormat(errmsgMoved, "X", x, 0);
Debug.Fail(string.Format(errmsgMoved, "X", x, 0));
y = 0;
}
if ((x + width) > map.Width)
{
width = (int)(map.Width - x);
log.FatalFormat(errmsgSize, "X");
Debug.Fail(string.Format(errmsgSize, "X"));
}
if ((y + height) > map.Height)
{
height = (int)(map.Height - y);
log.FatalFormat(errmsgSize, "Y");
Debug.Fail(string.Format(errmsgSize, "Y"));
}
return new Rectangle(x, y, width, height);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
return string.Format("({0},{1})x({2},{3})", GetString(X), GetString(Y), GetString(Width), GetString(Height));
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="l">The first argument.</param>
/// <param name="r">The second argument.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(MapSpawnRect l, MapSpawnRect r)
{
return (l.X == r.X) && (l.Y == r.Y) && (l.Width == r.Width) && (l.Height == r.Height);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="l">The first argument.</param>
/// <param name="r">The second argument.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(MapSpawnRect l, MapSpawnRect r)
{
return !(l == r);
}
}
}
| |
// 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.Diagnostics;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Semantics
{
internal partial class CMemberLookupResults
{
public partial class CMethodIterator
{
private SymbolLoader _pSymbolLoader;
private CSemanticChecker _pSemanticChecker;
// Inputs.
private AggregateType _pCurrentType;
private MethodOrPropertySymbol _pCurrentSym;
private AggregateDeclaration _pContext;
private TypeArray _pContainingTypes;
private CType _pQualifyingType;
private Name _pName;
private int _nArity;
private symbmask_t _mask;
private EXPRFLAG _flags;
// Internal state.
private int _nCurrentTypeCount;
private bool _bIsCheckingInstanceMethods;
private bool _bAtEnd;
private bool _bAllowBogusAndInaccessible;
// Flags for the current sym.
private bool _bCurrentSymIsBogus;
private bool _bCurrentSymIsInaccessible;
// if Extension can be part of the results that are returned by the iterator
// this may be false if an applicable instance method was found by bindgrptoArgs
private bool _bcanIncludeExtensionsInResults;
public CMethodIterator(CSemanticChecker checker, SymbolLoader symLoader, Name name, TypeArray containingTypes, CType @object, CType qualifyingType, AggregateDeclaration context, bool allowBogusAndInaccessible, bool allowExtensionMethods, int arity, EXPRFLAG flags, symbmask_t mask)
{
Debug.Assert(name != null);
Debug.Assert(symLoader != null);
Debug.Assert(checker != null);
Debug.Assert(containingTypes != null);
_pSemanticChecker = checker;
_pSymbolLoader = symLoader;
_pCurrentType = null;
_pCurrentSym = null;
_pName = name;
_pContainingTypes = containingTypes;
_pQualifyingType = qualifyingType;
_pContext = context;
_bAllowBogusAndInaccessible = allowBogusAndInaccessible;
_nArity = arity;
_flags = flags;
_mask = mask;
_nCurrentTypeCount = 0;
_bIsCheckingInstanceMethods = true;
_bAtEnd = false;
_bCurrentSymIsBogus = false;
_bCurrentSymIsInaccessible = false;
_bcanIncludeExtensionsInResults = allowExtensionMethods;
}
public MethodOrPropertySymbol GetCurrentSymbol()
{
return _pCurrentSym;
}
public AggregateType GetCurrentType()
{
return _pCurrentType;
}
public bool IsCurrentSymbolInaccessible()
{
return _bCurrentSymIsInaccessible;
}
public bool IsCurrentSymbolBogus()
{
return _bCurrentSymIsBogus;
}
public bool MoveNext(bool canIncludeExtensionsInResults)
{
if (_bcanIncludeExtensionsInResults)
{
_bcanIncludeExtensionsInResults = canIncludeExtensionsInResults;
}
if (_bAtEnd)
{
return false;
}
if (_pCurrentType == null) // First guy.
{
if (_pContainingTypes.Count == 0)
{
// No instance methods, only extensions.
_bIsCheckingInstanceMethods = false;
_bAtEnd = true;
return false;
}
else
{
if (!FindNextTypeForInstanceMethods())
{
// No instance or extensions.
_bAtEnd = true;
return false;
}
}
}
if (!FindNextMethod())
{
_bAtEnd = true;
return false;
}
return true;
}
public bool AtEnd()
{
return _pCurrentSym == null;
}
private CSemanticChecker GetSemanticChecker()
{
return _pSemanticChecker;
}
private SymbolLoader GetSymbolLoader()
{
return _pSymbolLoader;
}
public bool CanUseCurrentSymbol()
{
_bCurrentSymIsInaccessible = false;
_bCurrentSymIsBogus = false;
// Make sure that whether we're seeing a ctor is consistent with the flag.
// The only properties we handle are indexers.
if (_mask == symbmask_t.MASK_MethodSymbol && (
0 == (_flags & EXPRFLAG.EXF_CTOR) != !((MethodSymbol)_pCurrentSym).IsConstructor() ||
0 == (_flags & EXPRFLAG.EXF_OPERATOR) != !((MethodSymbol)_pCurrentSym).isOperator) ||
_mask == symbmask_t.MASK_PropertySymbol && !(_pCurrentSym is IndexerSymbol))
{
// Get the next symbol.
return false;
}
// If our arity is non-0, we must match arity with this symbol.
if (_nArity > 0)
{
if (_mask == symbmask_t.MASK_MethodSymbol && ((MethodSymbol)_pCurrentSym).typeVars.Count != _nArity)
{
return false;
}
}
// If this guy's not callable, no good.
if (!ExpressionBinder.IsMethPropCallable(_pCurrentSym, (_flags & EXPRFLAG.EXF_USERCALLABLE) != 0))
{
return false;
}
// Check access.
if (!GetSemanticChecker().CheckAccess(_pCurrentSym, _pCurrentType, _pContext, _pQualifyingType))
{
// Sym is not accessible. However, if we're allowing inaccessible, then let it through and mark it.
if (_bAllowBogusAndInaccessible)
{
_bCurrentSymIsInaccessible = true;
}
else
{
return false;
}
}
// Check bogus.
if (CSemanticChecker.CheckBogus(_pCurrentSym))
{
// Sym is bogus, but if we're allow it, then let it through and mark it.
if (_bAllowBogusAndInaccessible)
{
_bCurrentSymIsBogus = true;
}
else
{
return false;
}
}
return _bIsCheckingInstanceMethods;
}
private bool FindNextMethod()
{
while (true)
{
if (_pCurrentSym == null)
{
_pCurrentSym = GetSymbolLoader().LookupAggMember(
_pName, _pCurrentType.getAggregate(), _mask) as MethodOrPropertySymbol;
}
else
{
_pCurrentSym = GetSymbolLoader().LookupNextSym(
_pCurrentSym, _pCurrentType.getAggregate(), _mask) as MethodOrPropertySymbol;
}
// If we couldn't find a sym, we look up the type chain and get the next type.
if (_pCurrentSym == null)
{
if (_bIsCheckingInstanceMethods)
{
if (!FindNextTypeForInstanceMethods() && _bcanIncludeExtensionsInResults)
{
// We didn't find any more instance methods, set us into extension mode.
_bIsCheckingInstanceMethods = false;
}
else if (_pCurrentType == null && !_bcanIncludeExtensionsInResults)
{
return false;
}
else
{
// Found an instance method.
continue;
}
}
continue;
}
// Note that we do not filter the current symbol for the user. They must do that themselves.
// This is because for instance, BindGrpToArgs wants to filter on arguments before filtering
// on bogosity.
// If we're here, we're good to go.
break;
}
return true;
}
private bool FindNextTypeForInstanceMethods()
{
// Otherwise, search through other types listed as well as our base class.
if (_pContainingTypes.Count > 0)
{
if (_nCurrentTypeCount >= _pContainingTypes.Count)
{
// No more types to check.
_pCurrentType = null;
}
else
{
_pCurrentType = _pContainingTypes[_nCurrentTypeCount++] as AggregateType;
}
}
else
{
// We have no more types to consider, so check out the base class.
_pCurrentType = _pCurrentType.GetBaseClass();
}
return _pCurrentType != null;
}
}
}
}
| |
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
/*
* 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.Reflection;
namespace OpenSim.Region.CoreModules.Avatar.InstantMessage
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "InstantMessageModule")]
public class InstantMessageModule : ISharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private readonly List<Scene> m_scenes = new List<Scene>();
/// <value>
/// Is this module enabled?
/// </value>
private bool m_enabled = false;
#region Region Module interface
private IMessageTransferModule m_TransferModule = null;
public string Name
{
get { return "InstantMessageModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void AddRegion(Scene scene)
{
if (!m_enabled)
return;
lock (m_scenes)
{
if (!m_scenes.Contains(scene))
{
m_scenes.Add(scene);
scene.EventManager.OnClientConnect += OnClientConnect;
scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage;
}
}
}
public void Close()
{
}
public void Initialise(IConfigSource config)
{
if (config.Configs["Messaging"] != null)
{
if (config.Configs["Messaging"].GetString(
"InstantMessageModule", "InstantMessageModule") !=
"InstantMessageModule")
return;
}
m_enabled = true;
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
if (!m_enabled)
return;
if (m_TransferModule == null)
{
m_TransferModule =
scene.RequestModuleInterface<IMessageTransferModule>();
if (m_TransferModule == null)
{
m_log.Error("[INSTANT MESSAGE]: No message transfer module, IM will not work!");
scene.EventManager.OnClientConnect -= OnClientConnect;
scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage;
m_scenes.Clear();
m_enabled = false;
}
}
}
public void RemoveRegion(Scene scene)
{
if (!m_enabled)
return;
lock (m_scenes)
{
m_scenes.Remove(scene);
}
}
private void OnClientConnect(IClientCore client)
{
IClientIM clientIM;
if (client.TryGet(out clientIM))
{
clientIM.OnInstantMessage += OnInstantMessage;
}
}
#endregion Region Module interface
public void OnInstantMessage(IClientAPI client, GridInstantMessage im)
{
byte dialog = im.dialog;
if (dialog != (byte)InstantMessageDialog.MessageFromAgent
&& dialog != (byte)InstantMessageDialog.StartTyping
&& dialog != (byte)InstantMessageDialog.StopTyping
&& dialog != (byte)InstantMessageDialog.BusyAutoResponse
&& dialog != (byte)InstantMessageDialog.MessageFromObject)
{
return;
}
if (m_TransferModule != null)
{
if (client != null)
im.fromAgentName = client.FirstName + " " + client.LastName;
m_TransferModule.SendInstantMessage(im,
delegate(bool success)
{
if (dialog == (uint)InstantMessageDialog.StartTyping ||
dialog == (uint)InstantMessageDialog.StopTyping ||
dialog == (uint)InstantMessageDialog.MessageFromObject)
{
return;
}
if ((client != null) && !success)
{
client.SendInstantMessage(
new GridInstantMessage(
null, new UUID(im.fromAgentID), "System",
new UUID(im.toAgentID),
(byte)InstantMessageDialog.BusyAutoResponse,
"Unable to send instant message. " +
"User is not logged in.", false,
new Vector3()));
}
}
);
}
}
/// <summary>
///
/// </summary>
/// <param name="msg"></param>
private void OnGridInstantMessage(GridInstantMessage msg)
{
// Just call the Text IM handler above
// This event won't be raised unless we have that agent,
// so we can depend on the above not trying to send
// via grid again
//
OnInstantMessage(null, msg);
}
}
}
| |
// 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.Runtime.InteropServices;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// Managed SNI proxy implementation. Contains many SNI entry points used by SqlClient.
/// </summary>
internal class SNIProxy
{
public static readonly SNIProxy Singleton = new SNIProxy();
/// <summary>
/// Terminate SNI
/// </summary>
public void Terminate()
{
}
/// <summary>
/// Enable MARS support on a connection
/// </summary>
/// <param name="handle">Connection handle</param>
/// <returns>SNI error code</returns>
public uint EnableMars(SNIHandle handle)
{
if (SNIMarsManager.Singleton.CreateMarsConnection(handle) == TdsEnums.SNI_SUCCESS_IO_PENDING)
{
return TdsEnums.SNI_SUCCESS;
}
return TdsEnums.SNI_ERROR;
}
/// <summary>
/// Enable SSL on a connection
/// </summary>
/// <param name="handle">Connection handle</param>
/// <returns>SNI error code</returns>
public uint EnableSsl(SNIHandle handle, uint options)
{
try
{
return handle.EnableSsl(options);
}
catch (Exception e)
{
return SNICommon.ReportSNIError(SNIProviders.SSL_PROV, SNICommon.HandshakeFailureError, e);
}
}
/// <summary>
/// Disable SSL on a connection
/// </summary>
/// <param name="handle">Connection handle</param>
/// <returns>SNI error code</returns>
public uint DisableSsl(SNIHandle handle)
{
handle.DisableSsl();
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Generate SSPI context
/// </summary>
/// <param name="handle">SNI connection handle</param>
/// <param name="receivedBuff">Receive buffer</param>
/// <param name="receivedLength">Received length</param>
/// <param name="sendBuff">Send buffer</param>
/// <param name="sendLength">Send length</param>
/// <param name="serverName">Service Principal Name buffer</param>
/// <param name="serverNameLength">Length of Service Principal Name</param>
/// <returns>SNI error code</returns>
public uint GenSspiClientContext(SNIHandle handle, byte[] receivedBuff, uint receivedLength, byte[] sendBuff, ref uint sendLength, byte[] serverName, uint serverNameLength)
{
throw new PlatformNotSupportedException();
}
/// <summary>
/// Initialize SSPI
/// </summary>
/// <param name="maxLength">Max length of SSPI packet</param>
/// <returns>SNI error code</returns>
public uint InitializeSspiPackage(ref uint maxLength)
{
throw new PlatformNotSupportedException();
}
/// <summary>
/// Set connection buffer size
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="bufferSize">Buffer size</param>
/// <returns>SNI error code</returns>
public uint SetConnectionBufferSize(SNIHandle handle, uint bufferSize)
{
handle.SetBufferSize((int)bufferSize);
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Get packet data
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="inBuff">Buffer</param>
/// <param name="dataSize">Data size</param>
/// <returns>SNI error status</returns>
public uint PacketGetData(SNIPacket packet, byte[] inBuff, ref uint dataSize)
{
int dataSizeInt = 0;
packet.GetData(inBuff, ref dataSizeInt);
dataSize = (uint)dataSizeInt;
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Read synchronously
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">SNI packet</param>
/// <param name="timeout">Timeout</param>
/// <returns>SNI error status</returns>
public uint ReadSyncOverAsync(SNIHandle handle, out SNIPacket packet, int timeout)
{
return handle.Receive(out packet, timeout);
}
/// <summary>
/// Get SNI connection ID
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="clientConnectionId">Client connection ID</param>
/// <returns>SNI error status</returns>
public uint GetConnectionId(SNIHandle handle, ref Guid clientConnectionId)
{
clientConnectionId = handle.ConnectionId;
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Send a packet
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">SNI packet</param>
/// <param name="sync">true if synchronous, false if asynchronous</param>
/// <returns>SNI error status</returns>
public uint WritePacket(SNIHandle handle, SNIPacket packet, bool sync)
{
if (sync)
{
return handle.Send(packet.Clone());
}
else
{
return handle.SendAsync(packet.Clone());
}
}
/// <summary>
/// Reset a packet
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="write">true if packet is for write</param>
/// <param name="packet">SNI packet</param>
public void PacketReset(SNIHandle handle, bool write, SNIPacket packet)
{
packet.Reset();
}
/// <summary>
/// Create a SNI connection handle
/// </summary>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="fullServerName">Full server name from connection string</param>
/// <param name="ignoreSniOpenTimeout">Ignore open timeout</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="instanceName">Instance name</param>
/// <param name="spnBuffer">SPN</param>
/// <param name="flushCache">Flush packet cache</param>
/// <param name="async">Asynchronous connection</param>
/// <param name="parallel">Attempt parallel connects</param>
/// <returns>SNI handle</returns>
public SNIHandle CreateConnectionHandle(object callbackObject, string fullServerName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, byte[] spnBuffer, bool flushCache, bool async, bool parallel)
{
instanceName = new byte[1];
instanceName[0] = 0;
string[] serverNameParts = fullServerName.Split(':');
if (serverNameParts.Length > 2)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.InvalidConnStringError, string.Empty);
return null;
}
// Default to using tcp if no protocol is provided
if (serverNameParts.Length == 1)
{
return CreateTcpHandle(serverNameParts[0], timerExpire, callbackObject, parallel);
}
switch (serverNameParts[0])
{
case TdsEnums.TCP:
return CreateTcpHandle(serverNameParts[1], timerExpire, callbackObject, parallel);
case TdsEnums.NP:
return CreateNpHandle(serverNameParts[1], timerExpire, callbackObject, parallel);
default:
if (parallel)
{
SNICommon.ReportSNIError(SNIProviders.INVALID_PROV, 0, SNICommon.MultiSubnetFailoverWithNonTcpProtocol, string.Empty);
}
else
{
SNICommon.ReportSNIError(SNIProviders.INVALID_PROV, 0, SNICommon.ProtocolNotSupportedError, string.Empty);
}
return null;
}
}
/// <summary>
/// Creates an SNITCPHandle object
/// </summary>
/// <param name="fullServerName">Server string. May contain a comma delimited port number.</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="parallel">Should MultiSubnetFailover be used</param>
/// <returns>SNITCPHandle</returns>
private SNITCPHandle CreateTcpHandle(string fullServerName, long timerExpire, object callbackObject, bool parallel)
{
// TCP Format:
// tcp:<host name>\<instance name>
// tcp:<host name>,<TCP/IP port number>
int portNumber = 1433;
string[] serverAndPortParts = fullServerName.Split(',');
if (serverAndPortParts.Length == 2)
{
try
{
portNumber = ushort.Parse(serverAndPortParts[1]);
}
catch (Exception e)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InvalidConnStringError, e);
return null;
}
}
else if (serverAndPortParts.Length > 2)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, 0, SNICommon.InvalidConnStringError, string.Empty);
return null;
}
return new SNITCPHandle(serverAndPortParts[0], portNumber, timerExpire, callbackObject, parallel);
}
/// <summary>
/// Creates an SNINpHandle object
/// </summary>
/// <param name="fullServerName">Server string representing a UNC pipe path.</param>
/// <param name="timerExpire">Timer expiration</param>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="parallel">Should MultiSubnetFailover be used. Only returns an error for named pipes.</param>
/// <returns>SNINpHandle</returns>
private SNINpHandle CreateNpHandle(string fullServerName, long timerExpire, object callbackObject, bool parallel)
{
if (parallel)
{
SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.MultiSubnetFailoverWithNonTcpProtocol, string.Empty);
return null;
}
if(fullServerName.Length == 0 || fullServerName.Contains("/")) // Pipe paths only allow back slashes
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.NP_PROV, 0, SNICommon.InvalidConnStringError, string.Empty);
return null;
}
string serverName, pipeName;
if (!fullServerName.Contains(@"\"))
{
serverName = fullServerName;
pipeName = SNINpHandle.DefaultPipePath;
}
else
{
try
{
Uri pipeURI = new Uri(fullServerName);
string resourcePath = pipeURI.AbsolutePath;
string pipeToken = "/pipe/";
if (!resourcePath.StartsWith(pipeToken))
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.NP_PROV, 0, SNICommon.InvalidConnStringError, string.Empty);
return null;
}
pipeName = resourcePath.Substring(pipeToken.Length);
serverName = pipeURI.Host;
}
catch(UriFormatException)
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.NP_PROV, 0, SNICommon.InvalidConnStringError, string.Empty);
return null;
}
}
return new SNINpHandle(serverName, pipeName, timerExpire, callbackObject);
}
/// <summary>
/// Create MARS handle
/// </summary>
/// <param name="callbackObject">Asynchronous I/O callback object</param>
/// <param name="physicalConnection">SNI connection handle</param>
/// <param name="defaultBufferSize">Default buffer size</param>
/// <param name="async">Asynchronous connection</param>
/// <returns>SNI error status</returns>
public SNIHandle CreateMarsHandle(object callbackObject, SNIHandle physicalConnection, int defaultBufferSize, bool async)
{
SNIMarsConnection connection = SNIMarsManager.Singleton.GetConnection(physicalConnection);
return connection.CreateSession(callbackObject, async);
}
/// <summary>
/// Read packet asynchronously
/// </summary>
/// <param name="handle">SNI handle</param>
/// <param name="packet">Packet</param>
/// <returns>SNI error status</returns>
public uint ReadAsync(SNIHandle handle, ref SNIPacket packet)
{
packet = new SNIPacket(null);
return handle.ReceiveAsync(ref packet);
}
/// <summary>
/// Set packet data
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="data">Data</param>
/// <param name="length">Length</param>
public void PacketSetData(SNIPacket packet, byte[] data, int length)
{
packet.SetData(data, length);
}
/// <summary>
/// Release packet
/// </summary>
/// <param name="packet">SNI packet</param>
public void PacketRelease(SNIPacket packet)
{
packet.Release();
}
/// <summary>
/// Check SNI handle connection
/// </summary>
/// <param name="handle"></param>
/// <returns>SNI error status</returns>
public uint CheckConnection(SNIHandle handle)
{
return handle.CheckConnection();
}
/// <summary>
/// Get last SNI error on this thread
/// </summary>
/// <returns></returns>
public SNIError GetLastError()
{
return SNILoadHandle.SingletonInstance.LastError;
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: MemoryFailPoint
**
**
** Provides a way for an app to not start an operation unless
** there's a reasonable chance there's enough memory
** available for the operation to succeed.
**
**
===========================================================*/
using System;
using System.IO;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Security.Permissions;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
/*
This class allows an application to fail before starting certain
activities. The idea is to fail early instead of failing in the middle
of some long-running operation to increase the survivability of the
application and ensure you don't have to write tricky code to handle an
OOM anywhere in your app's code (which implies state corruption, meaning you
should unload the appdomain, if you have a transacted environment to ensure
rollback of individual transactions). This is an incomplete tool to attempt
hoisting all your OOM failures from anywhere in your worker methods to one
particular point where it is easier to handle an OOM failure, and you can
optionally choose to not start a workitem if it will likely fail. This does
not help the performance of your code directly (other than helping to avoid
AD unloads). The point is to avoid starting work if it is likely to fail.
The Enterprise Services team has used these memory gates effectively in the
unmanaged world for a decade.
In Whidbey, we will simply check to see if there is enough memory available
in the OS's page file & attempt to ensure there might be enough space free
within the process's address space (checking for address space fragmentation
as well). We will not commit or reserve any memory. To avoid ----s with
other threads using MemoryFailPoints, we'll also keep track of a
process-wide amount of memory "reserved" via all currently-active
MemoryFailPoints. This has two problems:
1) This can account for memory twice. If a thread creates a
MemoryFailPoint for 100 MB then allocates 99 MB, we'll see 99 MB
less free memory and 100 MB less reserved memory. Yet, subtracting
off the 100 MB is necessary because the thread may not have started
allocating memory yet. Disposing of this class immediately after
front-loaded allocations have completed is a great idea.
2) This is still vulnerable to ----s with other threads that don't use
MemoryFailPoints.
So this class is far from perfect. But it may be good enough to
meaningfully reduce the frequency of OutOfMemoryExceptions in managed apps.
In Orcas or later, we might allocate some memory from the OS and add it
to a allocation context for this thread. Obviously, at that point we need
some way of conveying when we release this block of memory. So, we
implemented IDisposable on this type in Whidbey and expect all users to call
this from within a using block to provide lexical scope for their memory
usage. The call to Dispose (implicit with the using block) will give us an
opportunity to release this memory, perhaps. We anticipate this will give
us the possibility of a more effective design in a future version.
In Orcas, we may also need to differentiate between allocations that would
go into the normal managed heap vs. the large object heap, or we should
consider checking for enough free space in both locations (with any
appropriate adjustments to ensure the memory is contiguous).
*/
namespace System.Runtime
{
public sealed class MemoryFailPoint : CriticalFinalizerObject, IDisposable
{
// Find the top section of user mode memory. Avoid the last 64K.
// Windows reserves that block for the kernel, apparently, and doesn't
// let us ask about that memory. But since we ask for memory in 1 MB
// chunks, we don't have to special case this. Also, we need to
// deal with 32 bit machines in 3 GB mode.
// Using Win32's GetSystemInfo should handle all this for us.
private static readonly ulong TopOfMemory;
// Walking the address space is somewhat expensive, taking around half
// a millisecond. Doing that per transaction limits us to a max of
// ~2000 transactions/second. Instead, let's do this address space
// walk once every 10 seconds, or when we will likely fail. This
// amortization scheme can reduce the cost of a memory gate by about
// a factor of 100.
private static long hiddenLastKnownFreeAddressSpace = 0;
private static long hiddenLastTimeCheckingAddressSpace = 0;
private const int CheckThreshold = 10 * 1000; // 10 seconds
private static long LastKnownFreeAddressSpace
{
get { return Volatile.Read(ref hiddenLastKnownFreeAddressSpace); }
set { Volatile.Write(ref hiddenLastKnownFreeAddressSpace, value); }
}
private static long AddToLastKnownFreeAddressSpace(long addend)
{
return Interlocked.Add(ref hiddenLastKnownFreeAddressSpace, addend);
}
private static long LastTimeCheckingAddressSpace
{
get { return Volatile.Read(ref hiddenLastTimeCheckingAddressSpace); }
set { Volatile.Write(ref hiddenLastTimeCheckingAddressSpace, value); }
}
// When allocating memory segment by segment, we've hit some cases
// where there are only 22 MB of memory available on the machine,
// we need 1 16 MB segment, and the OS does not succeed in giving us
// that memory. Reasons for this could include:
// 1) The GC does allocate memory when doing a collection.
// 2) Another process on the machine could grab that memory.
// 3) Some other part of the runtime might grab this memory.
// If we build in a little padding, we can help protect
// ourselves against some of these cases, and we want to err on the
// conservative side with this class.
private const int LowMemoryFudgeFactor = 16 << 20;
// Round requested size to a 16MB multiple to have a better granularity
// when checking for available memory.
private const int MemoryCheckGranularity = 16;
// Note: This may become dynamically tunable in the future.
// Also note that we can have different segment sizes for the normal vs.
// large object heap. We currently use the max of the two.
private static readonly ulong GCSegmentSize;
// For multi-threaded workers, we want to ensure that if two workers
// use a MemoryFailPoint at the same time, and they both succeed, that
// they don't trample over each other's memory. Keep a process-wide
// count of "reserved" memory, and decrement this in Dispose and
// in the critical finalizer. See
// SharedStatics.MemoryFailPointReservedMemory
private ulong _reservedMemory; // The size of this request (from user)
private bool _mustSubtractReservation; // Did we add data to SharedStatics?
[System.Security.SecuritySafeCritical] // auto-generated
static MemoryFailPoint()
{
GetMemorySettings(out GCSegmentSize, out TopOfMemory);
}
// We can remove this link demand in a future version - we will
// have scenarios for this in partial trust in the future, but
// we're doing this just to restrict this in case the code below
// is somehow incorrect.
[System.Security.SecurityCritical] // auto-generated_required
[ResourceExposure(ResourceScope.None)] // Just gives info about free mem.
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
public MemoryFailPoint(int sizeInMegabytes)
{
if (sizeInMegabytes <= 0)
throw new ArgumentOutOfRangeException("sizeInMegabytes", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.EndContractBlock();
ulong size = ((ulong)sizeInMegabytes) << 20;
_reservedMemory = size;
#if FEATURE_PAL
// Allow the fail point to succeed, unless we have a
// platform-independent way of checking the amount of free memory.
// We could allocate a byte[] then discard it, but we don't want
// to generate garbage like that.
#else
// Check to see that we both have enough memory on the system
// and that we have enough room within the user section of the
// process's address space. Also, we need to use the GC segment
// size, not the amount of memory the user wants to allocate.
// Consider correcting this to reflect free memory within the GC
// heap, and to check both the normal & large object heaps.
ulong segmentSize = (ulong) (Math.Ceiling((double)size / GCSegmentSize) * GCSegmentSize);
if (segmentSize >= TopOfMemory)
throw new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint_TooBig"));
ulong requestedSizeRounded = (ulong)(Math.Ceiling((double)sizeInMegabytes / MemoryCheckGranularity) * MemoryCheckGranularity);
//re-convert into bytes
requestedSizeRounded <<= 20;
ulong availPageFile = 0; // available VM (physical + page file)
ulong totalAddressSpaceFree = 0; // non-contiguous free address space
// Check for available memory, with 2 attempts at getting more
// memory.
// Stage 0: If we don't have enough, trigger a GC.
// Stage 1: If we don't have enough, try growing the swap file.
// Stage 2: Update memory state, then fail or leave loop.
//
// (In the future, we could consider adding another stage after
// Stage 0 to run finalizers. However, before doing that make sure
// that we could abort this constructor when we call
// GC.WaitForPendingFinalizers, noting that this method uses a CER
// so it can't be aborted, and we have a critical finalizer. It
// would probably work, but do some thinking first.)
for(int stage = 0; stage < 3; stage++) {
CheckForAvailableMemory(out availPageFile, out totalAddressSpaceFree);
// If we have enough room, then skip some stages.
// Note that multiple threads can still ---- on our free chunk
// of address space, which can't be easily solved.
ulong reserved = SharedStatics.MemoryFailPointReservedMemory;
ulong segPlusReserved = segmentSize + reserved;
bool overflow = segPlusReserved < segmentSize || segPlusReserved < reserved;
bool needPageFile = availPageFile < (requestedSizeRounded + reserved + LowMemoryFudgeFactor) || overflow;
bool needAddressSpace = totalAddressSpaceFree < segPlusReserved || overflow;
// Ensure our cached amount of free address space is not stale.
long now = Environment.TickCount; // Handle wraparound.
if ((now > LastTimeCheckingAddressSpace + CheckThreshold || now < LastTimeCheckingAddressSpace) ||
LastKnownFreeAddressSpace < (long) segmentSize) {
CheckForFreeAddressSpace(segmentSize, false);
}
bool needContiguousVASpace = (ulong) LastKnownFreeAddressSpace < segmentSize;
BCLDebug.Trace("MEMORYFAILPOINT", "MemoryFailPoint: Checking for {0} MB, for allocation size of {1} MB, stage {9}. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved via process's MemoryFailPoints: {8} MB",
segmentSize >> 20, sizeInMegabytes, needPageFile,
needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved, stage);
if (!needPageFile && !needAddressSpace && !needContiguousVASpace)
break;
switch(stage) {
case 0:
// The GC will release empty segments to the OS. This will
// relieve us from having to guess whether there's
// enough memory in either GC heap, and whether
// internal fragmentation will prevent those
// allocations from succeeding.
GC.Collect();
continue;
case 1:
// Do this step if and only if the page file is too small.
if (!needPageFile)
continue;
// Attempt to grow the OS's page file. Note that we ignore
// any allocation routines from the host intentionally.
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
// This shouldn't overflow due to the if clauses above.
UIntPtr numBytes = new UIntPtr(segmentSize);
unsafe {
void * pMemory = Win32Native.VirtualAlloc(null, numBytes, Win32Native.MEM_COMMIT, Win32Native.PAGE_READWRITE);
if (pMemory != null) {
bool r = Win32Native.VirtualFree(pMemory, UIntPtr.Zero, Win32Native.MEM_RELEASE);
if (!r)
__Error.WinIOError();
}
}
}
continue;
case 2:
// The call to CheckForAvailableMemory above updated our
// state.
if (needPageFile || needAddressSpace) {
InsufficientMemoryException e = new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint"));
#if _DEBUG
e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
needPageFile, needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved);
#endif
throw e;
}
if (needContiguousVASpace) {
InsufficientMemoryException e = new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint_VAFrag"));
#if _DEBUG
e.Data["MemFailPointState"] = new MemoryFailPointState(sizeInMegabytes, segmentSize,
needPageFile, needAddressSpace, needContiguousVASpace,
availPageFile >> 20, totalAddressSpaceFree >> 20,
LastKnownFreeAddressSpace >> 20, reserved);
#endif
throw e;
}
break;
default:
Contract.Assert(false, "Fell through switch statement!");
break;
}
}
// Success - we have enough room the last time we checked.
// Now update our shared state in a somewhat atomic fashion
// and handle a simple ---- with other MemoryFailPoint instances.
AddToLastKnownFreeAddressSpace(-((long) size));
if (LastKnownFreeAddressSpace < 0)
CheckForFreeAddressSpace(segmentSize, true);
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
SharedStatics.AddMemoryFailPointReservation((long) size);
_mustSubtractReservation = true;
}
#endif // FEATURE_PAL
}
#if !FEATURE_PAL
[System.Security.SecurityCritical] // auto-generated
private static void CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree)
{
bool r;
Win32Native.MEMORYSTATUSEX memory = new Win32Native.MEMORYSTATUSEX();
r = Win32Native.GlobalMemoryStatusEx(memory);
if (!r)
__Error.WinIOError();
availPageFile = memory.availPageFile;
totalAddressSpaceFree = memory.availVirtual;
//Console.WriteLine("Memory gate: Mem load: {0}% Available memory (physical + page file): {1} MB Total free address space: {2} MB GC Heap: {3} MB", memory.memoryLoad, memory.availPageFile >> 20, memory.availVirtual >> 20, GC.GetTotalMemory(true) >> 20);
}
// Based on the shouldThrow parameter, this will throw an exception, or
// returns whether there is enough space. In all cases, we update
// our last known free address space, hopefully avoiding needing to
// probe again.
[System.Security.SecurityCritical] // auto-generated
private static unsafe bool CheckForFreeAddressSpace(ulong size, bool shouldThrow)
{
// Start walking the address space at 0. VirtualAlloc may wrap
// around the address space. We don't need to find the exact
// pages that VirtualAlloc would return - we just need to
// know whether VirtualAlloc could succeed.
ulong freeSpaceAfterGCHeap = MemFreeAfterAddress(null, size);
BCLDebug.Trace("MEMORYFAILPOINT", "MemoryFailPoint: Checked for free VA space. Found enough? {0} Asked for: {1} Found: {2}", (freeSpaceAfterGCHeap >= size), size, freeSpaceAfterGCHeap);
// We may set these without taking a lock - I don't believe
// this will hurt, as long as we never increment this number in
// the Dispose method. If we do an extra bit of checking every
// once in a while, but we avoid taking a lock, we may win.
LastKnownFreeAddressSpace = (long) freeSpaceAfterGCHeap;
LastTimeCheckingAddressSpace = Environment.TickCount;
if (freeSpaceAfterGCHeap < size && shouldThrow)
throw new InsufficientMemoryException(Environment.GetResourceString("InsufficientMemory_MemFailPoint_VAFrag"));
return freeSpaceAfterGCHeap >= size;
}
// Returns the amount of consecutive free memory available in a block
// of pages. If we didn't have enough address space, we still return
// a positive value < size, to help potentially avoid the overhead of
// this check if we use a MemoryFailPoint with a smaller size next.
[System.Security.SecurityCritical] // auto-generated
private static unsafe ulong MemFreeAfterAddress(void * address, ulong size)
{
if (size >= TopOfMemory)
return 0;
ulong largestFreeRegion = 0;
Win32Native.MEMORY_BASIC_INFORMATION memInfo = new Win32Native.MEMORY_BASIC_INFORMATION();
UIntPtr sizeOfMemInfo = (UIntPtr) Marshal.SizeOf(memInfo);
while (((ulong)address) + size < TopOfMemory) {
UIntPtr r = Win32Native.VirtualQuery(address, ref memInfo, sizeOfMemInfo);
if (r == UIntPtr.Zero)
__Error.WinIOError();
ulong regionSize = memInfo.RegionSize.ToUInt64();
if (memInfo.State == Win32Native.MEM_FREE) {
if (regionSize >= size)
return regionSize;
else
largestFreeRegion = Math.Max(largestFreeRegion, regionSize);
}
address = (void *) ((ulong) address + regionSize);
}
return largestFreeRegion;
}
#endif // !FEATURE_PAL
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void GetMemorySettings(out ulong maxGCSegmentSize, out ulong topOfMemory);
[System.Security.SecuritySafeCritical] // destructors should be safe to call
~MemoryFailPoint()
{
Dispose(false);
}
// Applications must call Dispose, which conceptually "releases" the
// memory that was "reserved" by the MemoryFailPoint. This affects a
// global count of reserved memory in this version (helping to throttle
// future MemoryFailPoints) in this version. We may in the
// future create an allocation context and release it in the Dispose
// method. While the finalizer will eventually free this block of
// memory, apps will help their performance greatly by calling Dispose.
[System.Security.SecuritySafeCritical] // auto-generated
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[System.Security.SecurityCritical] // auto-generated
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private void Dispose(bool disposing)
{
// This is just bookkeeping to ensure multiple threads can really
// get enough memory, and this does not actually reserve memory
// within the GC heap.
if (_mustSubtractReservation) {
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
SharedStatics.AddMemoryFailPointReservation(-((long)_reservedMemory));
_mustSubtractReservation = false;
}
}
/*
// Prototype performance hack
// Let's pretend that we returned at least some free memory to
// the GC heap. We don't know this is true - the objects could
// have a longer lifetime, and the memory could be elsewhere in the
// GC heap. Additionally, we subtracted off the segment size, not
// this size. That's ok - we don't mind if this slowly degrades
// and requires us to refresh the value a little bit sooner.
// But releasing the memory here should help us avoid probing for
// free address space excessively with large workItem sizes.
Interlocked.Add(ref LastKnownFreeAddressSpace, _reservedMemory);
*/
}
#if _DEBUG
[Serializable]
internal sealed class MemoryFailPointState
{
private ulong _segmentSize;
private int _allocationSizeInMB;
private bool _needPageFile;
private bool _needAddressSpace;
private bool _needContiguousVASpace;
private ulong _availPageFile;
private ulong _totalFreeAddressSpace;
private long _lastKnownFreeAddressSpace;
private ulong _reservedMem;
private String _stackTrace; // Where did we fail, for additional debugging.
internal MemoryFailPointState(int allocationSizeInMB, ulong segmentSize, bool needPageFile, bool needAddressSpace, bool needContiguousVASpace, ulong availPageFile, ulong totalFreeAddressSpace, long lastKnownFreeAddressSpace, ulong reservedMem)
{
_allocationSizeInMB = allocationSizeInMB;
_segmentSize = segmentSize;
_needPageFile = needPageFile;
_needAddressSpace = needAddressSpace;
_needContiguousVASpace = needContiguousVASpace;
_availPageFile = availPageFile;
_totalFreeAddressSpace = totalFreeAddressSpace;
_lastKnownFreeAddressSpace = lastKnownFreeAddressSpace;
_reservedMem = reservedMem;
try
{
_stackTrace = Environment.StackTrace;
}
catch (System.Security.SecurityException)
{
_stackTrace = "no permission";
}
catch (OutOfMemoryException)
{
_stackTrace = "out of memory";
}
}
public override String ToString()
{
return String.Format(System.Globalization.CultureInfo.InvariantCulture, "MemoryFailPoint detected insufficient memory to guarantee an operation could complete. Checked for {0} MB, for allocation size of {1} MB. Need page file? {2} Need Address Space? {3} Need Contiguous address space? {4} Avail page file: {5} MB Total free VA space: {6} MB Contiguous free address space (found): {7} MB Space reserved by process's MemoryFailPoints: {8} MB",
_segmentSize >> 20, _allocationSizeInMB, _needPageFile,
_needAddressSpace, _needContiguousVASpace,
_availPageFile >> 20, _totalFreeAddressSpace >> 20,
_lastKnownFreeAddressSpace >> 20, _reservedMem);
}
public String StackTrace {
get { return _stackTrace; }
}
}
#endif
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System;
/*
* A class for representing continuous parameters
* that can be altered via the AI
*/
[System.Serializable]
public class ContinuousParameter
{
public String name;
public float value;
}
/*
* A class for representing an individual posture
*/
[System.Serializable]
public class MotionDataItem
{
public String label;
public int labelIndex;
public String clip;
public float time;
public float [] data;
public float lastProbability;
public Texture2D tex;
public Texture2D selectedTex;
public ContinuousParameter [] parameterValues;
}
/*
* Does posture recognition
*/
public class AIController : MonoBehaviour {
// whether to record animation in play mode
public Boolean recordData = false;
// the last classification
public string classification = "nothing";
// the component that records animations
public AnimationRecorder animationRecorder;
// the postures that are used for the nearest
// neighbour recognition
public MotionDataItem [] m_DataItems;
// the largest probability in the last
// classification calculation
private float maxProbability;
public ContinuousParameter [] parameters;
// the name to use for creating a new parameter
public string newParameterName = "";
// objects that will receive a
// message when there is a new
// classification
public GameObject[] listeners;
// controls the range of influence
// of each pose
public float defaultSigma = 1.0f;
// the joints (transforms) used in
// the recognition calculations
public Transform [] featureJoints;
//public bool useVelocityFeatures;
// the names of the classes
public string [] classLabelArray;
// the if of the current selected class
public int currentClassId = -1;
// the name of the current class
// implemented as a property so it can
// be calculated from the id
public string currentClassName
{
get
{
if(currentClassId >= 0)
return classLabelArray[currentClassId];
else
return "";
}
set
{
currentClassId = -1;
for (int i = 0; i < classLabelArray.Length; i++)
{
if(classLabelArray[i] == value)
{
currentClassId = i;
}
}
}
}
// the colours associated with
// each class
public Color [] classColours;
// the name to use for creating a new class
public string newClassName = "";
// the current selected posture
public int currentPosture = -1;
// get the numerical class id from it's name
public int GetClassId(string classLabel)
{
for (int i = 0; i < classLabelArray.Length; i++)
{
if (classLabelArray[i] == classLabel)
{
return i;
}
}
return -1;
}
// add a new class
public void AddClass(string label)
{
// don't add if there is no label
if(label.Equals(""))
return;
// only add if it isn't already there
if(GetClassId(label) < 0)
{
// do some array switching, because unity doesn't
// play well with more complex types
Array.Resize(ref classLabelArray, classLabelArray.Length+1);
classLabelArray[classLabelArray.Length-1] = label;
}
}
// deletes a class
public void RemoveClass(string label)
{
// check that there is actually a label
if(label.Equals(""))
return;
// get the numerical id of the class
int labelId = GetClassId(label);
if(labelId >= 0)
{
// copy all the later labels down in the array
for (int i = labelId; i < classLabelArray.Length-1; i++)
{
classLabelArray[i] = classLabelArray[i+1];
}
// do some array switching, because unity doesn't
// play well with more complex types
Array.Resize(ref classLabelArray, classLabelArray.Length-1);
// regenerate all of the labels for the data items
// as the label ids will have been invalidates
for (int i = 0; i < m_DataItems.Length; i++)
{
m_DataItems[i].labelIndex = GetClassId(m_DataItems[i].label);
}
}
}
public void AddParameter(String name)
{
// resize the DataItems array, adding a new item at the end
Array.Resize(ref parameters, parameters.Length+1);
parameters[parameters.Length-1] = new ContinuousParameter{ name = name, value = 0.0f};
for (int i = 0; i < m_DataItems.Length; i++)
{
Array.Resize(ref m_DataItems[i].parameterValues, parameters.Length);
m_DataItems[i].parameterValues[parameters.Length-1] = new ContinuousParameter{ name = name, value = -1.0f};
}
}
// relabel a given posture
public void LabelPosture(string label, int postureId)
{
if(postureId >= 0 && postureId < m_DataItems.Length)
{
m_DataItems[postureId].label = label;
}
}
// relabel a given posture to the current selected class
public void LabelPosture(int postureId)
{
LabelPosture(currentClassName, postureId);
}
// numbe of postures
public int GetNumPostures()
{
return m_DataItems.Length;
}
// get the class label of a posture
public string GetPostureLabel(int i)
{
return m_DataItems[i].label;
}
// get the animation clip that a posture comes from
public string GetPostureClip(int i)
{
return m_DataItems[i].clip;
}
// get time in the animation clip that the posture appears
public float GetPostureTime(int i)
{
return m_DataItems[i].time;
}
// get an animation curve from a clip
AnimationClipCurveData getCurve(AnimationClip clip, string pathName)
{
AnimationClipCurveData [] curveData = AnimationUtility.GetAllCurves(clip);
foreach (AnimationClipCurveData thiscurve in curveData)
{
if(thiscurve.path == pathName)
{
return thiscurve;
}
}
return null;
}
// get the rotation value of a particular joint (given by pathName)
// at time t
Quaternion getRotationValue(AnimationClip clip, string pathName, float t)
{
// this is the quaternion we use to represent the rotation.
// set it to a zero rotation and we will then add individual
// components to it
var q = Quaternion.identity;
AnimationClipCurveData [] curveData = AnimationUtility.GetAllCurves(clip);
foreach (AnimationClipCurveData thiscurve in curveData)
{
if(thiscurve.path == pathName)
{
if(thiscurve.propertyName == "m_LocalRotation.x")
{
q.x = thiscurve.curve.Evaluate(t);
}
if(thiscurve.propertyName == "m_LocalRotation.y")
{
q.y = thiscurve.curve.Evaluate(t);
}
if(thiscurve.propertyName == "m_LocalRotation.z")
{
q.z = thiscurve.curve.Evaluate(t);
}
if(thiscurve.propertyName == "m_LocalRotation.w")
{
q.w = thiscurve.curve.Evaluate(t);
}
}
}
return q;
}
// turn the angle into radians between
// pi and -pi
float processAngle(float angle)
{
if(angle > 180)
angle = 360-angle;
return Mathf.Deg2Rad*angle;
}
// turn a pose in an animation into an array of numbers that
// can be used by the classification algorithm
// clipName is the name of the animation clip
// time is the time at which the pose appears
float [] GetDataInstanceFromAnimation(string clipName, float time)
{
// get the animation component
Animation anim = gameObject.animation;
if(!anim)
Debug.Log("anim is null");
// three features per joint (x,y,z)
// currently velocity features aren't implemented
int numFeatures = featureJoints.Length*3;
//if(useVelocityFeatures)
// numFeatures = featureJoints.Length*6;
float [] data = new float[numFeatures];
// check that the clip exists
if(!anim[clipName])
return null;
AnimationClip clip = anim[clipName].clip;
// loop through all the features
// getting hold of the value
// j is our position in the array
int j = 0;
foreach (Transform feature in featureJoints)
{
// get the rotation value and turn it into x,y,z
// components (Euler Angles)
Quaternion q = getRotationValue(clip, feature.gameObject.name, time);
Vector3 eulers = q.eulerAngles;
data[j] = processAngle(eulers.x);
j++;
data[j] = processAngle(eulers.y);
j++;
data[j] = processAngle(eulers.z);
j++;
// not currently using velocity features
/*
if(useVelocityFeatures)
{
Quaternion dq = Quaternion.Inverse(q)*getRotationValue(clip, feature.gameObject.name, time+0.3f);
Vector3 dEulers = dq.eulerAngles;
data[j] = processAngle(dEulers.x)/0.3f;
j++;
data[j] = processAngle(dEulers.y)/0.3f;
j++;
data[j] = processAngle(dEulers.z)/0.3f;
j++;
}
*/
}
return data;
}
// turn the current pose into into an array of numbers that
// can be used by the classification algorithm
float [] GetDataInstanceLive()
{
// three features per joint (x,y,z)
// currently velocity features aren't implemented
int numFeatures = featureJoints.Length*3;
//if(useVelocityFeatures)
// numFeatures = featureJoints.Length*3;
float [] data = new float[numFeatures];
// loop through all the features
// getting hold of the value
// j is our position in the array
int j = 0;
foreach (Transform feature in featureJoints)
{
// get the rotation value and turn it into x,y,z
// components (Euler Angles)
Quaternion q = feature.localRotation;
float mag = (float)Math.Sqrt(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w);
q.x /= mag;
q.y /= mag;
q.z /= mag;
q.w /= mag;
Vector3 eulers = q.eulerAngles;
data[j] = processAngle(eulers.x);
// check for NaNs because I seem to get them from Quaternion.eulerAngles
// (should really use quaternion distance when calculating the gaussians)
if (Double.IsInfinity (data[j]) || Double.IsNaN (data[j]))
{
data[j] = 0.0f;
}
j++;
data[j] = processAngle(eulers.y);
// check for NaNs because I seem to get them from Quaternion.eulerAngles
if (Double.IsInfinity (data[j]) || Double.IsNaN (data[j]))
{
data[j] = 0.0f;
}
j++;
data[j] = processAngle(eulers.z);
// check for NaNs because I seem to get them from Quaternion.eulerAngles
if (Double.IsInfinity (data[j]) || Double.IsNaN (data[j]))
{
data[j] = 0.0f;
}
j++;
//Debug.Log ("from live " + feature.gameObject.name + " " + data[j-2] + " " + data[j-1] + " " + data[j] + " " + eulers + " " + q);
//if(useVelocityFeatures)
//{
// throw new System.Exception("velocity features in real time have not been implemented");
//}
}
return data;
}
// add a new posture to the data set
// parameters are:
// label - the class label to attach to the posture
// clip - the animation clip containing the posture
// time - the time at which it appears
// tex - the texture to use for displaying the posture
// selectedTex - the texture to use for displaying the posture when selected
public int AddPosture(string label, string clip, float time, Texture2D tex, Texture2D selectedTex)
{
// turn the posture into animation data
float [] data = GetDataInstanceFromAnimation(clip, time);
// get the label ID of the posture
// (checking for labels that don't exist)
int labelId = -1;
if(label == "")
{
labelId = -1;
}
else
{
labelId = GetClassId(label);
if(labelId < 0)
return -1;
}
// resize the DataItems array, adding a new item at the end
MotionDataItem [] newDataItems = new MotionDataItem[m_DataItems.Length+1];
for (int i = 0; i < m_DataItems.Length; i++)
{
newDataItems[i] = m_DataItems[i];
}
m_DataItems = newDataItems;
m_DataItems[m_DataItems.Length-1] = new MotionDataItem{ label = label, clip = clip, time = time, labelIndex = labelId, data = data, lastProbability = 0, tex=tex, selectedTex = selectedTex};
m_DataItems [m_DataItems.Length - 1].parameterValues = new ContinuousParameter[parameters.Length];
for (int i = 0; i < m_DataItems [m_DataItems.Length - 1].parameterValues.Length; i++)
{
m_DataItems [m_DataItems.Length - 1].parameterValues[i] = new ContinuousParameter();
m_DataItems [m_DataItems.Length - 1].parameterValues[i].name = parameters[i].name;
m_DataItems [m_DataItems.Length - 1].parameterValues[i].value = parameters[i].value;
}
// return the id of the posture
int id = m_DataItems.Length-1;
return id;
}
// conventiece overloaded version of AddPosture, which labels it with
// the current class
public int AddPosture(string clip, float time, Texture2D tex, Texture2D selectedTex)
{
return AddPosture(currentClassName, clip, time, tex, selectedTex);
}
// removes a posture
public void RemovePosture(int id)
{
if(id >= 0 && id < m_DataItems.Length)
{
// copy all the later labels down in the array
for (int i = id; i < m_DataItems.Length-1; i++)
{
m_DataItems[i] = m_DataItems[i+1];
}
// do some array switching, because unity doesn't
// play well with more complex types
Array.Resize(ref m_DataItems, m_DataItems.Length-1);
}
}
// delete all postures
public void ClearDataSet()
{
m_DataItems = new MotionDataItem[0];
}
// get the probability of the pose given by data based on the
// gaussian associated with a single data item
public float getProbability(MotionDataItem gaussian, float [] data)
{
// calculation for the gaussian distribution
float coef = (float)(1.0/Math.Pow(2*Math.PI, gaussian.data.Length/2.0));
coef = (float) (coef * 1.0f/(Math.Pow(defaultSigma, gaussian.data.Length/2.0f)));
float product = 0.0f;
for (int i = 0; i < data.Length; i++)
{
//Debug.Log ("data " + data[i] + " " + gaussian.data[i] + " " + defaultSigma);
product += (data[i]-gaussian.data[i]) * (data[i]-gaussian.data[i])/defaultSigma;
}
//Debug.Log ("product " + product);
float p = (float)(coef*Math.Exp(-0.5f*product));
if (Double.IsInfinity (p) || Double.IsNaN (p))
{
Debug.LogWarning("NaN probabilitiy " + p + " " + gaussian.label + " " + gaussian.time);
return 0.0f;
//throw new Exception ("Calculated probability is NaN");
}
// save the last probability
// (used for scaling the thumbnails)
gaussian.lastProbability = p;
return p;
}
// get the probabilites of the pose given by data
// given all of the class names
public float [] getProbabilities(float [] data)
{
// start with zero probabilities
float [] probs = new float[classLabelArray.Length];
// the number of data items used for each class
// (used to normalise the results)
float [] counts = new float[classLabelArray.Length];
// keep track of the maximum probability
maxProbability = 0.0f;
// for each data item calculated the probability
// and add it to the probabilities for that class
for(int i = 0; i < m_DataItems.Length; i++)
{
float p = getProbability(m_DataItems[i], data);
if(p > maxProbability)
maxProbability = p;
if(m_DataItems[i].labelIndex >= 0)
{
probs[m_DataItems[i].labelIndex] += p;
counts[m_DataItems[i].labelIndex] += 1.0f;
}
}
// normalise by the number of postures in the class
for (int i = 0; i < probs.Length; i++)
{
probs[i] /= counts[i];
}
return probs;
}
// classify the pose given by data
// chooses the class with the highest
// probabilty
public string Classify(float [] data)
{
float [] probs = getProbabilities(data);
int maxId = -1;
float maxProb = 0.0f;
for (int i = 0; i < probs.Length; i++)
{
if(probs[i] > maxProb)
{
maxId = i;
maxProb = probs[i];
}
}
if(maxId < 0 || maxProb <= 0)
return "nothing";
else
return classLabelArray[maxId];
}
#warning get velocities into the classification
// classify the current posture
// and send a message to any gameObjects that
// are listening
public string Classify()
{
float [] data = GetDataInstanceLive();
string new_classification = Classify(data);
if (new_classification != classification)
{
classification = new_classification;
if (Application.isPlaying){
if (new_classification != "nothing")
{
for (int i = 0; i < listeners.Length; i++)
{
listeners[i].SendMessage("OnNewPostureRecognised", new_classification);
}
}
}
}
if (new_classification != "nothing")
{
for(int i = 0; i < parameters.Length; i++)
{
float totalWeight = 0.0f;
float parameterVal = 0.0f;
for(int j = 0; j < m_DataItems.Length; j++)
{
if (m_DataItems[j].label == new_classification)
{
totalWeight += m_DataItems[j].lastProbability;
parameterVal += m_DataItems[j].lastProbability*m_DataItems[j].parameterValues[i].value;
}
}
if(totalWeight > 1.0e-15)
{
parameters[i].value = parameterVal/totalWeight;
for (int j = 0; j < listeners.Length; j++)
{
listeners[j].SendMessage(parameters[i].name, parameters[i].value);
}
}
}
}
return classification;
}
public double GetLastProbability(int i)
{
return m_DataItems[i].lastProbability;
}
public double GetMaxProbability(int i)
{
return maxProbability;
}
// sets up the class
// (creates the classLabelArray if
// it doesn't exist)
public void Init(){
if(classLabelArray == null)
classLabelArray= new string[0];
}
// called when it starts playing
// starts of the animation recording
// if needed
void Awake () {
Init ();
classification = "";
if(recordData && animationRecorder)
{
animationRecorder.enabled = true;
}
}
// turn off recording when we stop playing
void OnApplicationQuit()
{
if(recordData && animationRecorder)
{
animationRecorder.enabled = false;
}
}
// Update is called once per frame
// we classify the new posture
void Update () {
Classify ();
}
void OnEnable()
{
currentClassName = "";
}
void OnDisable()
{
currentClassName = "";
}
// gets the color associated with a class
public Color GetClassColour(int classId, bool selected)
{
if (classId < 0)
{
return Color.white;
}
if (selected)
{
return classColours [classId % classColours.Length];
}
else
{
Color selectedCol = classColours [classId % classColours.Length];
return new Color(selectedCol.r/2.0f, selectedCol.g/2.0f, selectedCol.b/2.0f, 1.0f);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Net.Sockets;
using System.Windows.Forms;
namespace MagiWol {
internal partial class DetailForm : Form {
public MagiWolDocument.AddressItem Destination { get; private set; }
public DetailForm(MagiWolDocument.AddressItem destination) {
InitializeComponent();
this.Font = SystemFonts.MessageBoxFont;
var fixedSizeFont = new Font("Courier New", base.Font.Size, base.Font.Style);
this.textMac.Font = fixedSizeFont;
this.textSecureOn.Font = fixedSizeFont;
this.Destination = destination;
//foreach (Control iControl in this.Controls) {
foreach (Control iControl in new Control[] { textTitle, textMac, textSecureOn, checkBroadcastAddress, checkBroadcastPort }) { //because of Mono
erp.SetIconPadding(iControl, 4);
erp.SetIconAlignment(iControl, ErrorIconAlignment.MiddleLeft);
}
}
private void DetailForm_Load(object sender, EventArgs e) {
if (this.Destination != null) {
textTitle.Text = this.Destination.Title;
textMac.Text = this.Destination.Mac;
textSecureOn.Text = this.Destination.SecureOn;
checkBroadcastAddress.Checked = this.Destination.IsBroadcastHostValid;
textBroadcastAddress.Text = this.Destination.BroadcastHost;
checkBroadcastPort.Checked = this.Destination.IsBroadcastPortValid;
textBroadcastPort.Text = this.Destination.BroadcastPort.ToString(CultureInfo.InvariantCulture);
textNotes.Text = this.Destination.Notes;
} else {
textBroadcastAddress.Text = Settings.BroadcastHost;
textBroadcastPort.Text = Settings.BroadcastPort.ToString(CultureInfo.InvariantCulture);
}
CheckForm();
}
private void buttonOk_Click(object sender, EventArgs e) {
if (this.Destination == null) {
this.Destination = new MagiWolDocument.AddressItem();
}
this.Destination.Title = textTitle.Text;
this.Destination.Mac = textMac.Text;
this.Destination.SecureOn = textSecureOn.Text;
string host;
if (checkBroadcastAddress.Checked) {
if (string.IsNullOrEmpty(textBroadcastAddress.Text.Trim()) == false) {
host = textBroadcastAddress.Text.Trim();
this.Destination.IsBroadcastHostValid = true;
} else {
host = Settings.BroadcastHost;
this.Destination.IsBroadcastHostValid = false;
}
} else {
host = this.Destination.BroadcastHost;
this.Destination.IsBroadcastHostValid = false;
}
int port;
if (checkBroadcastPort.Checked) {
if (int.TryParse(textBroadcastPort.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out port)) {
if ((port >= 0) || (port <= 65535)) {
this.Destination.IsBroadcastPortValid = true;
} else {
port = Settings.BroadcastPort;
this.Destination.IsBroadcastPortValid = false;
}
} else {
port = Settings.BroadcastPort;
this.Destination.IsBroadcastPortValid = false;
}
} else {
port = this.Destination.BroadcastPort;
this.Destination.IsBroadcastPortValid = false;
}
this.Destination.BroadcastHost = host;
this.Destination.BroadcastPort = port;
this.Destination.Notes = textNotes.Text;
}
private void checkBroadcastAddress_CheckedChanged(object sender, EventArgs e) {
textBroadcastAddress.Enabled = checkBroadcastAddress.Checked;
}
private void checkBroadcastPort_CheckedChanged(object sender, EventArgs e) {
textBroadcastPort.Enabled = checkBroadcastPort.Checked;
}
private void textBroadcastAddress_Validating(object sender, CancelEventArgs e) {
if (string.IsNullOrEmpty(textBroadcastAddress.Text)) {
if (this.Destination != null) {
textBroadcastAddress.Text = this.Destination.BroadcastHost;
} else {
textBroadcastAddress.Text = Settings.BroadcastHost;
}
}
}
private void textBroadcastPort_Validating(object sender, CancelEventArgs e) {
int port;
if (!(int.TryParse(textBroadcastPort.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out port) && (port >= 0) && (port <= 65535))) {
if (this.Destination != null) {
textBroadcastPort.Text = this.Destination.BroadcastPort.ToString(CultureInfo.InvariantCulture);
} else {
textBroadcastPort.Text = Settings.BroadcastPort.ToString(CultureInfo.InvariantCulture);
}
}
}
private void DetailForm_Shown(object sender, EventArgs e) {
textTitle.SelectAll();
}
private void textTitle_TextChanged(object sender, EventArgs e) {
CheckForm();
}
private void buttonTest_Click(object sender, EventArgs e) {
try {
try {
Cursor.Current = Cursors.WaitCursor;
try {
Magic.SendMagicPacket(textMac.Text, textSecureOn.Text, textBroadcastAddress.Text, checkBroadcastAddress.Checked, textBroadcastPort.Text, checkBroadcastPort.Checked);
} catch (InvalidOperationException ex) {
Medo.MessageBox.ShowError(this, ex.Message);
}
} finally {
Cursor.Current = Cursors.Default;
}
} catch (FormatException ex) {
Medo.MessageBox.ShowError(this, string.Format("Invalid format.\n\n{0}", ex.Message));
} catch (SocketException sex) {
Medo.MessageBox.ShowError(this, string.Format("Socket exception occurred.\n\n{0}", sex.Message));
}
}
private void textMac_TextChanged(object sender, EventArgs e) {
CheckForm();
}
private void textSecureOn_TextChanged(object sender, EventArgs e) {
CheckForm();
}
private void textBroadcastAddress_TextChanged(object sender, EventArgs e) {
CheckForm();
}
private void textBroadcastPort_TextChanged(object sender, EventArgs e) {
CheckForm();
}
private void CheckForm() {
if (textTitle.Text.Length == 0) {
erp.SetError(textTitle, "Text cannot be empty.");
} else {
erp.SetError(textTitle, null);
}
if (!Medo.Net.WakeOnLan.IsMacAddressValid(textMac.Text)) {
erp.SetError(textMac, "MAC address is not valid.");
} else {
erp.SetError(textMac, null);
}
if (!Medo.Net.WakeOnLan.IsSecureOnPasswordValid(textSecureOn.Text)) {
erp.SetError(textSecureOn, "SecureOn password is not valid.");
} else {
erp.SetError(textSecureOn, null);
}
if (checkBroadcastAddress.Checked) {
if (string.IsNullOrEmpty(textBroadcastAddress.Text.Trim())) {
erp.SetError(checkBroadcastAddress, "Host cannot be empty.");
} else {
erp.SetError(checkBroadcastAddress, null);
}
} else {
erp.SetError(checkBroadcastAddress, null);
}
int port;
if (checkBroadcastPort.Checked) {
if (int.TryParse(textBroadcastPort.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out port) && ((port >= 0) && (port <= 65535))) {
erp.SetError(checkBroadcastPort, null);
} else {
erp.SetError(checkBroadcastPort, "Port is not valid.");
}
} else {
erp.SetError(checkBroadcastPort, null);
}
buttonOk.Enabled = (textTitle.Text.Length > 0) && (Medo.Net.WakeOnLan.IsMacAddressValid(textMac.Text));
buttonTest.Enabled = (Medo.Net.WakeOnLan.IsMacAddressValid(textMac.Text));
}
private void textNotes_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyData == (Keys.Control | Keys.A)) {
textNotes.SelectAll();
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using Microsoft.Azure.Management.AppService.Fluent;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Samples.Common;
using Microsoft.Azure.Management.TrafficManager.Fluent;
using System;
using System.Linq;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
namespace ManageLinuxWebAppWithTrafficManager
{
/**
* Azure App Service sample for managing web apps.
* - Create a domain
* - Create a self-signed certificate for the domain
* - Create 3 app service plans in 3 different regions
* - Create 5 web apps under the 3 plans, bound to the domain and the certificate
* - Create a traffic manager in front of the web apps
* - Scale up the app service plans to twice the capacity
*/
public class Program
{
private static string CERT_PASSWORD = "StrongPass!12";
private static string pfxPath;
public static void RunSample(IAzure azure)
{
string resourceGroupName = SdkContext.RandomResourceName("rgNEMV_", 24);
string app1Name = SdkContext.RandomResourceName("webapp1-", 20);
string app2Name = SdkContext.RandomResourceName("webapp2-", 20);
string app3Name = SdkContext.RandomResourceName("webapp3-", 20);
string app4Name = SdkContext.RandomResourceName("webapp4-", 20);
string app5Name = SdkContext.RandomResourceName("webapp5-", 20);
string plan1Name = SdkContext.RandomResourceName("jplan1_", 15);
string plan2Name = SdkContext.RandomResourceName("jplan2_", 15);
string plan3Name = SdkContext.RandomResourceName("jplan3_", 15);
string domainName = SdkContext.RandomResourceName("jsdkdemo-", 20) + ".com";
string trafficManagerName = SdkContext.RandomResourceName("jsdktm-", 20);
try
{
//============================================================
// Purchase a domain (will be canceled for a full refund)
Utilities.Log("Purchasing a domain " + domainName + "...");
azure.ResourceGroups.Define(resourceGroupName)
.WithRegion(Region.USWest)
.Create();
var domain = azure.AppServices.AppServiceDomains.Define(domainName)
.WithExistingResourceGroup(resourceGroupName)
.DefineRegistrantContact()
.WithFirstName("Jon")
.WithLastName("Doe")
.WithEmail("[email protected]")
.WithAddressLine1("123 4th Ave")
.WithCity("Redmond")
.WithStateOrProvince("WA")
.WithCountry(CountryISOCode.UnitedStates)
.WithPostalCode("98052")
.WithPhoneCountryCode(CountryPhoneCode.UnitedStates)
.WithPhoneNumber("4258828080")
.Attach()
.WithDomainPrivacyEnabled(true)
.WithAutoRenewEnabled(false)
.Create();
Utilities.Log("Purchased domain " + domain.Name);
Utilities.Print(domain);
//============================================================
// Create a self-singed SSL certificate
pfxPath = domainName + ".pfx";
Utilities.Log("Creating a self-signed certificate " + pfxPath + "...");
Utilities.CreateCertificate(domainName, pfxPath, CERT_PASSWORD);
//============================================================
// Create 3 app service plans in 3 regions
Utilities.Log("Creating app service plan " + plan1Name + " in US West...");
var plan1 = CreateAppServicePlan(azure, resourceGroupName, plan1Name, Region.USWest);
Utilities.Log("Created app service plan " + plan1.Name);
Utilities.Print(plan1);
Utilities.Log("Creating app service plan " + plan2Name + " in Europe West...");
var plan2 = CreateAppServicePlan(azure, resourceGroupName, plan2Name, Region.EuropeWest);
Utilities.Log("Created app service plan " + plan2.Name);
Utilities.Print(plan1);
Utilities.Log("Creating app service plan " + plan3Name + " in Asia South East...");
var plan3 = CreateAppServicePlan(azure, resourceGroupName, plan3Name, Region.AsiaSouthEast);
Utilities.Log("Created app service plan " + plan2.Name);
Utilities.Print(plan1);
//============================================================
// Create 5 web apps under these 3 app service plans
Utilities.Log("Creating web app " + app1Name + "...");
var app1 = CreateWebApp(azure, domain, resourceGroupName, app1Name, plan1);
Utilities.Log("Created web app " + app1.Name);
Utilities.Print(app1);
Utilities.Log("Creating another web app " + app2Name + "...");
var app2 = CreateWebApp(azure, domain, resourceGroupName, app2Name, plan2);
Utilities.Log("Created web app " + app2.Name);
Utilities.Print(app2);
Utilities.Log("Creating another web app " + app3Name + "...");
var app3 = CreateWebApp(azure, domain, resourceGroupName, app3Name, plan3);
Utilities.Log("Created web app " + app3.Name);
Utilities.Print(app3);
Utilities.Log("Creating another web app " + app3Name + "...");
var app4 = CreateWebApp(azure, domain, resourceGroupName, app4Name, plan1);
Utilities.Log("Created web app " + app4.Name);
Utilities.Print(app4);
Utilities.Log("Creating another web app " + app3Name + "...");
var app5 = CreateWebApp(azure, domain, resourceGroupName, app5Name, plan1);
Utilities.Log("Created web app " + app5.Name);
Utilities.Print(app5);
//============================================================
// Create a traffic manager
Utilities.Log("Creating a traffic manager " + trafficManagerName + " for the web apps...");
var trafficManager = azure.TrafficManagerProfiles
.Define(trafficManagerName)
.WithExistingResourceGroup(resourceGroupName)
.WithLeafDomainLabel(trafficManagerName)
.WithTrafficRoutingMethod(TrafficRoutingMethod.Weighted)
.DefineAzureTargetEndpoint("endpoint1")
.ToResourceId(app1.Id)
.Attach()
.DefineAzureTargetEndpoint("endpoint2")
.ToResourceId(app2.Id)
.Attach()
.DefineAzureTargetEndpoint("endpoint3")
.ToResourceId(app3.Id)
.Attach()
.Create();
Utilities.Log("Created traffic manager " + trafficManager.Name);
//============================================================
// Scale up the app service plans
Utilities.Log("Scaling up app service plan " + plan1Name + "...");
plan1.Update()
.WithCapacity(plan1.Capacity * 2)
.Apply();
Utilities.Log("Scaled up app service plan " + plan1Name);
Utilities.Print(plan1);
Utilities.Log("Scaling up app service plan " + plan2Name + "...");
plan2.Update()
.WithCapacity(plan2.Capacity * 2)
.Apply();
Utilities.Log("Scaled up app service plan " + plan2Name);
Utilities.Print(plan2);
Utilities.Log("Scaling up app service plan " + plan3Name + "...");
plan3.Update()
.WithCapacity(plan3.Capacity * 2)
.Apply();
Utilities.Log("Scaled up app service plan " + plan3Name);
Utilities.Print(plan3);
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + resourceGroupName);
azure.ResourceGroups.DeleteByName(resourceGroupName);
Utilities.Log("Deleted Resource Group: " + resourceGroupName);
}
catch (NullReferenceException)
{
Utilities.Log("Did not create any resources in Azure. No clean up is necessary");
}
catch (Exception g)
{
Utilities.Log(g);
}
}
}
public static void Main(string[] args)
{
try
{
//=================================================================
// Authenticate
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
RunSample(azure);
}
catch (Exception e)
{
Utilities.Log(e);
}
}
private static IAppServicePlan CreateAppServicePlan(IAzure azure, string rgName, string name, Region region)
{
return azure.AppServices.AppServicePlans
.Define(name)
.WithRegion(region)
.WithExistingResourceGroup(rgName)
.WithPricingTier(PricingTier.BasicB1)
.WithOperatingSystem(Microsoft.Azure.Management.AppService.Fluent.OperatingSystem.Linux)
.Create();
}
private static IWebApp CreateWebApp(IAzure azure, IAppServiceDomain domain, string rgName, string name, IAppServicePlan plan)
{
return azure.WebApps.Define(name)
.WithExistingLinuxPlan(plan)
.WithExistingResourceGroup(rgName)
.WithBuiltInImage(RuntimeStack.NodeJS_4_5)
.WithManagedHostnameBindings(domain, name)
.DefineSslBinding()
.ForHostname(name + "." + domain.Name)
.WithPfxCertificateToUpload(Path.Combine(Utilities.ProjectPath, "Asset", pfxPath), CERT_PASSWORD)
.WithSniBasedSsl()
.Attach()
.DefineSourceControl()
.WithPublicGitRepository("https://github.Com/jianghaolu/azure-site-test")
.WithBranch("master")
.Attach()
.Create();
}
}
}
| |
using System;
using System.Diagnostics;
using System.Collections.Specialized;
using System.Globalization;
using NDoc.Core;
using NDoc.Core.Reflection;
namespace NDoc.Documenter.Msdn2
{
/// <summary>
/// Provides an extension object for the xslt transformations.
/// </summary>
public class MsdnXsltUtilities
{
private const string sdkDoc10BaseNamespace = "MS.NETFrameworkSDK";
private const string sdkDoc11BaseNamespace = "MS.NETFrameworkSDKv1.1";
private const string helpURL = "ms-help://";
private const string sdkRoot = "/cpref/html/frlrf";
private const string sdkDocPageExt = ".htm";
private const string msdnOnlineSdkBaseUrl = "http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrf";
private const string msdnOnlineSdkPageExt = ".asp";
private const string systemPrefix = "System.";
private string frameworkVersion="";
private string sdkDocBaseUrl;
private string sdkDocExt;
private StringDictionary fileNames;
private StringDictionary elemNames;
private StringCollection descriptions;
private string encodingString;
/// <summary>
/// Initializes a new instance of class MsdnXsltUtilities
/// </summary>
/// <param name="fileNames">A StringDictionary holding id to file name mappings.</param>
/// <param name="elemNames">A StringDictionary holding id to element name mappings</param>
/// <param name="linkToSdkDocVersion">Specifies the version of the SDK documentation.</param>
/// <param name="linkToSdkDocLangauge">Specifies the version of the SDK documentation.</param>
/// <param name="SdkLinksOnWeb">Specifies if links should be to ms online documentation.</param>
/// <param name="fileEncoding">Specifies if links should be to ms online documentation.</param>
public MsdnXsltUtilities(
StringDictionary fileNames,
StringDictionary elemNames,
SdkVersion linkToSdkDocVersion,
string linkToSdkDocLangauge,
bool SdkLinksOnWeb,
System.Text.Encoding fileEncoding)
{
Reset();
this.fileNames = fileNames;
this.elemNames = elemNames;
if (SdkLinksOnWeb)
{
sdkDocBaseUrl = msdnOnlineSdkBaseUrl;
sdkDocExt = msdnOnlineSdkPageExt;
}
else
{
switch (linkToSdkDocVersion)
{
case SdkVersion.SDK_v1_0:
sdkDocBaseUrl = GetLocalizedFrameworkURL(sdkDoc10BaseNamespace,linkToSdkDocLangauge);
sdkDocExt = sdkDocPageExt;
frameworkVersion="1.0";
break;
case SdkVersion.SDK_v1_1:
sdkDocBaseUrl = GetLocalizedFrameworkURL(sdkDoc11BaseNamespace,linkToSdkDocLangauge);
sdkDocExt = sdkDocPageExt;
frameworkVersion="1.1";
break;
default:
Debug.Assert( false ); // remind ourselves to update this list when new framework versions are supported
break;
}
}
encodingString = "text/html; charset=" + fileEncoding.WebName;
}
/// <summary>
/// Reset Overload method checking state.
/// </summary>
public void Reset()
{
descriptions = new StringCollection();
}
/// <summary>
/// Gets the base Url for system types links.
/// </summary>
public string SdkDocBaseUrl
{
get { return sdkDocBaseUrl; }
}
/// <summary>
/// Gets the page file extension for system types links.
/// </summary>
public string SdkDocExt
{
get { return sdkDocExt; }
}
/// <summary>
/// Gets the friendly version number for the framework.
/// </summary>
public string FrameworkVersion
{
get {return frameworkVersion;}
}
/// <summary>
/// Returns an HRef for a CRef.
/// </summary>
/// <param name="cref">CRef for which the HRef will be looked up.</param>
public string GetHRef(string cref)
{
if ((cref.Length < 2) || (cref[1] != ':'))
return string.Empty;
if ((cref.Length < 9)
|| (cref.Substring(2, 7) != systemPrefix))
{
string fileName = fileNames[cref];
if ((fileName == null) && cref.StartsWith("F:"))
fileName = fileNames["E:" + cref.Substring(2)];
if (fileName == null)
return "";
else
return fileName;
}
else
{
switch (cref.Substring(0, 2))
{
case "N:": // Namespace
return sdkDocBaseUrl + cref.Substring(2).Replace(".", "") + sdkDocExt;
case "T:": // Type: class, interface, struct, enum, delegate
// pointer types link to the type being pointed to
return sdkDocBaseUrl + cref.Substring(2).Replace(".", "").Replace( "*", "" ) + "ClassTopic" + sdkDocExt;
case "F:": // Field
case "P:": // Property
case "M:": // Method
case "E:": // Event
return GetFilenameForSystemMember(cref);
default:
return string.Empty;
}
}
}
/// <summary>
/// Returns a name for a CRef.
/// </summary>
/// <param name="cref">CRef for which the name will be looked up.</param>
public string GetName(string cref)
{
if (cref.Length < 2)
return cref;
if (cref[1] == ':')
{
if ((cref.Length < 9)
|| (cref.Substring(2, 7) != systemPrefix))
{
string name = elemNames[cref];
if (name != null)
return name;
}
int index;
if ((index = cref.IndexOf(".#c")) >= 0)
cref = cref.Substring(2, index - 2);
else if ((index = cref.IndexOf("(")) >= 0)
cref = cref.Substring(2, index - 2);
else
cref = cref.Substring(2);
}
return cref.Substring(cref.LastIndexOf(".") + 1);
}
private string GetFilenameForSystemMember(string id)
{
string crefName;
int index;
if ((index = id.IndexOf(".#c")) >= 0)
crefName = id.Substring(2, index - 2) + ".ctor";
else if ((index = id.IndexOf("(")) >= 0)
crefName = id.Substring(2, index - 2);
else
crefName = id.Substring(2);
index = crefName.LastIndexOf(".");
string crefType = crefName.Substring(0, index);
string crefMember = crefName.Substring(index + 1);
return sdkDocBaseUrl + crefType.Replace(".", "") + "Class" + crefMember + "Topic" + sdkDocExt;
}
/// <summary>
/// Looks up, whether a member has similar overloads, that have already been documented.
/// </summary>
/// <param name="description">A string describing this overload.</param>
/// <returns>true, if there has been a member with the same description.</returns>
/// <remarks>
/// <para>On the members pages overloads are cumulated. Instead of adding all overloads
/// to the members page, a link is added to the members page, that points
/// to an overloads page.</para>
/// <para>If for example one overload is public, while another one is protected,
/// we want both to appear on the members page. This is to make the search
/// for suitable members easier.</para>
/// <para>This leads us to the similarity of overloads. Two overloads are considered
/// similar, if they have the same name, declaring type, access (public, protected, ...)
/// and contract (static, non static). The description contains these four attributes
/// of the member. This means, that two members are similar, when they have the same
/// description.</para>
/// <para>Asking for the first time, if a member has similar overloads, will return false.
/// After that, if asking with the same description again, it will return true, so
/// the overload does not need to be added to the members page.</para>
/// </remarks>
public bool HasSimilarOverloads(string description)
{
if (descriptions.Contains(description))
return true;
descriptions.Add(description);
return false;
}
/// <summary>
/// Exposes <see cref="String.Replace(string, string)"/> to XSLT
/// </summary>
/// <param name="str">The string to search</param>
/// <param name="oldValue">The string to search for</param>
/// <param name="newValue">The string to replace</param>
/// <returns>A new string</returns>
public string Replace( string str, string oldValue, string newValue )
{
return str.Replace( oldValue, newValue );
}
/// <summary>
/// returns a localized sdk url if one exists for the <see cref="CultureInfo.CurrentCulture"/>.
/// </summary>
/// <param name="searchNamespace">base namespace to search for</param>
/// <param name="langCode">the localization language code</param>
/// <returns>ms-help url for sdk</returns>
private string GetLocalizedFrameworkURL(string searchNamespace, string langCode)
{
if (langCode!="en")
{
return helpURL + searchNamespace + "." + langCode.ToUpper() + sdkRoot;
}
else
{
//default to non-localized namespace
return helpURL + searchNamespace + sdkRoot;
}
}
/// <summary>
/// Gets HTML ContentType for the system's current ANSI code page.
/// </summary>
/// <returns>ContentType attribute string</returns>
public string GetContentType()
{
return encodingString;
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Text.Json
{
public enum JsonCommentHandling : byte
{
Disallow = (byte)0,
Skip = (byte)1,
Allow = (byte)2,
}
public sealed partial class JsonDocument : System.IDisposable
{
internal JsonDocument() { }
public System.Text.Json.JsonElement RootElement { get { throw null; } }
public void Dispose() { }
public static System.Text.Json.JsonDocument Parse(System.Buffers.ReadOnlySequence<byte> utf8Json, System.Text.Json.JsonDocumentOptions options = default(System.Text.Json.JsonDocumentOptions)) { throw null; }
public static System.Text.Json.JsonDocument Parse(System.IO.Stream utf8Json, System.Text.Json.JsonDocumentOptions options = default(System.Text.Json.JsonDocumentOptions)) { throw null; }
public static System.Text.Json.JsonDocument Parse(System.ReadOnlyMemory<byte> utf8Json, System.Text.Json.JsonDocumentOptions options = default(System.Text.Json.JsonDocumentOptions)) { throw null; }
public static System.Text.Json.JsonDocument Parse(System.ReadOnlyMemory<char> json, System.Text.Json.JsonDocumentOptions options = default(System.Text.Json.JsonDocumentOptions)) { throw null; }
public static System.Text.Json.JsonDocument Parse(string json, System.Text.Json.JsonDocumentOptions options = default(System.Text.Json.JsonDocumentOptions)) { throw null; }
public static System.Threading.Tasks.Task<System.Text.Json.JsonDocument> ParseAsync(System.IO.Stream utf8Json, System.Text.Json.JsonDocumentOptions options = default(System.Text.Json.JsonDocumentOptions), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static System.Text.Json.JsonDocument ParseValue(ref System.Text.Json.Utf8JsonReader reader) { throw null; }
public static bool TryParseValue(ref System.Text.Json.Utf8JsonReader reader, out System.Text.Json.JsonDocument document) { throw null; }
public void WriteTo(System.Text.Json.Utf8JsonWriter writer) { }
}
public partial struct JsonDocumentOptions
{
private int _dummyPrimitive;
public bool AllowTrailingCommas { readonly get { throw null; } set { } }
public System.Text.Json.JsonCommentHandling CommentHandling { readonly get { throw null; } set { } }
public int MaxDepth { readonly get { throw null; } set { } }
}
public readonly partial struct JsonElement
{
private readonly object _dummy;
private readonly int _dummyPrimitive;
public System.Text.Json.JsonElement this[int index] { get { throw null; } }
public System.Text.Json.JsonValueKind ValueKind { get { throw null; } }
public System.Text.Json.JsonElement Clone() { throw null; }
public System.Text.Json.JsonElement.ArrayEnumerator EnumerateArray() { throw null; }
public System.Text.Json.JsonElement.ObjectEnumerator EnumerateObject() { throw null; }
public int GetArrayLength() { throw null; }
public bool GetBoolean() { throw null; }
public byte GetByte() { throw null; }
public byte[] GetBytesFromBase64() { throw null; }
public System.DateTime GetDateTime() { throw null; }
public System.DateTimeOffset GetDateTimeOffset() { throw null; }
public decimal GetDecimal() { throw null; }
public double GetDouble() { throw null; }
public System.Guid GetGuid() { throw null; }
public short GetInt16() { throw null; }
public int GetInt32() { throw null; }
public long GetInt64() { throw null; }
public System.Text.Json.JsonElement GetProperty(System.ReadOnlySpan<byte> utf8PropertyName) { throw null; }
public System.Text.Json.JsonElement GetProperty(System.ReadOnlySpan<char> propertyName) { throw null; }
public System.Text.Json.JsonElement GetProperty(string propertyName) { throw null; }
public string GetRawText() { throw null; }
[System.CLSCompliantAttribute(false)]
public sbyte GetSByte() { throw null; }
public float GetSingle() { throw null; }
public string GetString() { throw null; }
[System.CLSCompliantAttribute(false)]
public ushort GetUInt16() { throw null; }
[System.CLSCompliantAttribute(false)]
public uint GetUInt32() { throw null; }
[System.CLSCompliantAttribute(false)]
public ulong GetUInt64() { throw null; }
public override string ToString() { throw null; }
public bool TryGetByte(out byte value) { throw null; }
public bool TryGetBytesFromBase64(out byte[] value) { throw null; }
public bool TryGetDateTime(out System.DateTime value) { throw null; }
public bool TryGetDateTimeOffset(out System.DateTimeOffset value) { throw null; }
public bool TryGetDecimal(out decimal value) { throw null; }
public bool TryGetDouble(out double value) { throw null; }
public bool TryGetGuid(out System.Guid value) { throw null; }
public bool TryGetInt16(out short value) { throw null; }
public bool TryGetInt32(out int value) { throw null; }
public bool TryGetInt64(out long value) { throw null; }
public bool TryGetProperty(System.ReadOnlySpan<byte> utf8PropertyName, out System.Text.Json.JsonElement value) { throw null; }
public bool TryGetProperty(System.ReadOnlySpan<char> propertyName, out System.Text.Json.JsonElement value) { throw null; }
public bool TryGetProperty(string propertyName, out System.Text.Json.JsonElement value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetSByte(out sbyte value) { throw null; }
public bool TryGetSingle(out float value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt16(out ushort value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt32(out uint value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt64(out ulong value) { throw null; }
public bool ValueEquals(System.ReadOnlySpan<byte> utf8Text) { throw null; }
public bool ValueEquals(System.ReadOnlySpan<char> text) { throw null; }
public bool ValueEquals(string text) { throw null; }
public void WriteTo(System.Text.Json.Utf8JsonWriter writer) { }
public partial struct ArrayEnumerator : System.Collections.Generic.IEnumerable<System.Text.Json.JsonElement>, System.Collections.Generic.IEnumerator<System.Text.Json.JsonElement>, System.Collections.IEnumerable, System.Collections.IEnumerator, System.IDisposable
{
private object _dummy;
private int _dummyPrimitive;
public System.Text.Json.JsonElement Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public System.Text.Json.JsonElement.ArrayEnumerator GetEnumerator() { throw null; }
public bool MoveNext() { throw null; }
public void Reset() { }
System.Collections.Generic.IEnumerator<System.Text.Json.JsonElement> System.Collections.Generic.IEnumerable<System.Text.Json.JsonElement>.GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public partial struct ObjectEnumerator : System.Collections.Generic.IEnumerable<System.Text.Json.JsonProperty>, System.Collections.Generic.IEnumerator<System.Text.Json.JsonProperty>, System.Collections.IEnumerable, System.Collections.IEnumerator, System.IDisposable
{
private object _dummy;
private int _dummyPrimitive;
public System.Text.Json.JsonProperty Current { get { throw null; } }
object System.Collections.IEnumerator.Current { get { throw null; } }
public void Dispose() { }
public System.Text.Json.JsonElement.ObjectEnumerator GetEnumerator() { throw null; }
public bool MoveNext() { throw null; }
public void Reset() { }
System.Collections.Generic.IEnumerator<System.Text.Json.JsonProperty> System.Collections.Generic.IEnumerable<System.Text.Json.JsonProperty>.GetEnumerator() { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
}
public readonly partial struct JsonEncodedText : System.IEquatable<System.Text.Json.JsonEncodedText>
{
private readonly object _dummy;
public System.ReadOnlySpan<byte> EncodedUtf8Bytes { get { throw null; } }
public static System.Text.Json.JsonEncodedText Encode(System.ReadOnlySpan<byte> utf8Value, System.Text.Encodings.Web.JavaScriptEncoder encoder = null) { throw null; }
public static System.Text.Json.JsonEncodedText Encode(System.ReadOnlySpan<char> value, System.Text.Encodings.Web.JavaScriptEncoder encoder = null) { throw null; }
public static System.Text.Json.JsonEncodedText Encode(string value, System.Text.Encodings.Web.JavaScriptEncoder encoder = null) { throw null; }
public override bool Equals(object obj) { throw null; }
public bool Equals(System.Text.Json.JsonEncodedText other) { throw null; }
public override int GetHashCode() { throw null; }
public override string ToString() { throw null; }
}
public partial class JsonException : System.Exception
{
public JsonException() { }
protected JsonException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
public JsonException(string message) { }
public JsonException(string message, System.Exception innerException) { }
public JsonException(string message, string path, long? lineNumber, long? bytePositionInLine) { }
public JsonException(string message, string path, long? lineNumber, long? bytePositionInLine, System.Exception innerException) { }
public long? BytePositionInLine { get { throw null; } }
public long? LineNumber { get { throw null; } }
public override string Message { get { throw null; } }
public string Path { get { throw null; } }
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { }
}
public abstract partial class JsonNamingPolicy
{
protected JsonNamingPolicy() { }
public static System.Text.Json.JsonNamingPolicy CamelCase { get { throw null; } }
public abstract string ConvertName(string name);
}
public readonly partial struct JsonProperty
{
private readonly object _dummy;
public string Name { get { throw null; } }
public System.Text.Json.JsonElement Value { get { throw null; } }
public bool NameEquals(System.ReadOnlySpan<byte> utf8Text) { throw null; }
public bool NameEquals(System.ReadOnlySpan<char> text) { throw null; }
public bool NameEquals(string text) { throw null; }
public override string ToString() { throw null; }
public void WriteTo(System.Text.Json.Utf8JsonWriter writer) { }
}
public partial struct JsonReaderOptions
{
private int _dummyPrimitive;
public bool AllowTrailingCommas { readonly get { throw null; } set { } }
public System.Text.Json.JsonCommentHandling CommentHandling { readonly get { throw null; } set { } }
public int MaxDepth { readonly get { throw null; } set { } }
}
public partial struct JsonReaderState
{
private object _dummy;
private int _dummyPrimitive;
public JsonReaderState(System.Text.Json.JsonReaderOptions options = default(System.Text.Json.JsonReaderOptions)) { throw null; }
public System.Text.Json.JsonReaderOptions Options { get { throw null; } }
}
public static partial class JsonSerializer
{
public static object Deserialize(System.ReadOnlySpan<byte> utf8Json, System.Type returnType, System.Text.Json.JsonSerializerOptions options = null) { throw null; }
public static object Deserialize(string json, System.Type returnType, System.Text.Json.JsonSerializerOptions options = null) { throw null; }
public static object Deserialize(ref System.Text.Json.Utf8JsonReader reader, System.Type returnType, System.Text.Json.JsonSerializerOptions options = null) { throw null; }
public static System.Threading.Tasks.ValueTask<object> DeserializeAsync(System.IO.Stream utf8Json, System.Type returnType, System.Text.Json.JsonSerializerOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static System.Threading.Tasks.ValueTask<TValue> DeserializeAsync<TValue>(System.IO.Stream utf8Json, System.Text.Json.JsonSerializerOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static TValue Deserialize<TValue>(System.ReadOnlySpan<byte> utf8Json, System.Text.Json.JsonSerializerOptions options = null) { throw null; }
public static TValue Deserialize<TValue>(string json, System.Text.Json.JsonSerializerOptions options = null) { throw null; }
public static TValue Deserialize<TValue>(ref System.Text.Json.Utf8JsonReader reader, System.Text.Json.JsonSerializerOptions options = null) { throw null; }
public static string Serialize(object value, System.Type inputType, System.Text.Json.JsonSerializerOptions options = null) { throw null; }
public static void Serialize(System.Text.Json.Utf8JsonWriter writer, object value, System.Type inputType, System.Text.Json.JsonSerializerOptions options = null) { }
public static System.Threading.Tasks.Task SerializeAsync(System.IO.Stream utf8Json, object value, System.Type inputType, System.Text.Json.JsonSerializerOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static System.Threading.Tasks.Task SerializeAsync<TValue>(System.IO.Stream utf8Json, TValue value, System.Text.Json.JsonSerializerOptions options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public static byte[] SerializeToUtf8Bytes(object value, System.Type inputType, System.Text.Json.JsonSerializerOptions options = null) { throw null; }
public static byte[] SerializeToUtf8Bytes<TValue>(TValue value, System.Text.Json.JsonSerializerOptions options = null) { throw null; }
public static void Serialize<TValue>(System.Text.Json.Utf8JsonWriter writer, TValue value, System.Text.Json.JsonSerializerOptions options = null) { }
public static string Serialize<TValue>(TValue value, System.Text.Json.JsonSerializerOptions options = null) { throw null; }
}
public sealed partial class JsonSerializerOptions
{
public JsonSerializerOptions() { }
public bool AllowTrailingCommas { get { throw null; } set { } }
public System.Collections.Generic.IList<System.Text.Json.Serialization.JsonConverter> Converters { get { throw null; } }
public int DefaultBufferSize { get { throw null; } set { } }
public System.Text.Json.JsonNamingPolicy DictionaryKeyPolicy { get { throw null; } set { } }
public System.Text.Encodings.Web.JavaScriptEncoder Encoder { get { throw null; } set { } }
public bool IgnoreNullValues { get { throw null; } set { } }
public bool IgnoreReadOnlyProperties { get { throw null; } set { } }
public int MaxDepth { get { throw null; } set { } }
public bool PropertyNameCaseInsensitive { get { throw null; } set { } }
public System.Text.Json.JsonNamingPolicy PropertyNamingPolicy { get { throw null; } set { } }
public System.Text.Json.JsonCommentHandling ReadCommentHandling { get { throw null; } set { } }
public bool WriteIndented { get { throw null; } set { } }
public System.Text.Json.Serialization.JsonConverter GetConverter(System.Type typeToConvert) { throw null; }
}
public enum JsonTokenType : byte
{
None = (byte)0,
StartObject = (byte)1,
EndObject = (byte)2,
StartArray = (byte)3,
EndArray = (byte)4,
PropertyName = (byte)5,
Comment = (byte)6,
String = (byte)7,
Number = (byte)8,
True = (byte)9,
False = (byte)10,
Null = (byte)11,
}
public enum JsonValueKind : byte
{
Undefined = (byte)0,
Object = (byte)1,
Array = (byte)2,
String = (byte)3,
Number = (byte)4,
True = (byte)5,
False = (byte)6,
Null = (byte)7,
}
public partial struct JsonWriterOptions
{
private object _dummy;
private int _dummyPrimitive;
public System.Text.Encodings.Web.JavaScriptEncoder Encoder { readonly get { throw null; } set { } }
public bool Indented { get { throw null; } set { } }
public bool SkipValidation { get { throw null; } set { } }
}
public ref partial struct Utf8JsonReader
{
private object _dummy;
private int _dummyPrimitive;
public Utf8JsonReader(System.Buffers.ReadOnlySequence<byte> jsonData, bool isFinalBlock, System.Text.Json.JsonReaderState state) { throw null; }
public Utf8JsonReader(System.Buffers.ReadOnlySequence<byte> jsonData, System.Text.Json.JsonReaderOptions options = default(System.Text.Json.JsonReaderOptions)) { throw null; }
public Utf8JsonReader(System.ReadOnlySpan<byte> jsonData, bool isFinalBlock, System.Text.Json.JsonReaderState state) { throw null; }
public Utf8JsonReader(System.ReadOnlySpan<byte> jsonData, System.Text.Json.JsonReaderOptions options = default(System.Text.Json.JsonReaderOptions)) { throw null; }
public long BytesConsumed { get { throw null; } }
public int CurrentDepth { get { throw null; } }
public System.Text.Json.JsonReaderState CurrentState { get { throw null; } }
public readonly bool HasValueSequence { get { throw null; } }
public bool IsFinalBlock { get { throw null; } }
public System.SequencePosition Position { get { throw null; } }
public readonly long TokenStartIndex { get { throw null; } }
public System.Text.Json.JsonTokenType TokenType { get { throw null; } }
public readonly System.Buffers.ReadOnlySequence<byte> ValueSequence { get { throw null; } }
public readonly System.ReadOnlySpan<byte> ValueSpan { get { throw null; } }
public bool GetBoolean() { throw null; }
public byte GetByte() { throw null; }
public byte[] GetBytesFromBase64() { throw null; }
public string GetComment() { throw null; }
public System.DateTime GetDateTime() { throw null; }
public System.DateTimeOffset GetDateTimeOffset() { throw null; }
public decimal GetDecimal() { throw null; }
public double GetDouble() { throw null; }
public System.Guid GetGuid() { throw null; }
public short GetInt16() { throw null; }
public int GetInt32() { throw null; }
public long GetInt64() { throw null; }
[System.CLSCompliantAttribute(false)]
public sbyte GetSByte() { throw null; }
public float GetSingle() { throw null; }
public string GetString() { throw null; }
[System.CLSCompliantAttribute(false)]
public ushort GetUInt16() { throw null; }
[System.CLSCompliantAttribute(false)]
public uint GetUInt32() { throw null; }
[System.CLSCompliantAttribute(false)]
public ulong GetUInt64() { throw null; }
public bool Read() { throw null; }
public void Skip() { }
public bool TryGetByte(out byte value) { throw null; }
public bool TryGetBytesFromBase64(out byte[] value) { throw null; }
public bool TryGetDateTime(out System.DateTime value) { throw null; }
public bool TryGetDateTimeOffset(out System.DateTimeOffset value) { throw null; }
public bool TryGetDecimal(out decimal value) { throw null; }
public bool TryGetDouble(out double value) { throw null; }
public bool TryGetGuid(out System.Guid value) { throw null; }
public bool TryGetInt16(out short value) { throw null; }
public bool TryGetInt32(out int value) { throw null; }
public bool TryGetInt64(out long value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetSByte(out sbyte value) { throw null; }
public bool TryGetSingle(out float value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt16(out ushort value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt32(out uint value) { throw null; }
[System.CLSCompliantAttribute(false)]
public bool TryGetUInt64(out ulong value) { throw null; }
public bool TrySkip() { throw null; }
public bool ValueTextEquals(System.ReadOnlySpan<byte> utf8Text) { throw null; }
public bool ValueTextEquals(System.ReadOnlySpan<char> text) { throw null; }
public bool ValueTextEquals(string text) { throw null; }
}
public sealed partial class Utf8JsonWriter : System.IAsyncDisposable, System.IDisposable
{
public Utf8JsonWriter(System.Buffers.IBufferWriter<byte> bufferWriter, System.Text.Json.JsonWriterOptions options = default(System.Text.Json.JsonWriterOptions)) { }
public Utf8JsonWriter(System.IO.Stream utf8Json, System.Text.Json.JsonWriterOptions options = default(System.Text.Json.JsonWriterOptions)) { }
public long BytesCommitted { get { throw null; } }
public int BytesPending { get { throw null; } }
public int CurrentDepth { get { throw null; } }
public System.Text.Json.JsonWriterOptions Options { get { throw null; } }
public void Dispose() { }
public System.Threading.Tasks.ValueTask DisposeAsync() { throw null; }
public void Flush() { }
public System.Threading.Tasks.Task FlushAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
public void Reset() { }
public void Reset(System.Buffers.IBufferWriter<byte> bufferWriter) { }
public void Reset(System.IO.Stream utf8Json) { }
public void WriteBase64String(System.ReadOnlySpan<byte> utf8PropertyName, System.ReadOnlySpan<byte> bytes) { }
public void WriteBase64String(System.ReadOnlySpan<char> propertyName, System.ReadOnlySpan<byte> bytes) { }
public void WriteBase64String(string propertyName, System.ReadOnlySpan<byte> bytes) { }
public void WriteBase64String(System.Text.Json.JsonEncodedText propertyName, System.ReadOnlySpan<byte> bytes) { }
public void WriteBase64StringValue(System.ReadOnlySpan<byte> bytes) { }
public void WriteBoolean(System.ReadOnlySpan<byte> utf8PropertyName, bool value) { }
public void WriteBoolean(System.ReadOnlySpan<char> propertyName, bool value) { }
public void WriteBoolean(string propertyName, bool value) { }
public void WriteBoolean(System.Text.Json.JsonEncodedText propertyName, bool value) { }
public void WriteBooleanValue(bool value) { }
public void WriteCommentValue(System.ReadOnlySpan<byte> utf8Value) { }
public void WriteCommentValue(System.ReadOnlySpan<char> value) { }
public void WriteCommentValue(string value) { }
public void WriteEndArray() { }
public void WriteEndObject() { }
public void WriteNull(System.ReadOnlySpan<byte> utf8PropertyName) { }
public void WriteNull(System.ReadOnlySpan<char> propertyName) { }
public void WriteNull(string propertyName) { }
public void WriteNull(System.Text.Json.JsonEncodedText propertyName) { }
public void WriteNullValue() { }
public void WriteNumber(System.ReadOnlySpan<byte> utf8PropertyName, decimal value) { }
public void WriteNumber(System.ReadOnlySpan<byte> utf8PropertyName, double value) { }
public void WriteNumber(System.ReadOnlySpan<byte> utf8PropertyName, int value) { }
public void WriteNumber(System.ReadOnlySpan<byte> utf8PropertyName, long value) { }
public void WriteNumber(System.ReadOnlySpan<byte> utf8PropertyName, float value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(System.ReadOnlySpan<byte> utf8PropertyName, uint value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(System.ReadOnlySpan<byte> utf8PropertyName, ulong value) { }
public void WriteNumber(System.ReadOnlySpan<char> propertyName, decimal value) { }
public void WriteNumber(System.ReadOnlySpan<char> propertyName, double value) { }
public void WriteNumber(System.ReadOnlySpan<char> propertyName, int value) { }
public void WriteNumber(System.ReadOnlySpan<char> propertyName, long value) { }
public void WriteNumber(System.ReadOnlySpan<char> propertyName, float value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(System.ReadOnlySpan<char> propertyName, uint value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(System.ReadOnlySpan<char> propertyName, ulong value) { }
public void WriteNumber(string propertyName, decimal value) { }
public void WriteNumber(string propertyName, double value) { }
public void WriteNumber(string propertyName, int value) { }
public void WriteNumber(string propertyName, long value) { }
public void WriteNumber(string propertyName, float value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(string propertyName, uint value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(string propertyName, ulong value) { }
public void WriteNumber(System.Text.Json.JsonEncodedText propertyName, decimal value) { }
public void WriteNumber(System.Text.Json.JsonEncodedText propertyName, double value) { }
public void WriteNumber(System.Text.Json.JsonEncodedText propertyName, int value) { }
public void WriteNumber(System.Text.Json.JsonEncodedText propertyName, long value) { }
public void WriteNumber(System.Text.Json.JsonEncodedText propertyName, float value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(System.Text.Json.JsonEncodedText propertyName, uint value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumber(System.Text.Json.JsonEncodedText propertyName, ulong value) { }
public void WriteNumberValue(decimal value) { }
public void WriteNumberValue(double value) { }
public void WriteNumberValue(int value) { }
public void WriteNumberValue(long value) { }
public void WriteNumberValue(float value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumberValue(uint value) { }
[System.CLSCompliantAttribute(false)]
public void WriteNumberValue(ulong value) { }
public void WritePropertyName(System.ReadOnlySpan<byte> utf8PropertyName) { }
public void WritePropertyName(System.ReadOnlySpan<char> propertyName) { }
public void WritePropertyName(string propertyName) { }
public void WritePropertyName(System.Text.Json.JsonEncodedText propertyName) { }
public void WriteStartArray() { }
public void WriteStartArray(System.ReadOnlySpan<byte> utf8PropertyName) { }
public void WriteStartArray(System.ReadOnlySpan<char> propertyName) { }
public void WriteStartArray(string propertyName) { }
public void WriteStartArray(System.Text.Json.JsonEncodedText propertyName) { }
public void WriteStartObject() { }
public void WriteStartObject(System.ReadOnlySpan<byte> utf8PropertyName) { }
public void WriteStartObject(System.ReadOnlySpan<char> propertyName) { }
public void WriteStartObject(string propertyName) { }
public void WriteStartObject(System.Text.Json.JsonEncodedText propertyName) { }
public void WriteString(System.ReadOnlySpan<byte> utf8PropertyName, System.DateTime value) { }
public void WriteString(System.ReadOnlySpan<byte> utf8PropertyName, System.DateTimeOffset value) { }
public void WriteString(System.ReadOnlySpan<byte> utf8PropertyName, System.Guid value) { }
public void WriteString(System.ReadOnlySpan<byte> utf8PropertyName, System.ReadOnlySpan<byte> utf8Value) { }
public void WriteString(System.ReadOnlySpan<byte> utf8PropertyName, System.ReadOnlySpan<char> value) { }
public void WriteString(System.ReadOnlySpan<byte> utf8PropertyName, string value) { }
public void WriteString(System.ReadOnlySpan<byte> utf8PropertyName, System.Text.Json.JsonEncodedText value) { }
public void WriteString(System.ReadOnlySpan<char> propertyName, System.DateTime value) { }
public void WriteString(System.ReadOnlySpan<char> propertyName, System.DateTimeOffset value) { }
public void WriteString(System.ReadOnlySpan<char> propertyName, System.Guid value) { }
public void WriteString(System.ReadOnlySpan<char> propertyName, System.ReadOnlySpan<byte> utf8Value) { }
public void WriteString(System.ReadOnlySpan<char> propertyName, System.ReadOnlySpan<char> value) { }
public void WriteString(System.ReadOnlySpan<char> propertyName, string value) { }
public void WriteString(System.ReadOnlySpan<char> propertyName, System.Text.Json.JsonEncodedText value) { }
public void WriteString(string propertyName, System.DateTime value) { }
public void WriteString(string propertyName, System.DateTimeOffset value) { }
public void WriteString(string propertyName, System.Guid value) { }
public void WriteString(string propertyName, System.ReadOnlySpan<byte> utf8Value) { }
public void WriteString(string propertyName, System.ReadOnlySpan<char> value) { }
public void WriteString(string propertyName, string value) { }
public void WriteString(string propertyName, System.Text.Json.JsonEncodedText value) { }
public void WriteString(System.Text.Json.JsonEncodedText propertyName, System.DateTime value) { }
public void WriteString(System.Text.Json.JsonEncodedText propertyName, System.DateTimeOffset value) { }
public void WriteString(System.Text.Json.JsonEncodedText propertyName, System.Guid value) { }
public void WriteString(System.Text.Json.JsonEncodedText propertyName, System.ReadOnlySpan<byte> utf8Value) { }
public void WriteString(System.Text.Json.JsonEncodedText propertyName, System.ReadOnlySpan<char> value) { }
public void WriteString(System.Text.Json.JsonEncodedText propertyName, string value) { }
public void WriteString(System.Text.Json.JsonEncodedText propertyName, System.Text.Json.JsonEncodedText value) { }
public void WriteStringValue(System.DateTime value) { }
public void WriteStringValue(System.DateTimeOffset value) { }
public void WriteStringValue(System.Guid value) { }
public void WriteStringValue(System.ReadOnlySpan<byte> utf8Value) { }
public void WriteStringValue(System.ReadOnlySpan<char> value) { }
public void WriteStringValue(string value) { }
public void WriteStringValue(System.Text.Json.JsonEncodedText value) { }
}
}
namespace System.Text.Json.Serialization
{
public abstract partial class JsonAttribute : System.Attribute
{
protected JsonAttribute() { }
}
public abstract partial class JsonConverter
{
internal JsonConverter() { }
public abstract bool CanConvert(System.Type typeToConvert);
}
[System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Property | System.AttributeTargets.Struct, AllowMultiple=false)]
public partial class JsonConverterAttribute : System.Text.Json.Serialization.JsonAttribute
{
protected JsonConverterAttribute() { }
public JsonConverterAttribute(System.Type converterType) { }
public System.Type ConverterType { get { throw null; } }
public virtual System.Text.Json.Serialization.JsonConverter CreateConverter(System.Type typeToConvert) { throw null; }
}
public abstract partial class JsonConverterFactory : System.Text.Json.Serialization.JsonConverter
{
protected JsonConverterFactory() { }
public abstract System.Text.Json.Serialization.JsonConverter CreateConverter(System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options);
}
public abstract partial class JsonConverter<T> : System.Text.Json.Serialization.JsonConverter
{
protected internal JsonConverter() { }
public override bool CanConvert(System.Type typeToConvert) { throw null; }
public abstract T Read(ref System.Text.Json.Utf8JsonReader reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options);
public abstract void Write(System.Text.Json.Utf8JsonWriter writer, T value, System.Text.Json.JsonSerializerOptions options);
}
[System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false)]
public sealed partial class JsonExtensionDataAttribute : System.Text.Json.Serialization.JsonAttribute
{
public JsonExtensionDataAttribute() { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false)]
public sealed partial class JsonIgnoreAttribute : System.Text.Json.Serialization.JsonAttribute
{
public JsonIgnoreAttribute() { }
}
[System.AttributeUsageAttribute(System.AttributeTargets.Property, AllowMultiple=false)]
public sealed partial class JsonPropertyNameAttribute : System.Text.Json.Serialization.JsonAttribute
{
public JsonPropertyNameAttribute(string name) { }
public string Name { get { throw null; } }
}
public sealed partial class JsonStringEnumConverter : System.Text.Json.Serialization.JsonConverterFactory
{
public JsonStringEnumConverter() { }
public JsonStringEnumConverter(System.Text.Json.JsonNamingPolicy namingPolicy = null, bool allowIntegerValues = true) { }
public override bool CanConvert(System.Type typeToConvert) { throw null; }
public override System.Text.Json.Serialization.JsonConverter CreateConverter(System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options) { throw null; }
}
}
| |
#region Copyright
/*Copyright (C) 2015 Konstantin Udilovich
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.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kodestruct.Common.Mathematics;
namespace Kodestruct.Common.Section
{
/// <summary>
/// A shape that has double circular flare. This shape is used to calculate double
/// filleted area properties, for example fillet area of wide flange section
/// </summary>
public class PartWithDoubleFillet : CompoundShapePart
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="FilletSize">Height of circular spandrel (e.g "k" dimension for wide flange I-beams).</param>
/// <param name="RectangleWidth">Solid rectangle width (e.g web width for wide flange I-beams). </param>
/// <param name="InsertionPoint"> Insertion point (at wider part). </param>
/// <param name="IsTopWidened">Defines if wider part is at the top or bottom.</param>
///
public PartWithDoubleFillet(double FilletSize, double RectangleWidth, Point2D InsertionPoint, bool IsTopWidened)
{
this.Size = FilletSize;
this.InsertionPoint = InsertionPoint;
isTopWidened = IsTopWidened;
this.SolidRectangleWidth = RectangleWidth;
}
public override double GetHeight()
{
double h;
if (Size>0)
{
h = Math.Abs(Centroid.Y - InsertionPoint.Y) * 2;
}
else
{
h = 0.0;
}
return h;
}
protected override double GetActualHeight()
{
return this.Size;
}
public override double GetWidth()
{
double b;
if (Size>0)
{
double h = Math.Abs(Centroid.Y - InsertionPoint.Y) * 2;
double A = GetArea();
b = A / h;
}
else
{
b = 0.0;
}
return b;
}
protected override double GetYmax()
{
return this.InsertionPoint.Y;
}
protected override double GetYmin()
{
return this.InsertionPoint.Y - this.Size;
}
protected bool isTopWidened;
public bool IsTopWidened
{
get { return isTopWidened; }
}
public override double GetMomentOfInertia()
{
double IxCircularShapes = 2 * GetCircularSpandrelMomentOfInertia();
double ybarCir = IsTopWidened ? (InsertionPoint.Y - GetCircularSpandrelCentroid()) - this.Centroid.Y : this.Centroid.Y -(InsertionPoint.Y + GetCircularSpandrelCentroid()) ;
double IxCircularAreas = 2* GetCircularSpandrelArea() * Math.Pow(ybarCir, 2);
double IxRectShape = b_rect * Math.Pow(r, 3) / 12.0;
double ybarRect = IsTopWidened ? Centroid.Y - (InsertionPoint.Y - r / 2.0) : Centroid.Y - (InsertionPoint.Y + r / 2.0);
double IxRectArea = SolidRectangleWidth * r * Math.Pow(ybarRect, 2);
double Ix = IxCircularShapes + IxCircularAreas + IxRectShape + IxRectArea;
return Ix;
}
//public override double GetMomentOfInertiaY()
//{
// double IyCircularShapes = 2 * GetCircularSpandrelMomentOfInertia();
// double xbarCir = GetCircularSpandrelCentroid() + b_rect / 2;
// double IyCircularAreas = 2* GetCircularSpandrelArea() * Math.Pow(xbarCir, 2);
// double IyRectShape = r * Math.Pow(b_rect, 3) / 12.0;
// double Iy = IyCircularShapes + IyCircularAreas + IyRectShape;
// return Iy;
//}
protected double r;
/// <summary>
/// Circlar fillet radius
/// </summary>
public double Size
{
get { return r;}
set { r = value;}
}
protected double b_rect;
public double SolidRectangleWidth
{
get { return b_rect; }
set { b_rect = value; }
}
/// <summary>
/// Area of combinedshape (1 rectangle + 2 quarter circles)
/// </summary>
/// <returns></returns>
public override double GetArea()
{
if (Size>0)
{
double A_rect = r * b_rect;
double A_circ = GetCircularSpandrelArea();
return 2 * A_circ + A_rect;
}
else
{
return 0.0;
}
}
protected double GetCircularSpandrelArea()
{
double A_circ = (1 - ((Math.PI) / (4))) * Math.Pow(r, 2);
return A_circ;
}
protected double GetCircularSpandrelMomentOfInertia()
{
double IxCircularShapeFlat = (1 - 5.0 / 16.0 * Math.PI) * Math.Pow(r, 4); // this is with respect to flat portion axis
// to get the Moment of Inertia with respect to centroidal axis of the shape
double IxCircularShape = IxCircularShapeFlat - (GetCircularSpandrelArea() * Math.Pow(GetCircularSpandrelCentroid(), 2));
return IxCircularShape;
}
/// <summary>
/// Centoid of the circular part of component
/// </summary>
/// <param name="IsTopWide"></param>
/// <returns></returns>
protected double GetCircularSpandrelCentroid()
{
double yc;
double y_botWide ;
y_botWide=(((10-3*Math.PI)*r) / (3*(4-Math.PI)));
//if (IsTopWidened)
// {
// yc = r-y_botWide;
// }
//else
// {
yc = y_botWide;
//}
return yc;
}
Point2D centroid;
/// <summary>
/// Gets centroid of combined component double quarter-circle + rectangle.
/// </summary>
/// <returns></returns>
public override Point2D GetCentroid()
{
if (Size >0)
{
if (centroid == null)
{
double y_c;
double y_circ;
y_circ = GetCircularSpandrelCentroid();
y_c = (2 * GetCircularSpandrelArea() * GetCircularSpandrelCentroid() + b_rect * r * r / 2.0) / GetArea();
if (this.isTopWidened == true)
{
centroid = new Point2D(InsertionPoint.X, InsertionPoint.Y - y_c);
}
else
{
centroid = new Point2D(InsertionPoint.X, InsertionPoint.Y + y_c);
}
}
}
else
{
centroid = new Point2D(InsertionPoint.X, InsertionPoint.Y);
}
return centroid;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using OrchardCore.Modules;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Metadata.Models;
using OrchardCore.ContentManagement.Metadata.Settings;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Records;
using OrchardCore.ContentTypes.Events;
using OrchardCore.ContentTypes.ViewModels;
using OrchardCore.Mvc.Utilities;
using YesSql;
namespace OrchardCore.ContentTypes.Services
{
public class ContentDefinitionService : IContentDefinitionService
{
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly IEnumerable<IContentDefinitionEventHandler> _contentDefinitionEventHandlers;
private readonly IContentManager _contentManager;
private readonly ISession _session;
private readonly IEnumerable<ContentPart> _contentParts;
private readonly IEnumerable<ContentField> _contentFields;
public ContentDefinitionService(
IContentDefinitionManager contentDefinitionManager,
IEnumerable<IContentDefinitionEventHandler> contentDefinitionEventHandlers,
IContentManager contentManager,
ISession session,
IEnumerable<ContentPart> contentParts,
IEnumerable<ContentField> contentFields,
ILogger<IContentDefinitionService> logger,
IStringLocalizer<ContentDefinitionService> localizer)
{
_session = session;
_contentManager = contentManager;
_contentDefinitionManager = contentDefinitionManager;
_contentDefinitionEventHandlers = contentDefinitionEventHandlers;
_contentParts = contentParts;
_contentFields = contentFields;
Logger = logger;
T = localizer;
}
public ILogger Logger { get; }
public IStringLocalizer T { get; set; }
public IEnumerable<EditTypeViewModel> GetTypes()
{
return _contentDefinitionManager
.ListTypeDefinitions()
.Select(ctd => new EditTypeViewModel(ctd))
.OrderBy(m => m.DisplayName);
}
public EditTypeViewModel GetType(string name)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(name);
if (contentTypeDefinition == null)
{
return null;
}
return new EditTypeViewModel(contentTypeDefinition);
}
public ContentTypeDefinition AddType(string name, string displayName)
{
if (String.IsNullOrWhiteSpace(displayName))
{
throw new ArgumentException(nameof(displayName));
}
if (String.IsNullOrWhiteSpace(name))
{
name = GenerateContentTypeNameFromDisplayName(displayName);
}
else {
if (!name[0].IsLetter())
{
throw new ArgumentException("Content type name must start with a letter", "name");
}
}
while (_contentDefinitionManager.GetTypeDefinition(name) != null)
name = VersionName(name);
var contentTypeDefinition = new ContentTypeDefinition(name, displayName);
_contentDefinitionManager.StoreTypeDefinition(contentTypeDefinition);
// Ensure it has its own part
_contentDefinitionManager.AlterTypeDefinition(name, builder => builder.WithPart(name));
_contentDefinitionManager.AlterTypeDefinition(name, cfg => cfg.Creatable().Draftable().Listable().Securable());
_contentDefinitionEventHandlers.Invoke(x => x.ContentTypeCreated(new ContentTypeCreatedContext { ContentTypeDefinition = contentTypeDefinition }), Logger);
return contentTypeDefinition;
}
public void RemoveType(string name, bool deleteContent)
{
// first remove all attached parts
var typeDefinition = _contentDefinitionManager.GetTypeDefinition(name);
var partDefinitions = typeDefinition.Parts.ToArray();
foreach (var partDefinition in partDefinitions)
{
RemovePartFromType(partDefinition.PartDefinition.Name, name);
// delete the part if it's its own part
if (partDefinition.PartDefinition.Name == name)
{
RemovePart(name);
}
}
_contentDefinitionManager.DeleteTypeDefinition(name);
// TODO: Create a scheduled job to delete the content items
if (deleteContent)
{
var contentItems = _session
.Query<ContentItem, ContentItemIndex>(x => x.ContentType == name)
.ListAsync().GetAwaiter().GetResult();
foreach (var contentItem in contentItems)
{
_session.Delete(contentItem);
}
}
_contentDefinitionEventHandlers.Invoke(x => x.ContentTypeRemoved(new ContentTypeRemovedContext { ContentTypeDefinition = typeDefinition }), Logger);
}
public void AddPartToType(string partName, string typeName)
{
_contentDefinitionManager.AlterTypeDefinition(typeName, typeBuilder => typeBuilder.WithPart(partName));
_contentDefinitionEventHandlers.Invoke(x => x.ContentPartAttached(new ContentPartAttachedContext { ContentTypeName = typeName, ContentPartName = partName }), Logger);
}
public void AddReusablePartToType(string name, string displayName, string description, string partName, string typeName)
{
_contentDefinitionManager.AlterTypeDefinition(typeName, typeBuilder => typeBuilder.WithPart(name, partName, cfg =>
{
cfg.WithDisplayName(displayName);
cfg.WithDescription(description);
}));
_contentDefinitionEventHandlers.Invoke(x => x.ContentPartAttached(new ContentPartAttachedContext { ContentTypeName = typeName, ContentPartName = partName }), Logger);
}
public void RemovePartFromType(string partName, string typeName)
{
_contentDefinitionManager.AlterTypeDefinition(typeName, typeBuilder => typeBuilder.RemovePart(partName));
_contentDefinitionEventHandlers.Invoke(x => x.ContentPartDetached(new ContentPartDetachedContext { ContentTypeName = typeName, ContentPartName = partName }), Logger);
}
public IEnumerable<EditPartViewModel> GetParts(bool metadataPartsOnly)
{
var typeNames = new HashSet<string>(GetTypes().Select(ctd => ctd.Name));
// user-defined parts
// except for those parts with the same name as a type (implicit type's part or a mistake)
var userContentParts = _contentDefinitionManager.ListPartDefinitions()
.Where(cpd => !typeNames.Contains(cpd.Name))
.Select(cpd => new EditPartViewModel(cpd))
.ToDictionary(
k => k.Name,
v => v);
// code-defined parts
var codeDefinedParts = metadataPartsOnly
? Enumerable.Empty<EditPartViewModel>()
: _contentParts
.Where(cpd => !userContentParts.ContainsKey(cpd.GetType().Name))
.Select(cpi => new EditPartViewModel { Name = cpi.GetType().Name, DisplayName = cpi.GetType().Name })
.ToList();
// Order by display name
return codeDefinedParts
.Union(userContentParts.Values)
.OrderBy(m => m.DisplayName);
}
public EditPartViewModel GetPart(string name)
{
var contentPartDefinition = _contentDefinitionManager.GetPartDefinition(name);
if (contentPartDefinition == null)
{
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition(name);
if(contentTypeDefinition == null)
{
return null;
}
contentPartDefinition = new ContentPartDefinition(name);
}
var viewModel = new EditPartViewModel(contentPartDefinition);
return viewModel;
}
public EditPartViewModel AddPart(CreatePartViewModel partViewModel)
{
var name = partViewModel.Name;
if (_contentDefinitionManager.GetPartDefinition(name) != null)
throw new Exception(T["Cannot add part named '{0}'. It already exists.", name]);
if (!string.IsNullOrEmpty(name))
{
_contentDefinitionManager.AlterPartDefinition(name, builder => builder.Attachable());
var partDefinition = _contentDefinitionManager.GetPartDefinition(name);
_contentDefinitionEventHandlers.Invoke(x => x.ContentPartCreated(new ContentPartCreatedContext { ContentPartDefinition = partDefinition }), Logger);
return new EditPartViewModel(partDefinition);
}
return null;
}
public void RemovePart(string name)
{
var partDefinition = _contentDefinitionManager.GetPartDefinition(name);
if (partDefinition == null)
{
// Couldn't find this named part, ignore it
return;
}
var fieldDefinitions = partDefinition.Fields.ToArray();
foreach (var fieldDefinition in fieldDefinitions)
{
RemoveFieldFromPart(fieldDefinition.Name, name);
}
_contentDefinitionManager.DeletePartDefinition(name);
_contentDefinitionEventHandlers.Invoke(x => x.ContentPartRemoved(new ContentPartRemovedContext { ContentPartDefinition = partDefinition }), Logger);
}
public IEnumerable<Type> GetFields()
{
return _contentFields.Select(x => x.GetType()).ToList();
}
public void AddFieldToPart(string fieldName, string fieldTypeName, string partName)
{
AddFieldToPart(fieldName, fieldName, fieldTypeName, partName);
}
public void AddFieldToPart(string fieldName, string displayName, string fieldTypeName, string partName)
{
if (String.IsNullOrEmpty(fieldName))
{
throw new ArgumentException(nameof(fieldName));
}
var partDefinition = _contentDefinitionManager.GetPartDefinition(partName);
var typeDefinition = _contentDefinitionManager.GetTypeDefinition(partName);
// If the type exists ensure it has its own part
if (typeDefinition != null)
{
_contentDefinitionManager.AlterTypeDefinition(partName, builder => builder.WithPart(partName));
}
fieldName = fieldName.ToSafeName();
_contentDefinitionManager.AlterPartDefinition(partName,
partBuilder => partBuilder.WithField(fieldName, fieldBuilder => fieldBuilder.OfType(fieldTypeName).WithDisplayName(displayName)));
_contentDefinitionEventHandlers.Invoke(x => x.ContentFieldAttached(new ContentFieldAttachedContext
{
ContentPartName = partName,
ContentFieldTypeName = fieldTypeName,
ContentFieldName = fieldName,
ContentFieldDisplayName = displayName
}), Logger);
}
public void RemoveFieldFromPart(string fieldName, string partName)
{
_contentDefinitionManager.AlterPartDefinition(partName, typeBuilder => typeBuilder.RemoveField(fieldName));
_contentDefinitionEventHandlers.Invoke(x => x.ContentFieldDetached(new ContentFieldDetachedContext
{
ContentPartName = partName,
ContentFieldName = fieldName
}), Logger);
}
public void AlterField(EditPartViewModel partViewModel, EditFieldViewModel fieldViewModel)
{
_contentDefinitionManager.AlterPartDefinition(partViewModel.Name, partBuilder =>
{
partBuilder.WithField(fieldViewModel.Name, fieldBuilder =>
{
fieldBuilder.WithDisplayName(fieldViewModel.DisplayName);
});
});
}
public void AlterTypePart(EditTypePartViewModel typePartViewModel)
{
var typeDefinition = typePartViewModel.TypePartDefinition.ContentTypeDefinition;
_contentDefinitionManager.AlterTypeDefinition(typeDefinition.Name, type =>
{
type.WithPart(typePartViewModel.Name, typePartViewModel.TypePartDefinition.PartDefinition, part =>
{
part.WithDisplayName(typePartViewModel.DisplayName);
part.WithDescription(typePartViewModel.Description);
});
});
}
public void AlterTypePartsOrder(ContentTypeDefinition typeDefinition, string[] partNames)
{
_contentDefinitionManager.AlterTypeDefinition(typeDefinition.Name, type =>
{
for (var i = 0; i < partNames.Length; i++)
{
var partDefinition = typeDefinition.Parts.FirstOrDefault(x => x.Name == partNames[i]);
type.WithPart(partNames[i], partDefinition.PartDefinition, part =>
{
part.WithSetting("Position", i.ToString());
});
}
});
}
public void AlterPartFieldsOrder(ContentPartDefinition partDefinition, string[] fieldNames)
{
_contentDefinitionManager.AlterPartDefinition(partDefinition.Name, type =>
{
for (var i = 0; i < fieldNames.Length; i++)
{
var fieldDefinition = partDefinition.Fields.FirstOrDefault(x => x.Name == fieldNames[i]);
type.WithField(fieldNames[i], field =>
{
field.WithSetting("Position", i.ToString());
});
}
});
}
public string GenerateContentTypeNameFromDisplayName(string displayName)
{
displayName = displayName.ToSafeName();
while (_contentDefinitionManager.GetTypeDefinition(displayName) != null)
displayName = VersionName(displayName);
return displayName;
}
public string GenerateFieldNameFromDisplayName(string partName, string displayName)
{
IEnumerable<ContentPartFieldDefinition> fieldDefinitions;
var part = _contentDefinitionManager.GetPartDefinition(partName);
displayName = displayName.ToSafeName();
if (part == null)
{
var type = _contentDefinitionManager.GetTypeDefinition(partName);
if (type == null)
{
throw new ArgumentException("The part doesn't exist: " + partName);
}
var typePart = type.Parts.FirstOrDefault(x => x.PartDefinition.Name == partName);
// id passed in might be that of a type w/ no implicit field
if (typePart == null)
{
return displayName;
}
else {
fieldDefinitions = typePart.PartDefinition.Fields.ToArray();
}
}
else {
fieldDefinitions = part.Fields.ToArray();
}
while (fieldDefinitions.Any(x => String.Equals(displayName.Trim(), x.Name.Trim(), StringComparison.OrdinalIgnoreCase)))
displayName = VersionName(displayName);
return displayName;
}
private static string VersionName(string name)
{
int version;
var nameParts = name.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
if (nameParts.Length > 1 && int.TryParse(nameParts.Last(), out version))
{
version = version > 0 ? ++version : 2;
//this could unintentionally chomp something that looks like a version
name = string.Join("-", nameParts.Take(nameParts.Length - 1));
}
else {
version = 2;
}
return string.Format("{0}-{1}", name, version);
}
}
}
| |
// 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.ComponentModel; //Component
using System.Data.Common;
using System.Diagnostics;
using System.Runtime.CompilerServices;
// todo:
// There may be two ways to improve performance:
// 1. pool statements on the connection object
// 2. Do not create a datareader object for non-datareader returning command execution.
//
// We do not want to do the effort unless we have to squeze performance.
namespace System.Data.Odbc
{
public sealed class OdbcCommand : DbCommand, ICloneable
{
private static int s_objectTypeCount; // Bid counter
internal readonly int ObjectID = System.Threading.Interlocked.Increment(ref s_objectTypeCount);
private string _commandText;
private CommandType _commandType;
private int _commandTimeout = ADP.DefaultCommandTimeout;
private UpdateRowSource _updatedRowSource = UpdateRowSource.Both;
private bool _designTimeInvisible;
private bool _isPrepared; // true if the command is prepared
private OdbcConnection _connection;
private OdbcTransaction _transaction;
private WeakReference _weakDataReaderReference;
private CMDWrapper _cmdWrapper;
private OdbcParameterCollection _parameterCollection; // Parameter collection
private ConnectionState _cmdState;
public OdbcCommand() : base()
{
GC.SuppressFinalize(this);
}
public OdbcCommand(string cmdText) : this()
{
// note: arguments are assigned to properties so we do not have to trace them.
// We still need to include them into the argument list of the definition!
CommandText = cmdText;
}
public OdbcCommand(string cmdText, OdbcConnection connection) : this()
{
CommandText = cmdText;
Connection = connection;
}
public OdbcCommand(string cmdText, OdbcConnection connection, OdbcTransaction transaction) : this()
{
CommandText = cmdText;
Connection = connection;
Transaction = transaction;
}
private void DisposeDeadDataReader()
{
if (ConnectionState.Fetching == _cmdState)
{
if (null != _weakDataReaderReference && !_weakDataReaderReference.IsAlive)
{
if (_cmdWrapper != null)
{
_cmdWrapper.FreeKeyInfoStatementHandle(ODBC32.STMT.CLOSE);
_cmdWrapper.FreeStatementHandle(ODBC32.STMT.CLOSE);
}
CloseFromDataReader();
}
}
}
private void DisposeDataReader()
{
if (null != _weakDataReaderReference)
{
IDisposable reader = (IDisposable)_weakDataReaderReference.Target;
if ((null != reader) && _weakDataReaderReference.IsAlive)
{
((IDisposable)reader).Dispose();
}
CloseFromDataReader();
}
}
internal void DisconnectFromDataReaderAndConnection()
{
// get a reference to the datareader if it is alive
OdbcDataReader liveReader = null;
if (_weakDataReaderReference != null)
{
OdbcDataReader reader;
reader = (OdbcDataReader)_weakDataReaderReference.Target;
if (_weakDataReaderReference.IsAlive)
{
liveReader = reader;
}
}
// remove reference to this from the live datareader
if (liveReader != null)
{
liveReader.Command = null;
}
_transaction = null;
if (null != _connection)
{
_connection.RemoveWeakReference(this);
_connection = null;
}
// if the reader is dead we have to dismiss the statement
if (liveReader == null)
{
CloseCommandWrapper();
}
// else DataReader now has exclusive ownership
_cmdWrapper = null;
}
protected override void Dispose(bool disposing)
{ // MDAC 65459
if (disposing)
{
// release mananged objects
// in V1.0, V1.1 the Connection,Parameters,CommandText,Transaction where reset
this.DisconnectFromDataReaderAndConnection();
_parameterCollection = null;
CommandText = null;
}
_cmdWrapper = null; // let go of the CommandWrapper
_isPrepared = false;
base.Dispose(disposing); // notify base classes
}
internal bool Canceling
{
get
{
return _cmdWrapper.Canceling;
}
}
public override string CommandText
{
get
{
string value = _commandText;
return ((null != value) ? value : string.Empty);
}
set
{
if (_commandText != value)
{
PropertyChanging();
_commandText = value;
}
}
}
public override int CommandTimeout
{ // V1.2.3300, XXXCommand V1.0.5000
get
{
return _commandTimeout;
}
set
{
if (value < 0)
{
throw ADP.InvalidCommandTimeout(value);
}
if (value != _commandTimeout)
{
PropertyChanging();
_commandTimeout = value;
}
}
}
public void ResetCommandTimeout()
{ // V1.2.3300
if (ADP.DefaultCommandTimeout != _commandTimeout)
{
PropertyChanging();
_commandTimeout = ADP.DefaultCommandTimeout;
}
}
private bool ShouldSerializeCommandTimeout()
{ // V1.2.3300
return (ADP.DefaultCommandTimeout != _commandTimeout);
}
[
DefaultValue(System.Data.CommandType.Text),
]
public override CommandType CommandType
{
get
{
CommandType cmdType = _commandType;
return ((0 != cmdType) ? cmdType : CommandType.Text);
}
set
{
switch (value)
{ // @perfnote: Enum.IsDefined
case CommandType.Text:
case CommandType.StoredProcedure:
PropertyChanging();
_commandType = value;
break;
case CommandType.TableDirect:
throw ODBC.NotSupportedCommandType(value);
default:
throw ADP.InvalidCommandType(value);
}
}
}
public new OdbcConnection Connection
{
get
{
return _connection;
}
set
{
if (value != _connection)
{
PropertyChanging();
this.DisconnectFromDataReaderAndConnection();
Debug.Assert(null == _cmdWrapper, "has CMDWrapper when setting connection");
_connection = value;
//OnSchemaChanged();
}
}
}
protected override DbConnection DbConnection
{ // V1.2.3300
get
{
return Connection;
}
set
{
Connection = (OdbcConnection)value;
}
}
protected override DbParameterCollection DbParameterCollection
{ // V1.2.3300
get
{
return Parameters;
}
}
protected override DbTransaction DbTransaction
{ // V1.2.3300
get
{
return Transaction;
}
set
{
Transaction = (OdbcTransaction)value;
}
}
// @devnote: By default, the cmd object is visible on the design surface (i.e. VS7 Server Tray)
// to limit the number of components that clutter the design surface,
// when the DataAdapter design wizard generates the insert/update/delete commands it will
// set the DesignTimeVisible property to false so that cmds won't appear as individual objects
[
DefaultValue(true),
DesignOnly(true),
Browsable(false),
EditorBrowsableAttribute(EditorBrowsableState.Never),
]
public override bool DesignTimeVisible
{ // V1.2.3300, XXXCommand V1.0.5000
get
{
return !_designTimeInvisible;
}
set
{
_designTimeInvisible = !value;
TypeDescriptor.Refresh(this); // VS7 208845
}
}
internal bool HasParameters
{
get
{
return (null != _parameterCollection);
}
}
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
]
public new OdbcParameterCollection Parameters
{
get
{
if (null == _parameterCollection)
{
_parameterCollection = new OdbcParameterCollection();
}
return _parameterCollection;
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
]
public new OdbcTransaction Transaction
{
get
{
if ((null != _transaction) && (null == _transaction.Connection))
{
_transaction = null; // Dawn of the Dead
}
return _transaction;
}
set
{
if (_transaction != value)
{
PropertyChanging(); // fire event before value is validated
_transaction = value;
}
}
}
[
DefaultValue(System.Data.UpdateRowSource.Both),
]
public override UpdateRowSource UpdatedRowSource
{ // V1.2.3300, XXXCommand V1.0.5000
get
{
return _updatedRowSource;
}
set
{
switch (value)
{ // @perfnote: Enum.IsDefined
case UpdateRowSource.None:
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
_updatedRowSource = value;
break;
default:
throw ADP.InvalidUpdateRowSource(value);
}
}
}
internal OdbcDescriptorHandle GetDescriptorHandle(ODBC32.SQL_ATTR attribute)
{
return _cmdWrapper.GetDescriptorHandle(attribute);
}
// GetStatementHandle
// ------------------
// Try to return a cached statement handle.
//
// Creates a CmdWrapper object if necessary
// If no handle is available a handle will be allocated.
// Bindings will be unbound if a handle is cached and the bindings are invalid.
//
internal CMDWrapper GetStatementHandle()
{
// update the command wrapper object, allocate buffer
// create reader object
//
if (_cmdWrapper == null)
{
_cmdWrapper = new CMDWrapper(_connection);
Debug.Assert(null != _connection, "GetStatementHandle without connection?");
_connection.AddWeakReference(this, OdbcReferenceCollection.CommandTag);
}
if (_cmdWrapper._dataReaderBuf == null)
{
_cmdWrapper._dataReaderBuf = new CNativeBuffer(4096);
}
// if there is already a statement handle we need to do some cleanup
//
if (null == _cmdWrapper.StatementHandle)
{
_isPrepared = false;
_cmdWrapper.CreateStatementHandle();
}
else if ((null != _parameterCollection) && _parameterCollection.RebindCollection)
{
_cmdWrapper.FreeStatementHandle(ODBC32.STMT.RESET_PARAMS);
}
return _cmdWrapper;
}
// OdbcCommand.Cancel()
//
// In ODBC3.0 ... a call to SQLCancel when no processing is done has no effect at all
// (ODBC Programmer's Reference ...)
//
public override void Cancel()
{
CMDWrapper wrapper = _cmdWrapper;
if (null != wrapper)
{
wrapper.Canceling = true;
OdbcStatementHandle stmt = wrapper.StatementHandle;
if (null != stmt)
{
lock (stmt)
{
// Cancel the statement
ODBC32.RetCode retcode = stmt.Cancel();
// copy of StatementErrorHandler, because stmt may become null
switch (retcode)
{
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
// don't fire info message events on cancel
break;
default:
throw wrapper.Connection.HandleErrorNoThrow(stmt, retcode);
}
}
}
}
}
object ICloneable.Clone()
{
OdbcCommand clone = new OdbcCommand();
clone.CommandText = CommandText;
clone.CommandTimeout = this.CommandTimeout;
clone.CommandType = CommandType;
clone.Connection = this.Connection;
clone.Transaction = this.Transaction;
clone.UpdatedRowSource = UpdatedRowSource;
if ((null != _parameterCollection) && (0 < Parameters.Count))
{
OdbcParameterCollection parameters = clone.Parameters;
foreach (ICloneable parameter in Parameters)
{
parameters.Add(parameter.Clone());
}
}
return clone;
}
internal bool RecoverFromConnection()
{
DisposeDeadDataReader();
return (ConnectionState.Closed == _cmdState);
}
private void CloseCommandWrapper()
{
CMDWrapper wrapper = _cmdWrapper;
if (null != wrapper)
{
try
{
wrapper.Dispose();
if (null != _connection)
{
_connection.RemoveWeakReference(this);
}
}
finally
{
_cmdWrapper = null;
}
}
}
internal void CloseFromConnection()
{
if (null != _parameterCollection)
{
_parameterCollection.RebindCollection = true;
}
DisposeDataReader();
CloseCommandWrapper();
_isPrepared = false;
_transaction = null;
}
internal void CloseFromDataReader()
{
_weakDataReaderReference = null;
_cmdState = ConnectionState.Closed;
}
public new OdbcParameter CreateParameter()
{
return new OdbcParameter();
}
protected override DbParameter CreateDbParameter()
{
return CreateParameter();
}
protected override DbDataReader ExecuteDbDataReader(CommandBehavior behavior)
{
return ExecuteReader(behavior);
}
public override int ExecuteNonQuery()
{
using (OdbcDataReader reader = ExecuteReaderObject(0, ADP.ExecuteNonQuery, false))
{
reader.Close();
return reader.RecordsAffected;
}
}
public new OdbcDataReader ExecuteReader()
{
return ExecuteReader(0/*CommandBehavior*/);
}
public new OdbcDataReader ExecuteReader(CommandBehavior behavior)
{
return ExecuteReaderObject(behavior, ADP.ExecuteReader, true);
}
internal OdbcDataReader ExecuteReaderFromSQLMethod(object[] methodArguments,
ODBC32.SQL_API method)
{
return ExecuteReaderObject(CommandBehavior.Default, method.ToString(), true, methodArguments, method);
}
private OdbcDataReader ExecuteReaderObject(CommandBehavior behavior, string method, bool needReader)
{ // MDAC 68324
if ((CommandText == null) || (CommandText.Length == 0))
{
throw (ADP.CommandTextRequired(method));
}
// using all functions to tell ExecuteReaderObject that
return ExecuteReaderObject(behavior, method, needReader, null, ODBC32.SQL_API.SQLEXECDIRECT);
}
private OdbcDataReader ExecuteReaderObject(CommandBehavior behavior,
string method,
bool needReader,
object[] methodArguments,
ODBC32.SQL_API odbcApiMethod)
{ // MDAC 68324
OdbcDataReader localReader = null;
try
{
DisposeDeadDataReader(); // this is a no-op if cmdState is not Fetching
ValidateConnectionAndTransaction(method); // cmdState will change to Executing
if (0 != (CommandBehavior.SingleRow & behavior))
{
// CommandBehavior.SingleRow implies CommandBehavior.SingleResult
behavior |= CommandBehavior.SingleResult;
}
ODBC32.RetCode retcode;
OdbcStatementHandle stmt = GetStatementHandle().StatementHandle;
_cmdWrapper.Canceling = false;
if (null != _weakDataReaderReference)
{
if (_weakDataReaderReference.IsAlive)
{
object target = _weakDataReaderReference.Target;
if (null != target && _weakDataReaderReference.IsAlive)
{
if (!((OdbcDataReader)target).IsClosed)
{
throw ADP.OpenReaderExists(); // MDAC 66411
}
}
}
}
localReader = new OdbcDataReader(this, _cmdWrapper, behavior);
//Set command properties
//Not all drivers support timeout. So fail silently if error
if (!Connection.ProviderInfo.NoQueryTimeout)
{
TrySetStatementAttribute(stmt,
ODBC32.SQL_ATTR.QUERY_TIMEOUT,
(IntPtr)this.CommandTimeout);
}
// todo: If we remember the state we can omit a lot of SQLSetStmtAttrW calls ...
// if we do not create a reader we do not even need to do that
if (needReader)
{
if (Connection.IsV3Driver)
{
if (!Connection.ProviderInfo.NoSqlSoptSSNoBrowseTable && !Connection.ProviderInfo.NoSqlSoptSSHiddenColumns)
{
// Need to get the metadata information
//SQLServer actually requires browse info turned on ahead of time...
//Note: We ignore any failures, since this is SQLServer specific
//We won't specialcase for SQL Server but at least for non-V3 drivers
if (localReader.IsBehavior(CommandBehavior.KeyInfo))
{
if (!_cmdWrapper._ssKeyInfoModeOn)
{
TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.NOBROWSETABLE, (IntPtr)ODBC32.SQL_NB.ON);
TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.HIDDEN_COLUMNS, (IntPtr)ODBC32.SQL_HC.ON);
_cmdWrapper._ssKeyInfoModeOff = false;
_cmdWrapper._ssKeyInfoModeOn = true;
}
}
else
{
if (!_cmdWrapper._ssKeyInfoModeOff)
{
TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.NOBROWSETABLE, (IntPtr)ODBC32.SQL_NB.OFF);
TrySetStatementAttribute(stmt, (ODBC32.SQL_ATTR)ODBC32.SQL_SOPT_SS.HIDDEN_COLUMNS, (IntPtr)ODBC32.SQL_HC.OFF);
_cmdWrapper._ssKeyInfoModeOff = true;
_cmdWrapper._ssKeyInfoModeOn = false;
}
}
}
}
}
if (localReader.IsBehavior(CommandBehavior.KeyInfo) ||
localReader.IsBehavior(CommandBehavior.SchemaOnly))
{
retcode = stmt.Prepare(CommandText);
if (ODBC32.RetCode.SUCCESS != retcode)
{
_connection.HandleError(stmt, retcode);
}
}
bool mustRelease = false;
CNativeBuffer parameterBuffer = _cmdWrapper._nativeParameterBuffer;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
//Handle Parameters
//Note: We use the internal variable as to not instante a new object collection,
//for the common case of using no parameters.
if ((null != _parameterCollection) && (0 < _parameterCollection.Count))
{
int parameterBufferSize = _parameterCollection.CalcParameterBufferSize(this);
if (null == parameterBuffer || parameterBuffer.Length < parameterBufferSize)
{
if (null != parameterBuffer)
{
parameterBuffer.Dispose();
}
parameterBuffer = new CNativeBuffer(parameterBufferSize);
_cmdWrapper._nativeParameterBuffer = parameterBuffer;
}
else
{
parameterBuffer.ZeroMemory();
}
parameterBuffer.DangerousAddRef(ref mustRelease);
_parameterCollection.Bind(this, _cmdWrapper, parameterBuffer);
}
if (!localReader.IsBehavior(CommandBehavior.SchemaOnly))
{
// Can't get the KeyInfo after command execution (SQL Server only since it does not support multiple
// results on the same connection). Stored procedures (SP) do not return metadata before actual execution
// Need to check the column count since the command type may not be set to SP for a SP.
if ((localReader.IsBehavior(CommandBehavior.KeyInfo) || localReader.IsBehavior(CommandBehavior.SchemaOnly))
&& (CommandType != CommandType.StoredProcedure))
{
short cColsAffected;
retcode = stmt.NumberOfResultColumns(out cColsAffected);
if (retcode == ODBC32.RetCode.SUCCESS || retcode == ODBC32.RetCode.SUCCESS_WITH_INFO)
{
if (cColsAffected > 0)
{
localReader.GetSchemaTable();
}
}
else if (retcode == ODBC32.RetCode.NO_DATA)
{
// do nothing
}
else
{
// any other returncode indicates an error
_connection.HandleError(stmt, retcode);
}
}
switch (odbcApiMethod)
{
case ODBC32.SQL_API.SQLEXECDIRECT:
if (localReader.IsBehavior(CommandBehavior.KeyInfo) || _isPrepared)
{
//Already prepared, so use SQLExecute
retcode = stmt.Execute();
// Build metadata here
// localReader.GetSchemaTable();
}
else
{
#if DEBUG
//if (AdapterSwitches.OleDbTrace.TraceInfo) {
// ADP.DebugWriteLine("SQLExecDirectW: " + CommandText);
//}
#endif
//SQLExecDirect
retcode = stmt.ExecuteDirect(CommandText);
}
break;
case ODBC32.SQL_API.SQLTABLES:
retcode = stmt.Tables((string)methodArguments[0], //TableCatalog
(string)methodArguments[1], //TableSchema,
(string)methodArguments[2], //TableName
(string)methodArguments[3]); //TableType
break;
case ODBC32.SQL_API.SQLCOLUMNS:
retcode = stmt.Columns((string)methodArguments[0], //TableCatalog
(string)methodArguments[1], //TableSchema
(string)methodArguments[2], //TableName
(string)methodArguments[3]); //ColumnName
break;
case ODBC32.SQL_API.SQLPROCEDURES:
retcode = stmt.Procedures((string)methodArguments[0], //ProcedureCatalog
(string)methodArguments[1], //ProcedureSchema
(string)methodArguments[2]); //procedureName
break;
case ODBC32.SQL_API.SQLPROCEDURECOLUMNS:
retcode = stmt.ProcedureColumns((string)methodArguments[0], //ProcedureCatalog
(string)methodArguments[1], //ProcedureSchema
(string)methodArguments[2], //procedureName
(string)methodArguments[3]); //columnName
break;
case ODBC32.SQL_API.SQLSTATISTICS:
retcode = stmt.Statistics((string)methodArguments[0], //TableCatalog
(string)methodArguments[1], //TableSchema
(string)methodArguments[2], //TableName
(short)methodArguments[3], //IndexTrpe
(short)methodArguments[4]); //Accuracy
break;
case ODBC32.SQL_API.SQLGETTYPEINFO:
retcode = stmt.GetTypeInfo((short)methodArguments[0]); //SQL Type
break;
default:
// this should NEVER happen
Debug.Fail("ExecuteReaderObjectcalled with unsupported ODBC API method.");
throw ADP.InvalidOperation(method.ToString());
}
//Note: Execute will return NO_DATA for Update/Delete non-row returning queries
if ((ODBC32.RetCode.SUCCESS != retcode) && (ODBC32.RetCode.NO_DATA != retcode))
{
_connection.HandleError(stmt, retcode);
}
} // end SchemaOnly
}
finally
{
if (mustRelease)
{
parameterBuffer.DangerousRelease();
}
}
_weakDataReaderReference = new WeakReference(localReader);
// XXXCommand.Execute should position reader on first row returning result
// any exceptions in the initial non-row returning results should be thrown
// from ExecuteXXX not the DataReader
if (!localReader.IsBehavior(CommandBehavior.SchemaOnly))
{
localReader.FirstResult();
}
_cmdState = ConnectionState.Fetching;
}
finally
{
if (ConnectionState.Fetching != _cmdState)
{
if (null != localReader)
{
// clear bindings so we don't grab output parameters on a failed execute
if (null != _parameterCollection)
{
_parameterCollection.ClearBindings();
}
((IDisposable)localReader).Dispose();
}
if (ConnectionState.Closed != _cmdState)
{
_cmdState = ConnectionState.Closed;
}
}
}
return localReader;
}
public override object ExecuteScalar()
{
object value = null;
using (IDataReader reader = ExecuteReaderObject(0, ADP.ExecuteScalar, false))
{
if (reader.Read() && (0 < reader.FieldCount))
{
value = reader.GetValue(0);
}
reader.Close();
}
return value;
}
internal string GetDiagSqlState()
{
return _cmdWrapper.GetDiagSqlState();
}
private void PropertyChanging()
{
_isPrepared = false;
}
// Prepare
//
// if the CommandType property is set to TableDirect Prepare does nothing.
// if the CommandType property is set to StoredProcedure Prepare should succeed but result
// in a no-op
//
// throw InvalidOperationException
// if the connection is not set
// if the connection is not open
//
public override void Prepare()
{
ODBC32.RetCode retcode;
ValidateOpenConnection(ADP.Prepare);
if (0 != (ConnectionState.Fetching & _connection.InternalState))
{
throw ADP.OpenReaderExists();
}
if (CommandType == CommandType.TableDirect)
{
return; // do nothing
}
DisposeDeadDataReader();
GetStatementHandle();
OdbcStatementHandle stmt = _cmdWrapper.StatementHandle;
retcode = stmt.Prepare(CommandText);
if (ODBC32.RetCode.SUCCESS != retcode)
{
_connection.HandleError(stmt, retcode);
}
_isPrepared = true;
}
private void TrySetStatementAttribute(OdbcStatementHandle stmt, ODBC32.SQL_ATTR stmtAttribute, IntPtr value)
{
ODBC32.RetCode retcode = stmt.SetStatementAttribute(
stmtAttribute,
value,
ODBC32.SQL_IS.UINTEGER);
if (retcode == ODBC32.RetCode.ERROR)
{
string sqlState;
stmt.GetDiagnosticField(out sqlState);
if ((sqlState == "HYC00") || (sqlState == "HY092"))
{
Connection.FlagUnsupportedStmtAttr(stmtAttribute);
}
else
{
// now what? Should we throw?
}
}
}
private void ValidateOpenConnection(string methodName)
{
// see if we have a connection
OdbcConnection connection = Connection;
if (null == connection)
{
throw ADP.ConnectionRequired(methodName);
}
// must have an open and available connection
ConnectionState state = connection.State;
if (ConnectionState.Open != state)
{
throw ADP.OpenConnectionRequired(methodName, state);
}
}
private void ValidateConnectionAndTransaction(string method)
{
if (null == _connection)
{
throw ADP.ConnectionRequired(method);
}
_transaction = _connection.SetStateExecuting(method, Transaction);
_cmdState = ConnectionState.Executing;
}
}
internal sealed class CMDWrapper
{
private OdbcStatementHandle _stmt; // hStmt
private OdbcStatementHandle _keyinfostmt; // hStmt for keyinfo
internal OdbcDescriptorHandle _hdesc; // hDesc
internal CNativeBuffer _nativeParameterBuffer; // Native memory for internal memory management
// (Performance optimization)
internal CNativeBuffer _dataReaderBuf; // Reusable DataReader buffer
private readonly OdbcConnection _connection; // Connection
private bool _canceling; // true if the command is canceling
internal bool _hasBoundColumns;
internal bool _ssKeyInfoModeOn; // tells us if the SqlServer specific options are on
internal bool _ssKeyInfoModeOff; // a tri-state value would be much better ...
internal CMDWrapper(OdbcConnection connection)
{
_connection = connection;
}
internal bool Canceling
{
get
{
return _canceling;
}
set
{
_canceling = value;
}
}
internal OdbcConnection Connection
{
get
{
return _connection;
}
}
internal bool HasBoundColumns
{
// get {
// return _hasBoundColumns;
// }
set
{
_hasBoundColumns = value;
}
}
internal OdbcStatementHandle StatementHandle
{
get { return _stmt; }
}
internal OdbcStatementHandle KeyInfoStatement
{
get
{
return _keyinfostmt;
}
}
internal void CreateKeyInfoStatementHandle()
{
DisposeKeyInfoStatementHandle();
_keyinfostmt = _connection.CreateStatementHandle();
}
internal void CreateStatementHandle()
{
DisposeStatementHandle();
_stmt = _connection.CreateStatementHandle();
}
internal void Dispose()
{
if (null != _dataReaderBuf)
{
_dataReaderBuf.Dispose();
_dataReaderBuf = null;
}
DisposeStatementHandle();
CNativeBuffer buffer = _nativeParameterBuffer;
_nativeParameterBuffer = null;
if (null != buffer)
{
buffer.Dispose();
}
_ssKeyInfoModeOn = false;
_ssKeyInfoModeOff = false;
}
private void DisposeDescriptorHandle()
{
OdbcDescriptorHandle handle = _hdesc;
if (null != handle)
{
_hdesc = null;
handle.Dispose();
}
}
internal void DisposeStatementHandle()
{
DisposeKeyInfoStatementHandle();
DisposeDescriptorHandle();
OdbcStatementHandle handle = _stmt;
if (null != handle)
{
_stmt = null;
handle.Dispose();
}
}
internal void DisposeKeyInfoStatementHandle()
{
OdbcStatementHandle handle = _keyinfostmt;
if (null != handle)
{
_keyinfostmt = null;
handle.Dispose();
}
}
internal void FreeStatementHandle(ODBC32.STMT stmt)
{
DisposeDescriptorHandle();
OdbcStatementHandle handle = _stmt;
if (null != handle)
{
try
{
ODBC32.RetCode retcode;
retcode = handle.FreeStatement(stmt);
StatementErrorHandler(retcode);
}
catch (Exception e)
{
//
if (ADP.IsCatchableExceptionType(e))
{
_stmt = null;
handle.Dispose();
}
throw;
}
}
}
internal void FreeKeyInfoStatementHandle(ODBC32.STMT stmt)
{
OdbcStatementHandle handle = _keyinfostmt;
if (null != handle)
{
try
{
handle.FreeStatement(stmt);
}
catch (Exception e)
{
//
if (ADP.IsCatchableExceptionType(e))
{
_keyinfostmt = null;
handle.Dispose();
}
throw;
}
}
}
// Get the Descriptor Handle for the current statement
//
internal OdbcDescriptorHandle GetDescriptorHandle(ODBC32.SQL_ATTR attribute)
{
OdbcDescriptorHandle hdesc = _hdesc;
if (null == _hdesc)
{
_hdesc = hdesc = new OdbcDescriptorHandle(_stmt, attribute);
}
return hdesc;
}
internal string GetDiagSqlState()
{
string sqlstate;
_stmt.GetDiagnosticField(out sqlstate);
return sqlstate;
}
internal void StatementErrorHandler(ODBC32.RetCode retcode)
{
switch (retcode)
{
case ODBC32.RetCode.SUCCESS:
case ODBC32.RetCode.SUCCESS_WITH_INFO:
_connection.HandleErrorNoThrow(_stmt, retcode);
break;
default:
throw _connection.HandleErrorNoThrow(_stmt, retcode);
}
}
internal void UnbindStmtColumns()
{
if (_hasBoundColumns)
{
FreeStatementHandle(ODBC32.STMT.UNBIND);
_hasBoundColumns = false;
}
}
}
}
| |
/*
* 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.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Xml;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using log4net;
using Nini.Config;
using Nwc.XmlRpc;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Mono.Addins;
using OpenSim.Services.Connectors.Hypergrid;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Services.UserProfilesService;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using Microsoft.CSharp;
namespace OpenSim.Region.CoreModules.Avatar.UserProfiles
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UserProfilesModule")]
public class UserProfileModule : IProfileModule, INonSharedRegionModule
{
/// <summary>
/// Logging
/// </summary>
static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// The pair of Dictionaries are used to handle the switching of classified ads
// by maintaining a cache of classified id to creator id mappings and an interest
// count. The entries are removed when the interest count reaches 0.
Dictionary<UUID, UUID> m_classifiedCache = new Dictionary<UUID, UUID>();
Dictionary<UUID, int> m_classifiedInterest = new Dictionary<UUID, int>();
private JsonRpcRequestManager rpc = new JsonRpcRequestManager();
public Scene Scene
{
get; private set;
}
/// <summary>
/// Gets or sets the ConfigSource.
/// </summary>
/// <value>
/// The configuration
/// </value>
public IConfigSource Config
{
get;
set;
}
/// <summary>
/// Gets or sets the URI to the profile server.
/// </summary>
/// <value>
/// The profile server URI.
/// </value>
public string ProfileServerUri
{
get;
set;
}
IProfileModule ProfileModule
{
get; set;
}
IUserManagement UserManagementModule
{
get; set;
}
/// <summary>
/// Gets or sets a value indicating whether this
/// <see cref="OpenSim.Region.Coremodules.UserProfiles.UserProfileModule"/> is enabled.
/// </summary>
/// <value>
/// <c>true</c> if enabled; otherwise, <c>false</c>.
/// </value>
public bool Enabled
{
get;
set;
}
public string MyGatekeeper
{
get; private set;
}
#region IRegionModuleBase implementation
/// <summary>
/// This is called to initialize the region module. For shared modules, this is called exactly once, after
/// creating the single (shared) instance. For non-shared modules, this is called once on each instance, after
/// the instace for the region has been created.
/// </summary>
/// <param name='source'>
/// Source.
/// </param>
public void Initialise(IConfigSource source)
{
Config = source;
ReplaceableInterface = typeof(IProfileModule);
IConfig profileConfig = Config.Configs["UserProfiles"];
if (profileConfig == null)
{
m_log.Debug("[PROFILES]: UserProfiles disabled, no configuration");
Enabled = false;
return;
}
// If we find ProfileURL then we configure for FULL support
// else we setup for BASIC support
ProfileServerUri = profileConfig.GetString("ProfileServiceURL", "");
if (ProfileServerUri == "")
{
Enabled = false;
return;
}
m_log.Debug("[PROFILES]: Full Profiles Enabled");
ReplaceableInterface = null;
Enabled = true;
MyGatekeeper = Util.GetConfigVarFromSections<string>(source, "GatekeeperURI",
new string[] { "Startup", "Hypergrid", "UserProfiles" }, String.Empty);
}
/// <summary>
/// Adds the region.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void AddRegion(Scene scene)
{
if(!Enabled)
return;
Scene = scene;
Scene.RegisterModuleInterface<IProfileModule>(this);
Scene.EventManager.OnNewClient += OnNewClient;
Scene.EventManager.OnMakeRootAgent += HandleOnMakeRootAgent;
UserManagementModule = Scene.RequestModuleInterface<IUserManagement>();
}
void HandleOnMakeRootAgent (ScenePresence obj)
{
if(obj.PresenceType == PresenceType.Npc)
return;
Util.FireAndForget(delegate
{
GetImageAssets(((IScenePresence)obj).UUID);
}, null, "UserProfileModule.GetImageAssets");
}
/// <summary>
/// Removes the region.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void RemoveRegion(Scene scene)
{
if(!Enabled)
return;
}
/// <summary>
/// This will be called once for every scene loaded. In a shared module this will be multiple times in one
/// instance, while a nonshared module instance will only be called once. This method is called after AddRegion
/// has been called in all modules for that scene, providing an opportunity to request another module's
/// interface, or hook an event from another module.
/// </summary>
/// <param name='scene'>
/// Scene.
/// </param>
public void RegionLoaded(Scene scene)
{
if(!Enabled)
return;
}
/// <summary>
/// If this returns non-null, it is the type of an interface that this module intends to register. This will
/// cause the loader to defer loading of this module until all other modules have been loaded. If no other
/// module has registered the interface by then, this module will be activated, else it will remain inactive,
/// letting the other module take over. This should return non-null ONLY in modules that are intended to be
/// easily replaceable, e.g. stub implementations that the developer expects to be replaced by third party
/// provided modules.
/// </summary>
/// <value>
/// The replaceable interface.
/// </value>
public Type ReplaceableInterface
{
get; private set;
}
/// <summary>
/// Called as the instance is closed.
/// </summary>
public void Close()
{
}
/// <value>
/// The name of the module
/// </value>
/// <summary>
/// Gets the module name.
/// </summary>
public string Name
{
get { return "UserProfileModule"; }
}
#endregion IRegionModuleBase implementation
#region Region Event Handlers
/// <summary>
/// Raises the new client event.
/// </summary>
/// <param name='client'>
/// Client.
/// </param>
void OnNewClient(IClientAPI client)
{
//Profile
client.OnRequestAvatarProperties += RequestAvatarProperties;
client.OnUpdateAvatarProperties += AvatarPropertiesUpdate;
client.OnAvatarInterestUpdate += AvatarInterestsUpdate;
// Classifieds
client.AddGenericPacketHandler("avatarclassifiedsrequest", ClassifiedsRequest);
client.OnClassifiedInfoUpdate += ClassifiedInfoUpdate;
client.OnClassifiedInfoRequest += ClassifiedInfoRequest;
client.OnClassifiedDelete += ClassifiedDelete;
// Picks
client.AddGenericPacketHandler("avatarpicksrequest", PicksRequest);
client.AddGenericPacketHandler("pickinforequest", PickInfoRequest);
client.OnPickInfoUpdate += PickInfoUpdate;
client.OnPickDelete += PickDelete;
// Notes
client.AddGenericPacketHandler("avatarnotesrequest", NotesRequest);
client.OnAvatarNotesUpdate += NotesUpdate;
// Preferences
client.OnUserInfoRequest += UserPreferencesRequest;
client.OnUpdateUserInfo += UpdateUserPreferences;
}
#endregion Region Event Handlers
#region Classified
///
/// <summary>
/// Handles the avatar classifieds request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void ClassifiedsRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID targetID;
UUID.TryParse(args[0], out targetID);
// Can't handle NPC yet...
ScenePresence p = FindPresence(targetID);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
GetUserProfileServerURI(targetID, out serverURI);
UUID creatorId = UUID.Zero;
Dictionary<UUID, string> classifieds = new Dictionary<UUID, string>();
OSDMap parameters= new OSDMap();
UUID.TryParse(args[0], out creatorId);
parameters.Add("creatorId", OSD.FromUUID(creatorId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "avatarclassifiedsrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds);
return;
}
parameters = (OSDMap)Params;
OSDArray list = (OSDArray)parameters["result"];
foreach(OSD map in list)
{
OSDMap m = (OSDMap)map;
UUID cid = m["classifieduuid"].AsUUID();
string name = m["name"].AsString();
classifieds[cid] = name;
lock (m_classifiedCache)
{
if (!m_classifiedCache.ContainsKey(cid))
{
m_classifiedCache.Add(cid,creatorId);
m_classifiedInterest.Add(cid, 0);
}
m_classifiedInterest[cid]++;
}
}
remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds);
}
public void ClassifiedInfoRequest(UUID queryClassifiedID, IClientAPI remoteClient)
{
UUID target = remoteClient.AgentId;
UserClassifiedAdd ad = new UserClassifiedAdd();
ad.ClassifiedId = queryClassifiedID;
lock (m_classifiedCache)
{
if (m_classifiedCache.ContainsKey(queryClassifiedID))
{
target = m_classifiedCache[queryClassifiedID];
m_classifiedInterest[queryClassifiedID] --;
if (m_classifiedInterest[queryClassifiedID] == 0)
{
m_classifiedInterest.Remove(queryClassifiedID);
m_classifiedCache.Remove(queryClassifiedID);
}
}
}
string serverURI = string.Empty;
GetUserProfileServerURI(target, out serverURI);
object Ad = (object)ad;
if(!rpc.JsonRpcRequest(ref Ad, "classifieds_info_query", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error getting classified info", false);
return;
}
ad = (UserClassifiedAdd) Ad;
if(ad.CreatorId == UUID.Zero)
return;
Vector3 globalPos = new Vector3();
Vector3.TryParse(ad.GlobalPos, out globalPos);
remoteClient.SendClassifiedInfoReply(ad.ClassifiedId, ad.CreatorId, (uint)ad.CreationDate, (uint)ad.ExpirationDate,
(uint)ad.Category, ad.Name, ad.Description, ad.ParcelId, (uint)ad.ParentEstate,
ad.SnapshotId, ad.SimName, globalPos, ad.ParcelName, ad.Flags, ad.Price);
}
/// <summary>
/// Classifieds info update.
/// </summary>
/// <param name='queryclassifiedID'>
/// Queryclassified I.
/// </param>
/// <param name='queryCategory'>
/// Query category.
/// </param>
/// <param name='queryName'>
/// Query name.
/// </param>
/// <param name='queryDescription'>
/// Query description.
/// </param>
/// <param name='queryParcelID'>
/// Query parcel I.
/// </param>
/// <param name='queryParentEstate'>
/// Query parent estate.
/// </param>
/// <param name='querySnapshotID'>
/// Query snapshot I.
/// </param>
/// <param name='queryGlobalPos'>
/// Query global position.
/// </param>
/// <param name='queryclassifiedFlags'>
/// Queryclassified flags.
/// </param>
/// <param name='queryclassifiedPrice'>
/// Queryclassified price.
/// </param>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void ClassifiedInfoUpdate(UUID queryclassifiedID, uint queryCategory, string queryName, string queryDescription, UUID queryParcelID,
uint queryParentEstate, UUID querySnapshotID, Vector3 queryGlobalPos, byte queryclassifiedFlags,
int queryclassifiedPrice, IClientAPI remoteClient)
{
UserClassifiedAdd ad = new UserClassifiedAdd();
Scene s = (Scene) remoteClient.Scene;
Vector3 pos = remoteClient.SceneAgent.AbsolutePosition;
ILandObject land = s.LandChannel.GetLandObject(pos.X, pos.Y);
ScenePresence p = FindPresence(remoteClient.AgentId);
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
if (land == null)
{
ad.ParcelName = string.Empty;
}
else
{
ad.ParcelName = land.LandData.Name;
}
ad.CreatorId = remoteClient.AgentId;
ad.ClassifiedId = queryclassifiedID;
ad.Category = Convert.ToInt32(queryCategory);
ad.Name = queryName;
ad.Description = queryDescription;
ad.ParentEstate = Convert.ToInt32(queryParentEstate);
ad.SnapshotId = querySnapshotID;
ad.SimName = remoteClient.Scene.RegionInfo.RegionName;
ad.GlobalPos = queryGlobalPos.ToString ();
ad.Flags = queryclassifiedFlags;
ad.Price = queryclassifiedPrice;
ad.ParcelId = p.currentParcelUUID;
object Ad = ad;
OSD.SerializeMembers(Ad);
if(!rpc.JsonRpcRequest(ref Ad, "classified_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating classified", false);
return;
}
}
/// <summary>
/// Classifieds delete.
/// </summary>
/// <param name='queryClassifiedID'>
/// Query classified I.
/// </param>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void ClassifiedDelete(UUID queryClassifiedID, IClientAPI remoteClient)
{
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
UUID classifiedId;
OSDMap parameters= new OSDMap();
UUID.TryParse(queryClassifiedID.ToString(), out classifiedId);
parameters.Add("classifiedId", OSD.FromUUID(classifiedId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "classified_delete", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error classified delete", false);
return;
}
parameters = (OSDMap)Params;
}
#endregion Classified
#region Picks
/// <summary>
/// Handles the avatar picks request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void PicksRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
UUID targetId;
UUID.TryParse(args[0], out targetId);
// Can't handle NPC yet...
ScenePresence p = FindPresence(targetId);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
GetUserProfileServerURI(targetId, out serverURI);
Dictionary<UUID, string> picks = new Dictionary<UUID, string>();
OSDMap parameters= new OSDMap();
parameters.Add("creatorId", OSD.FromUUID(targetId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "avatarpicksrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarPicksReply(new UUID(args[0]), picks);
return;
}
parameters = (OSDMap)Params;
OSDArray list = (OSDArray)parameters["result"];
foreach(OSD map in list)
{
OSDMap m = (OSDMap)map;
UUID cid = m["pickuuid"].AsUUID();
string name = m["name"].AsString();
m_log.DebugFormat("[PROFILES]: PicksRequest {0}", name);
picks[cid] = name;
}
remoteClient.SendAvatarPicksReply(new UUID(args[0]), picks);
}
/// <summary>
/// Handles the pick info request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void PickInfoRequest(Object sender, string method, List<String> args)
{
if (!(sender is IClientAPI))
return;
UUID targetID;
UUID.TryParse (args [0], out targetID);
string serverURI = string.Empty;
GetUserProfileServerURI (targetID, out serverURI);
string theirGatekeeperURI;
GetUserGatekeeperURI (targetID, out theirGatekeeperURI);
IClientAPI remoteClient = (IClientAPI)sender;
UserProfilePick pick = new UserProfilePick ();
UUID.TryParse (args [0], out pick.CreatorId);
UUID.TryParse (args [1], out pick.PickId);
object Pick = (object)pick;
if (!rpc.JsonRpcRequest (ref Pick, "pickinforequest", serverURI, UUID.Random ().ToString ())) {
remoteClient.SendAgentAlertMessage (
"Error selecting pick", false);
return;
}
pick = (UserProfilePick)Pick;
Vector3 globalPos = new Vector3(Vector3.Zero);
// Smoke and mirrors
if (pick.Gatekeeper == MyGatekeeper)
{
Vector3.TryParse(pick.GlobalPos,out globalPos);
}
else
{
// Setup the illusion
string region = string.Format("{0} {1}",pick.Gatekeeper,pick.SimName);
GridRegion target = Scene.GridService.GetRegionByName(Scene.RegionInfo.ScopeID, region);
if(target == null)
{
// This is a dead or unreachable region
}
else
{
// Work our slight of hand
int x = target.RegionLocX;
int y = target.RegionLocY;
dynamic synthX = globalPos.X - (globalPos.X/Constants.RegionSize) * Constants.RegionSize;
synthX += x;
globalPos.X = synthX;
dynamic synthY = globalPos.Y - (globalPos.Y/Constants.RegionSize) * Constants.RegionSize;
synthY += y;
globalPos.Y = synthY;
}
}
m_log.DebugFormat("[PROFILES]: PickInfoRequest: {0} : {1}", pick.Name.ToString(), pick.SnapshotId.ToString());
// Pull the rabbit out of the hat
remoteClient.SendPickInfoReply(pick.PickId,pick.CreatorId,pick.TopPick,pick.ParcelId,pick.Name,
pick.Desc,pick.SnapshotId,pick.ParcelName,pick.OriginalName,pick.SimName,
globalPos,pick.SortOrder,pick.Enabled);
}
/// <summary>
/// Updates the userpicks
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='pickID'>
/// Pick I.
/// </param>
/// <param name='creatorID'>
/// the creator of the pick
/// </param>
/// <param name='topPick'>
/// Top pick.
/// </param>
/// <param name='name'>
/// Name.
/// </param>
/// <param name='desc'>
/// Desc.
/// </param>
/// <param name='snapshotID'>
/// Snapshot I.
/// </param>
/// <param name='sortOrder'>
/// Sort order.
/// </param>
/// <param name='enabled'>
/// Enabled.
/// </param>
public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc, UUID snapshotID, int sortOrder, bool enabled)
{
//TODO: See how this works with NPC, May need to test
m_log.DebugFormat("[PROFILES]: Start PickInfoUpdate Name: {0} PickId: {1} SnapshotId: {2}", name, pickID.ToString(), snapshotID.ToString());
UserProfilePick pick = new UserProfilePick();
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
ScenePresence p = FindPresence(remoteClient.AgentId);
Vector3 avaPos = p.AbsolutePosition;
// Getting the global position for the Avatar
Vector3 posGlobal = new Vector3(remoteClient.Scene.RegionInfo.WorldLocX + avaPos.X,
remoteClient.Scene.RegionInfo.WorldLocY + avaPos.Y,
avaPos.Z);
string landParcelName = "My Parcel";
UUID landParcelID = p.currentParcelUUID;
ILandObject land = p.Scene.LandChannel.GetLandObject(avaPos.X, avaPos.Y);
if (land != null)
{
// If land found, use parcel uuid from here because the value from SP will be blank if the avatar hasnt moved
landParcelName = land.LandData.Name;
landParcelID = land.LandData.GlobalID;
}
else
{
m_log.WarnFormat(
"[PROFILES]: PickInfoUpdate found no parcel info at {0},{1} in {2}",
avaPos.X, avaPos.Y, p.Scene.Name);
}
pick.PickId = pickID;
pick.CreatorId = creatorID;
pick.TopPick = topPick;
pick.Name = name;
pick.Desc = desc;
pick.ParcelId = landParcelID;
pick.SnapshotId = snapshotID;
pick.ParcelName = landParcelName;
pick.SimName = remoteClient.Scene.RegionInfo.RegionName;
pick.Gatekeeper = MyGatekeeper;
pick.GlobalPos = posGlobal.ToString();
pick.SortOrder = sortOrder;
pick.Enabled = enabled;
object Pick = (object)pick;
if(!rpc.JsonRpcRequest(ref Pick, "picks_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating pick", false);
return;
}
m_log.DebugFormat("[PROFILES]: Finish PickInfoUpdate {0} {1}", pick.Name, pick.PickId.ToString());
}
/// <summary>
/// Delete a Pick
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='queryPickID'>
/// Query pick I.
/// </param>
public void PickDelete(IClientAPI remoteClient, UUID queryPickID)
{
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
OSDMap parameters= new OSDMap();
parameters.Add("pickId", OSD.FromUUID(queryPickID));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "picks_delete", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error picks delete", false);
return;
}
}
#endregion Picks
#region Notes
/// <summary>
/// Handles the avatar notes request.
/// </summary>
/// <param name='sender'>
/// Sender.
/// </param>
/// <param name='method'>
/// Method.
/// </param>
/// <param name='args'>
/// Arguments.
/// </param>
public void NotesRequest(Object sender, string method, List<String> args)
{
UserProfileNotes note = new UserProfileNotes();
if (!(sender is IClientAPI))
return;
IClientAPI remoteClient = (IClientAPI)sender;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
note.UserId = remoteClient.AgentId;
UUID.TryParse(args[0], out note.TargetId);
object Note = (object)note;
if(!rpc.JsonRpcRequest(ref Note, "avatarnotesrequest", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAvatarNotesReply(note.TargetId, note.Notes);
return;
}
note = (UserProfileNotes) Note;
remoteClient.SendAvatarNotesReply(note.TargetId, note.Notes);
}
/// <summary>
/// Avatars the notes update.
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='queryTargetID'>
/// Query target I.
/// </param>
/// <param name='queryNotes'>
/// Query notes.
/// </param>
public void NotesUpdate(IClientAPI remoteClient, UUID queryTargetID, string queryNotes)
{
UserProfileNotes note = new UserProfileNotes();
note.UserId = remoteClient.AgentId;
note.TargetId = queryTargetID;
note.Notes = queryNotes;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Note = note;
if(!rpc.JsonRpcRequest(ref Note, "avatar_notes_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating note", false);
return;
}
}
#endregion Notes
#region User Preferences
/// <summary>
/// Updates the user preferences.
/// </summary>
/// <param name='imViaEmail'>
/// Im via email.
/// </param>
/// <param name='visible'>
/// Visible.
/// </param>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void UpdateUserPreferences(bool imViaEmail, bool visible, IClientAPI remoteClient)
{
UserPreferences pref = new UserPreferences();
pref.UserId = remoteClient.AgentId;
pref.IMViaEmail = imViaEmail;
pref.Visible = visible;
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Pref = pref;
if(!rpc.JsonRpcRequest(ref Pref, "user_preferences_update", serverURI, UUID.Random().ToString()))
{
m_log.InfoFormat("[PROFILES]: UserPreferences update error");
remoteClient.SendAgentAlertMessage("Error updating preferences", false);
return;
}
}
/// <summary>
/// Users the preferences request.
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
public void UserPreferencesRequest(IClientAPI remoteClient)
{
UserPreferences pref = new UserPreferences();
pref.UserId = remoteClient.AgentId;
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Pref = (object)pref;
if(!rpc.JsonRpcRequest(ref Pref, "user_preferences_request", serverURI, UUID.Random().ToString()))
{
// m_log.InfoFormat("[PROFILES]: UserPreferences request error");
// remoteClient.SendAgentAlertMessage("Error requesting preferences", false);
return;
}
pref = (UserPreferences) Pref;
remoteClient.SendUserInfoReply(pref.IMViaEmail, pref.Visible, pref.EMail);
}
#endregion User Preferences
#region Avatar Properties
/// <summary>
/// Update the avatars interests .
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='wantmask'>
/// Wantmask.
/// </param>
/// <param name='wanttext'>
/// Wanttext.
/// </param>
/// <param name='skillsmask'>
/// Skillsmask.
/// </param>
/// <param name='skillstext'>
/// Skillstext.
/// </param>
/// <param name='languages'>
/// Languages.
/// </param>
public void AvatarInterestsUpdate(IClientAPI remoteClient, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages)
{
UserProfileProperties prop = new UserProfileProperties();
prop.UserId = remoteClient.AgentId;
prop.WantToMask = (int)wantmask;
prop.WantToText = wanttext;
prop.SkillsMask = (int)skillsmask;
prop.SkillsText = skillstext;
prop.Language = languages;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Param = prop;
if(!rpc.JsonRpcRequest(ref Param, "avatar_interests_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating interests", false);
return;
}
}
public void RequestAvatarProperties(IClientAPI remoteClient, UUID avatarID)
{
if (String.IsNullOrEmpty(avatarID.ToString()) || String.IsNullOrEmpty(remoteClient.AgentId.ToString()))
{
// Looking for a reason that some viewers are sending null Id's
m_log.DebugFormat("[PROFILES]: This should not happen remoteClient.AgentId {0} - avatarID {1}", remoteClient.AgentId, avatarID);
return;
}
// Can't handle NPC yet...
ScenePresence p = FindPresence(avatarID);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
return;
}
string serverURI = string.Empty;
bool foreign = GetUserProfileServerURI(avatarID, out serverURI);
UserAccount account = null;
Dictionary<string,object> userInfo;
if (!foreign)
{
account = Scene.UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, avatarID);
}
else
{
userInfo = new Dictionary<string, object>();
}
Byte[] charterMember = new Byte[1];
string born = String.Empty;
uint flags = 0x00;
if (null != account)
{
if (account.UserTitle == "")
{
charterMember[0] = (Byte)((account.UserFlags & 0xf00) >> 8);
}
else
{
charterMember = Utils.StringToBytes(account.UserTitle);
}
born = Util.ToDateTime(account.Created).ToString(
"M/d/yyyy", CultureInfo.InvariantCulture);
flags = (uint)(account.UserFlags & 0xff);
}
else
{
if (GetUserAccountData(avatarID, out userInfo) == true)
{
if ((string)userInfo["user_title"] == "")
{
charterMember[0] = (Byte)(((Byte)userInfo["user_flags"] & 0xf00) >> 8);
}
else
{
charterMember = Utils.StringToBytes((string)userInfo["user_title"]);
}
int val_born = (int)userInfo["user_created"];
born = Util.ToDateTime(val_born).ToString(
"M/d/yyyy", CultureInfo.InvariantCulture);
// picky, picky
int val_flags = (int)userInfo["user_flags"];
flags = (uint)(val_flags & 0xff);
}
}
UserProfileProperties props = new UserProfileProperties();
string result = string.Empty;
props.UserId = avatarID;
if (!GetProfileData(ref props, foreign, out result))
{
// m_log.DebugFormat("Error getting profile for {0}: {1}", avatarID, result);
return;
}
remoteClient.SendAvatarProperties(props.UserId, props.AboutText, born, charterMember , props.FirstLifeText, flags,
props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId);
remoteClient.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText, (uint)props.SkillsMask,
props.SkillsText, props.Language);
}
/// <summary>
/// Updates the avatar properties.
/// </summary>
/// <param name='remoteClient'>
/// Remote client.
/// </param>
/// <param name='newProfile'>
/// New profile.
/// </param>
public void AvatarPropertiesUpdate(IClientAPI remoteClient, UserProfileData newProfile)
{
if (remoteClient.AgentId == newProfile.ID)
{
UserProfileProperties prop = new UserProfileProperties();
prop.UserId = remoteClient.AgentId;
prop.WebUrl = newProfile.ProfileUrl;
prop.ImageId = newProfile.Image;
prop.AboutText = newProfile.AboutText;
prop.FirstLifeImageId = newProfile.FirstLifeImage;
prop.FirstLifeText = newProfile.FirstLifeAboutText;
string serverURI = string.Empty;
GetUserProfileServerURI(remoteClient.AgentId, out serverURI);
object Prop = prop;
if(!rpc.JsonRpcRequest(ref Prop, "avatar_properties_update", serverURI, UUID.Random().ToString()))
{
remoteClient.SendAgentAlertMessage(
"Error updating properties", false);
return;
}
RequestAvatarProperties(remoteClient, newProfile.ID);
}
}
/// <summary>
/// Gets the profile data.
/// </summary>
/// <returns>
/// The profile data.
/// </returns>
bool GetProfileData(ref UserProfileProperties properties, bool foreign, out string message)
{
// Can't handle NPC yet...
ScenePresence p = FindPresence(properties.UserId);
if (null != p)
{
if (p.PresenceType == PresenceType.Npc)
{
message = "Id points to NPC";
return false;
}
}
string serverURI = string.Empty;
GetUserProfileServerURI(properties.UserId, out serverURI);
// This is checking a friend on the home grid
// Not HG friend
if (String.IsNullOrEmpty(serverURI))
{
message = "No Presence - foreign friend";
return false;
}
object Prop = (object)properties;
if (!rpc.JsonRpcRequest(ref Prop, "avatar_properties_request", serverURI, UUID.Random().ToString()))
{
// If it's a foreign user then try again using OpenProfile, in case that's what the grid is using
bool secondChanceSuccess = false;
if (foreign)
{
try
{
OpenProfileClient client = new OpenProfileClient(serverURI);
if (client.RequestAvatarPropertiesUsingOpenProfile(ref properties))
secondChanceSuccess = true;
}
catch (Exception e)
{
m_log.Debug(
string.Format(
"[PROFILES]: Request using the OpenProfile API for user {0} to {1} failed",
properties.UserId, serverURI),
e);
// Allow the return 'message' to say "JsonRpcRequest" and not "OpenProfile", because
// the most likely reason that OpenProfile failed is that the remote server
// doesn't support OpenProfile, and that's not very interesting.
}
}
if (!secondChanceSuccess)
{
message = string.Format("JsonRpcRequest for user {0} to {1} failed", properties.UserId, serverURI);
m_log.DebugFormat("[PROFILES]: {0}", message);
return false;
}
// else, continue below
}
properties = (UserProfileProperties)Prop;
message = "Success";
return true;
}
#endregion Avatar Properties
#region Utils
bool GetImageAssets(UUID avatarId)
{
string profileServerURI = string.Empty;
string assetServerURI = string.Empty;
bool foreign = GetUserProfileServerURI(avatarId, out profileServerURI);
if(!foreign)
return true;
assetServerURI = UserManagementModule.GetUserServerURL(avatarId, "AssetServerURI");
if(string.IsNullOrEmpty(profileServerURI) || string.IsNullOrEmpty(assetServerURI))
return false;
OSDMap parameters= new OSDMap();
parameters.Add("avatarId", OSD.FromUUID(avatarId));
OSD Params = (OSD)parameters;
if(!rpc.JsonRpcRequest(ref Params, "image_assets_request", profileServerURI, UUID.Random().ToString()))
{
return false;
}
parameters = (OSDMap)Params;
if (parameters.ContainsKey("result"))
{
OSDArray list = (OSDArray)parameters["result"];
foreach (OSD asset in list)
{
OSDString assetId = (OSDString)asset;
Scene.AssetService.Get(string.Format("{0}/{1}", assetServerURI, assetId.AsString()));
}
return true;
}
else
{
m_log.ErrorFormat("[PROFILES]: Problematic response for image_assets_request from {0}", profileServerURI);
return false;
}
}
/// <summary>
/// Gets the user account data.
/// </summary>
/// <returns>
/// The user profile data.
/// </returns>
/// <param name='userID'>
/// If set to <c>true</c> user I.
/// </param>
/// <param name='userInfo'>
/// If set to <c>true</c> user info.
/// </param>
bool GetUserAccountData(UUID userID, out Dictionary<string, object> userInfo)
{
Dictionary<string,object> info = new Dictionary<string, object>();
if (UserManagementModule.IsLocalGridUser(userID))
{
// Is local
IUserAccountService uas = Scene.UserAccountService;
UserAccount account = uas.GetUserAccount(Scene.RegionInfo.ScopeID, userID);
info["user_flags"] = account.UserFlags;
info["user_created"] = account.Created;
if (!String.IsNullOrEmpty(account.UserTitle))
info["user_title"] = account.UserTitle;
else
info["user_title"] = "";
userInfo = info;
return false;
}
else
{
// Is Foreign
string home_url = UserManagementModule.GetUserServerURL(userID, "HomeURI");
if (String.IsNullOrEmpty(home_url))
{
info["user_flags"] = 0;
info["user_created"] = 0;
info["user_title"] = "Unavailable";
userInfo = info;
return true;
}
UserAgentServiceConnector uConn = new UserAgentServiceConnector(home_url);
Dictionary<string, object> account;
try
{
account = uConn.GetUserInfo(userID);
}
catch (Exception e)
{
m_log.Debug("[PROFILES]: GetUserInfo call failed ", e);
account = new Dictionary<string, object>();
}
if (account.Count > 0)
{
if (account.ContainsKey("user_flags"))
info["user_flags"] = account["user_flags"];
else
info["user_flags"] = "";
if (account.ContainsKey("user_created"))
info["user_created"] = account["user_created"];
else
info["user_created"] = "";
info["user_title"] = "HG Visitor";
}
else
{
info["user_flags"] = 0;
info["user_created"] = 0;
info["user_title"] = "HG Visitor";
}
userInfo = info;
return true;
}
}
/// <summary>
/// Gets the user gatekeeper server URI.
/// </summary>
/// <returns>
/// The user gatekeeper server URI.
/// </returns>
/// <param name='userID'>
/// If set to <c>true</c> user URI.
/// </param>
/// <param name='serverURI'>
/// If set to <c>true</c> server URI.
/// </param>
bool GetUserGatekeeperURI(UUID userID, out string serverURI)
{
bool local;
local = UserManagementModule.IsLocalGridUser(userID);
if (!local)
{
serverURI = UserManagementModule.GetUserServerURL(userID, "GatekeeperURI");
// Is Foreign
return true;
}
else
{
serverURI = MyGatekeeper;
// Is local
return false;
}
}
/// <summary>
/// Gets the user profile server UR.
/// </summary>
/// <returns>
/// The user profile server UR.
/// </returns>
/// <param name='userID'>
/// If set to <c>true</c> user I.
/// </param>
/// <param name='serverURI'>
/// If set to <c>true</c> server UR.
/// </param>
bool GetUserProfileServerURI(UUID userID, out string serverURI)
{
bool local;
local = UserManagementModule.IsLocalGridUser(userID);
if (!local)
{
serverURI = UserManagementModule.GetUserServerURL(userID, "ProfileServerURI");
// Is Foreign
return true;
}
else
{
serverURI = ProfileServerUri;
// Is local
return false;
}
}
/// <summary>
/// Finds the presence.
/// </summary>
/// <returns>
/// The presence.
/// </returns>
/// <param name='clientID'>
/// Client I.
/// </param>
ScenePresence FindPresence(UUID clientID)
{
ScenePresence p;
p = Scene.GetScenePresence(clientID);
if (p != null && !p.IsChildAgent)
return p;
return null;
}
#endregion Util
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.ObjectModel;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.Security.Principal;
using System.Collections.Generic;
using System.Globalization;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.Runtime.Diagnostics;
namespace System.ServiceModel.Security
{
public abstract class IdentityVerifier
{
protected IdentityVerifier()
{
// empty
}
public static IdentityVerifier CreateDefault()
{
return DefaultIdentityVerifier.Instance;
}
public abstract bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext);
public abstract bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity);
static void AdjustAddress(ref EndpointAddress reference, Uri via)
{
// if we don't have an identity and we have differing Uris, we should use the Via
if (reference.Identity == null && reference.Uri != via)
{
reference = new EndpointAddress(via);
}
}
internal void EnsureOutgoingIdentity(EndpointAddress serviceReference, Uri via, AuthorizationContext authorizationContext)
{
AdjustAddress(ref serviceReference, via);
this.EnsureIdentity(serviceReference, authorizationContext, SR.IdentityCheckFailedForOutgoingMessage);
}
internal void EnsureOutgoingIdentity(EndpointAddress serviceReference, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
{
if (authorizationPolicies == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationPolicies");
}
AuthorizationContext ac = AuthorizationContext.CreateDefaultAuthorizationContext(authorizationPolicies);
EnsureIdentity(serviceReference, ac, SR.IdentityCheckFailedForOutgoingMessage);
}
private void EnsureIdentity(EndpointAddress serviceReference, AuthorizationContext authorizationContext, String errorString)
{
if (authorizationContext == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authorizationContext");
}
EndpointIdentity identity;
if (!TryGetIdentity(serviceReference, out identity))
{
SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authorizationContext, this.GetType());
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(errorString, identity, serviceReference)));
}
else
{
if (!CheckAccess(identity, authorizationContext))
{
// CheckAccess performs a Trace on failure, no need to do it twice
Exception e = CreateIdentityCheckException(identity, authorizationContext, errorString, serviceReference);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(e);
}
}
}
private Exception CreateIdentityCheckException(EndpointIdentity identity, AuthorizationContext authorizationContext, string errorString, EndpointAddress serviceReference)
{
Exception result;
if (identity.IdentityClaim != null
&& identity.IdentityClaim.ClaimType == ClaimTypes.Dns
&& identity.IdentityClaim.Right == Rights.PossessProperty
&& identity.IdentityClaim.Resource is string)
{
string expectedDnsName = (string)identity.IdentityClaim.Resource;
string actualDnsName = null;
for (int i = 0; i < authorizationContext.ClaimSets.Count; ++i)
{
ClaimSet claimSet = authorizationContext.ClaimSets[i];
foreach (Claim claim in claimSet.FindClaims(ClaimTypes.Dns, Rights.PossessProperty))
{
if (claim.Resource is string)
{
actualDnsName = (string)claim.Resource;
break;
}
}
if (actualDnsName != null)
{
break;
}
}
if (SR.IdentityCheckFailedForIncomingMessage.Equals(errorString))
{
if (actualDnsName == null)
{
result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForIncomingMessageLackOfDnsClaim, expectedDnsName));
}
else
{
result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForIncomingMessage, expectedDnsName, actualDnsName));
}
}
else if (SR.IdentityCheckFailedForOutgoingMessage.Equals(errorString))
{
if (actualDnsName == null)
{
result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForOutgoingMessageLackOfDnsClaim, expectedDnsName));
}
else
{
result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForOutgoingMessage, expectedDnsName, actualDnsName));
}
}
else
{
result = new MessageSecurityException(SR.Format(errorString, identity, serviceReference));
}
}
else
{
result = new MessageSecurityException(SR.Format(errorString, identity, serviceReference));
}
return result;
}
private class DefaultIdentityVerifier : IdentityVerifier
{
static readonly DefaultIdentityVerifier instance = new DefaultIdentityVerifier();
public static DefaultIdentityVerifier Instance
{
get { return instance; }
}
public override bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity)
{
if (reference == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reference");
identity = reference.Identity;
if (identity == null)
{
identity = this.TryCreateDnsIdentity(reference);
}
if (identity == null)
{
SecurityTraceRecordHelper.TraceIdentityDeterminationFailure(reference, typeof(DefaultIdentityVerifier));
return false;
}
else
{
SecurityTraceRecordHelper.TraceIdentityDeterminationSuccess(reference, identity, typeof(DefaultIdentityVerifier));
return true;
}
}
EndpointIdentity TryCreateDnsIdentity(EndpointAddress reference)
{
Uri toAddress = reference.Uri;
if (!toAddress.IsAbsoluteUri)
return null;
return EndpointIdentity.CreateDnsIdentity(toAddress.DnsSafeHost);
}
internal Claim CheckDnsEquivalence(ClaimSet claimSet, string expectedSpn)
{
// host/<machine-name> satisfies the DNS identity claim
IEnumerable<Claim> claims = claimSet.FindClaims(ClaimTypes.Spn, Rights.PossessProperty);
foreach (Claim claim in claims)
{
if (expectedSpn.Equals((string)claim.Resource, StringComparison.OrdinalIgnoreCase))
{
return claim;
}
}
return null;
}
internal Claim CheckSidEquivalence(SecurityIdentifier identitySid, ClaimSet claimSet)
{
throw ExceptionHelper.PlatformNotSupported("IdentityVerifier.CheckSidEquivalence");
}
public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
{
EventTraceActivity eventTraceActivity = null;
if (identity == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("identity");
if (authContext == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("authContext");
if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity((OperationContext.Current != null) ? OperationContext.Current.IncomingMessage : null);
}
for (int i = 0; i < authContext.ClaimSets.Count; ++i)
{
ClaimSet claimSet = authContext.ClaimSets[i];
if (claimSet.ContainsClaim(identity.IdentityClaim))
{
SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, identity.IdentityClaim, this.GetType());
return true;
}
// try Claim equivalence
string expectedSpn = null;
if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
{
expectedSpn = string.Format(CultureInfo.InvariantCulture, "host/{0}", (string)identity.IdentityClaim.Resource);
Claim claim = CheckDnsEquivalence(claimSet, expectedSpn);
if (claim != null)
{
SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
return true;
}
}
// Allow a Sid claim to support UPN, and SPN identities
// SID claims not available yet
//SecurityIdentifier identitySid = null;
//if (ClaimTypes.Sid.Equals(identity.IdentityClaim.ClaimType))
//{
// throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Sid");
//}
//else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType))
//{
// throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Upn");
//}
//else if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType))
//{
// throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Spn");
//}
//else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
//{
// throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Dns");
//}
//if (identitySid != null)
//{
// Claim claim = CheckSidEquivalence(identitySid, claimSet);
// if (claim != null)
// {
// SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
// return true;
// }
//}
}
SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authContext, this.GetType());
if (TD.SecurityIdentityVerificationFailureIsEnabled())
{
TD.SecurityIdentityVerificationFailure(eventTraceActivity);
}
return false;
}
}
}
}
| |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.IO;
using System.Text;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
// To simplify the process of finding the toolbox bitmap resource:
// #1 Create an internal class called "resfinder" outside of the root namespace.
// #2 Use "resfinder" in the toolbox bitmap attribute instead of the control name.
// #3 use the "<default namespace>.<resourcename>" string to locate the resource.
// See: http://www.bobpowell.net/toolboxbitmap.htm
internal class resfinder
{
}
namespace WeifenLuo.WinFormsUI.Docking
{
[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "0#")]
public delegate IDockContent DeserializeDockContent(string persistString);
[LocalizedDescription("DockPanel_Description")]
[Designer(typeof(System.Windows.Forms.Design.ControlDesigner))]
[ToolboxBitmap(typeof(resfinder), "WeifenLuo.WinFormsUI.Docking.DockPanel.bmp")]
[DefaultProperty("DocumentStyle")]
[DefaultEvent("ActiveContentChanged")]
public partial class DockPanel : Panel
{
private FocusManagerImpl m_focusManager;
private DockPanelExtender m_extender;
private DockPaneCollection m_panes;
private FloatWindowCollection m_floatWindows;
private AutoHideWindowControl m_autoHideWindow;
private DockWindowCollection m_dockWindows;
private DockContent m_dummyContent;
private Control m_dummyControl;
public DockPanel()
{
m_focusManager = new FocusManagerImpl(this);
m_extender = new DockPanelExtender(this);
m_panes = new DockPaneCollection();
m_floatWindows = new FloatWindowCollection();
SuspendLayout();
m_autoHideWindow = new AutoHideWindowControl(this);
m_autoHideWindow.Visible = false;
SetAutoHideWindowParent();
m_dummyControl = new DummyControl();
m_dummyControl.Bounds = new Rectangle(0, 0, 1, 1);
Controls.Add(m_dummyControl);
m_dockWindows = new DockWindowCollection(this);
Controls.AddRange(new Control[] {
DockWindows[DockState.Document],
DockWindows[DockState.DockLeft],
DockWindows[DockState.DockRight],
DockWindows[DockState.DockTop],
DockWindows[DockState.DockBottom]
});
m_dummyContent = new DockContent();
ResumeLayout();
}
private Color m_BackColor;
/// <summary>
/// Determines the color with which the client rectangle will be drawn.
/// If this property is used instead of the BackColor it will not have any influence on the borders to the surrounding controls (DockPane).
/// The BackColor property changes the borders of surrounding controls (DockPane).
/// Alternatively both properties may be used (BackColor to draw and define the color of the borders and DockBackColor to define the color of the client rectangle).
/// For Backgroundimages: Set your prefered Image, then set the DockBackColor and the BackColor to the same Color (Control)
/// </summary>
[Description("Determines the color with which the client rectangle will be drawn.\r\n" +
"If this property is used instead of the BackColor it will not have any influence on the borders to the surrounding controls (DockPane).\r\n" +
"The BackColor property changes the borders of surrounding controls (DockPane).\r\n" +
"Alternatively both properties may be used (BackColor to draw and define the color of the borders and DockBackColor to define the color of the client rectangle).\r\n" +
"For Backgroundimages: Set your prefered Image, then set the DockBackColor and the BackColor to the same Color (Control).")]
public Color DockBackColor
{
get
{
return !m_BackColor.IsEmpty ? m_BackColor : base.BackColor;
}
set
{
if (m_BackColor != value)
{
m_BackColor = value;
this.Refresh();
}
}
}
private AutoHideStripBase m_autoHideStripControl = null;
internal AutoHideStripBase AutoHideStripControl
{
get
{
if (m_autoHideStripControl == null)
{
m_autoHideStripControl = AutoHideStripFactory.CreateAutoHideStrip(this);
Controls.Add(m_autoHideStripControl);
}
return m_autoHideStripControl;
}
}
internal void ResetAutoHideStripControl()
{
if (m_autoHideStripControl != null)
m_autoHideStripControl.Dispose();
m_autoHideStripControl = null;
}
private void MdiClientHandleAssigned(object sender, EventArgs e)
{
SetMdiClient();
PerformLayout();
}
private void MdiClient_Layout(object sender, LayoutEventArgs e)
{
if (DocumentStyle != DocumentStyle.DockingMdi)
return;
foreach (DockPane pane in Panes)
if (pane.DockState == DockState.Document)
pane.SetContentBounds();
InvalidateWindowRegion();
}
private bool m_disposed = false;
protected override void Dispose(bool disposing)
{
lock (this)
{
if (!m_disposed && disposing)
{
m_focusManager.Dispose();
if (m_mdiClientController != null)
{
m_mdiClientController.HandleAssigned -= new EventHandler(MdiClientHandleAssigned);
m_mdiClientController.MdiChildActivate -= new EventHandler(ParentFormMdiChildActivate);
m_mdiClientController.Layout -= new LayoutEventHandler(MdiClient_Layout);
m_mdiClientController.Dispose();
}
FloatWindows.Dispose();
Panes.Dispose();
DummyContent.Dispose();
m_disposed = true;
}
base.Dispose(disposing);
}
}
[Browsable(false)]
public IDockContent ActiveAutoHideContent
{
get { return AutoHideWindow.ActiveContent; }
set { AutoHideWindow.ActiveContent = value; }
}
private bool m_allowEndUserDocking = true;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_AllowEndUserDocking_Description")]
[DefaultValue(true)]
public bool AllowEndUserDocking
{
get { return m_allowEndUserDocking; }
set { m_allowEndUserDocking = value; }
}
private bool m_allowEndUserNestedDocking = true;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_AllowEndUserNestedDocking_Description")]
[DefaultValue(true)]
public bool AllowEndUserNestedDocking
{
get { return m_allowEndUserNestedDocking; }
set { m_allowEndUserNestedDocking = value; }
}
private DockContentCollection m_contents = new DockContentCollection();
[Browsable(false)]
public DockContentCollection Contents
{
get { return m_contents; }
}
internal DockContent DummyContent
{
get { return m_dummyContent; }
}
private bool m_rightToLeftLayout = false;
[DefaultValue(false)]
[LocalizedCategory("Appearance")]
[LocalizedDescription("DockPanel_RightToLeftLayout_Description")]
public bool RightToLeftLayout
{
get { return m_rightToLeftLayout; }
set
{
if (m_rightToLeftLayout == value)
return;
m_rightToLeftLayout = value;
foreach (FloatWindow floatWindow in FloatWindows)
floatWindow.RightToLeftLayout = value;
}
}
protected override void OnRightToLeftChanged(EventArgs e)
{
base.OnRightToLeftChanged(e);
foreach (FloatWindow floatWindow in FloatWindows)
{
if (floatWindow.RightToLeft != RightToLeft)
floatWindow.RightToLeft = RightToLeft;
}
}
private bool m_showDocumentIcon = false;
[DefaultValue(false)]
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_ShowDocumentIcon_Description")]
public bool ShowDocumentIcon
{
get { return m_showDocumentIcon; }
set
{
if (m_showDocumentIcon == value)
return;
m_showDocumentIcon = value;
Refresh();
}
}
private DockPanelSkin m_dockPanelSkin = new DockPanelSkin();
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockPanelSkin")]
public DockPanelSkin Skin
{
get { return m_dockPanelSkin; }
set { m_dockPanelSkin = value; }
}
private DocumentTabStripLocation m_documentTabStripLocation = DocumentTabStripLocation.Top;
[DefaultValue(DocumentTabStripLocation.Top)]
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DocumentTabStripLocation")]
public DocumentTabStripLocation DocumentTabStripLocation
{
get { return m_documentTabStripLocation; }
set { m_documentTabStripLocation = value; }
}
[Browsable(false)]
public DockPanelExtender Extender
{
get { return m_extender; }
}
[Browsable(false)]
public DockPanelExtender.IDockPaneFactory DockPaneFactory
{
get { return Extender.DockPaneFactory; }
}
[Browsable(false)]
public DockPanelExtender.IFloatWindowFactory FloatWindowFactory
{
get { return Extender.FloatWindowFactory; }
}
internal DockPanelExtender.IDockPaneCaptionFactory DockPaneCaptionFactory
{
get { return Extender.DockPaneCaptionFactory; }
}
internal DockPanelExtender.IDockPaneStripFactory DockPaneStripFactory
{
get { return Extender.DockPaneStripFactory; }
}
internal DockPanelExtender.IAutoHideStripFactory AutoHideStripFactory
{
get { return Extender.AutoHideStripFactory; }
}
[Browsable(false)]
public DockPaneCollection Panes
{
get { return m_panes; }
}
internal Rectangle DockArea
{
get
{
return new Rectangle(DockPadding.Left, DockPadding.Top,
ClientRectangle.Width - DockPadding.Left - DockPadding.Right,
ClientRectangle.Height - DockPadding.Top - DockPadding.Bottom);
}
}
private double m_dockBottomPortion = 0.25;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockBottomPortion_Description")]
[DefaultValue(0.25)]
public double DockBottomPortion
{
get { return m_dockBottomPortion; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
if (value == m_dockBottomPortion)
return;
m_dockBottomPortion = value;
if (m_dockBottomPortion < 1 && m_dockTopPortion < 1)
{
if (m_dockTopPortion + m_dockBottomPortion > 1)
m_dockTopPortion = 1 - m_dockBottomPortion;
}
PerformLayout();
}
}
private double m_dockLeftPortion = 0.25;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockLeftPortion_Description")]
[DefaultValue(0.25)]
public double DockLeftPortion
{
get { return m_dockLeftPortion; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
if (value == m_dockLeftPortion)
return;
m_dockLeftPortion = value;
if (m_dockLeftPortion < 1 && m_dockRightPortion < 1)
{
if (m_dockLeftPortion + m_dockRightPortion > 1)
m_dockRightPortion = 1 - m_dockLeftPortion;
}
PerformLayout();
}
}
private double m_dockRightPortion = 0.25;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockRightPortion_Description")]
[DefaultValue(0.25)]
public double DockRightPortion
{
get { return m_dockRightPortion; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
if (value == m_dockRightPortion)
return;
m_dockRightPortion = value;
if (m_dockLeftPortion < 1 && m_dockRightPortion < 1)
{
if (m_dockLeftPortion + m_dockRightPortion > 1)
m_dockLeftPortion = 1 - m_dockRightPortion;
}
PerformLayout();
}
}
private double m_dockTopPortion = 0.25;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DockTopPortion_Description")]
[DefaultValue(0.25)]
public double DockTopPortion
{
get { return m_dockTopPortion; }
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException("value");
if (value == m_dockTopPortion)
return;
m_dockTopPortion = value;
if (m_dockTopPortion < 1 && m_dockBottomPortion < 1)
{
if (m_dockTopPortion + m_dockBottomPortion > 1)
m_dockBottomPortion = 1 - m_dockTopPortion;
}
PerformLayout();
}
}
[Browsable(false)]
public DockWindowCollection DockWindows
{
get { return m_dockWindows; }
}
public void UpdateDockWindowZOrder(DockStyle dockStyle, bool fullPanelEdge)
{
if (dockStyle == DockStyle.Left)
{
if (fullPanelEdge)
DockWindows[DockState.DockLeft].SendToBack();
else
DockWindows[DockState.DockLeft].BringToFront();
}
else if (dockStyle == DockStyle.Right)
{
if (fullPanelEdge)
DockWindows[DockState.DockRight].SendToBack();
else
DockWindows[DockState.DockRight].BringToFront();
}
else if (dockStyle == DockStyle.Top)
{
if (fullPanelEdge)
DockWindows[DockState.DockTop].SendToBack();
else
DockWindows[DockState.DockTop].BringToFront();
}
else if (dockStyle == DockStyle.Bottom)
{
if (fullPanelEdge)
DockWindows[DockState.DockBottom].SendToBack();
else
DockWindows[DockState.DockBottom].BringToFront();
}
}
[Browsable(false)]
public int DocumentsCount
{
get
{
int count = 0;
foreach (IDockContent content in Documents)
count++;
return count;
}
}
public IDockContent[] DocumentsToArray()
{
int count = DocumentsCount;
IDockContent[] documents = new IDockContent[count];
int i = 0;
foreach (IDockContent content in Documents)
{
documents[i] = content;
i++;
}
return documents;
}
[Browsable(false)]
public IEnumerable<IDockContent> Documents
{
get
{
foreach (IDockContent content in Contents)
{
if (content.DockHandler.DockState == DockState.Document)
yield return content;
}
}
}
private Rectangle DocumentRectangle
{
get
{
Rectangle rect = DockArea;
if (DockWindows[DockState.DockLeft].VisibleNestedPanes.Count != 0)
{
rect.X += (int)(DockArea.Width * DockLeftPortion);
rect.Width -= (int)(DockArea.Width * DockLeftPortion);
}
if (DockWindows[DockState.DockRight].VisibleNestedPanes.Count != 0)
rect.Width -= (int)(DockArea.Width * DockRightPortion);
if (DockWindows[DockState.DockTop].VisibleNestedPanes.Count != 0)
{
rect.Y += (int)(DockArea.Height * DockTopPortion);
rect.Height -= (int)(DockArea.Height * DockTopPortion);
}
if (DockWindows[DockState.DockBottom].VisibleNestedPanes.Count != 0)
rect.Height -= (int)(DockArea.Height * DockBottomPortion);
return rect;
}
}
private Control DummyControl
{
get { return m_dummyControl; }
}
[Browsable(false)]
public FloatWindowCollection FloatWindows
{
get { return m_floatWindows; }
}
private Size m_defaultFloatWindowSize = new Size(300, 300);
[Category("Layout")]
[LocalizedDescription("DockPanel_DefaultFloatWindowSize_Description")]
public Size DefaultFloatWindowSize
{
get { return m_defaultFloatWindowSize; }
set { m_defaultFloatWindowSize = value; }
}
private bool ShouldSerializeDefaultFloatWindowSize()
{
return DefaultFloatWindowSize != new Size(300, 300);
}
private DocumentStyle m_documentStyle = DocumentStyle.DockingMdi;
[LocalizedCategory("Category_Docking")]
[LocalizedDescription("DockPanel_DocumentStyle_Description")]
[DefaultValue(DocumentStyle.DockingMdi)]
public DocumentStyle DocumentStyle
{
get { return m_documentStyle; }
set
{
if (value == m_documentStyle)
return;
if (!Enum.IsDefined(typeof(DocumentStyle), value))
throw new InvalidEnumArgumentException();
if (value == DocumentStyle.SystemMdi && DockWindows[DockState.Document].VisibleNestedPanes.Count > 0)
throw new InvalidEnumArgumentException();
m_documentStyle = value;
SuspendLayout(true);
SetAutoHideWindowParent();
SetMdiClient();
InvalidateWindowRegion();
foreach (IDockContent content in Contents)
{
if (content.DockHandler.DockState == DockState.Document)
content.DockHandler.SetPaneAndVisible(content.DockHandler.Pane);
}
PerformMdiClientLayout();
ResumeLayout(true, true);
}
}
private int GetDockWindowSize(DockState dockState)
{
if (dockState == DockState.DockLeft || dockState == DockState.DockRight)
{
int width = ClientRectangle.Width - DockPadding.Left - DockPadding.Right;
int dockLeftSize = m_dockLeftPortion >= 1 ? (int)m_dockLeftPortion : (int)(width * m_dockLeftPortion);
int dockRightSize = m_dockRightPortion >= 1 ? (int)m_dockRightPortion : (int)(width * m_dockRightPortion);
if (dockLeftSize < MeasurePane.MinSize)
dockLeftSize = MeasurePane.MinSize;
if (dockRightSize < MeasurePane.MinSize)
dockRightSize = MeasurePane.MinSize;
if (dockLeftSize + dockRightSize > width - MeasurePane.MinSize)
{
int adjust = (dockLeftSize + dockRightSize) - (width - MeasurePane.MinSize);
dockLeftSize -= adjust / 2;
dockRightSize -= adjust / 2;
}
return dockState == DockState.DockLeft ? dockLeftSize : dockRightSize;
}
else if (dockState == DockState.DockTop || dockState == DockState.DockBottom)
{
int height = ClientRectangle.Height - DockPadding.Top - DockPadding.Bottom;
int dockTopSize = m_dockTopPortion >= 1 ? (int)m_dockTopPortion : (int)(height * m_dockTopPortion);
int dockBottomSize = m_dockBottomPortion >= 1 ? (int)m_dockBottomPortion : (int)(height * m_dockBottomPortion);
if (dockTopSize < MeasurePane.MinSize)
dockTopSize = MeasurePane.MinSize;
if (dockBottomSize < MeasurePane.MinSize)
dockBottomSize = MeasurePane.MinSize;
if (dockTopSize + dockBottomSize > height - MeasurePane.MinSize)
{
int adjust = (dockTopSize + dockBottomSize) - (height - MeasurePane.MinSize);
dockTopSize -= adjust / 2;
dockBottomSize -= adjust / 2;
}
return dockState == DockState.DockTop ? dockTopSize : dockBottomSize;
}
else
return 0;
}
protected override void OnLayout(LayoutEventArgs levent)
{
SuspendLayout(true);
AutoHideStripControl.Bounds = ClientRectangle;
CalculateDockPadding();
DockWindows[DockState.DockLeft].Width = GetDockWindowSize(DockState.DockLeft);
DockWindows[DockState.DockRight].Width = GetDockWindowSize(DockState.DockRight);
DockWindows[DockState.DockTop].Height = GetDockWindowSize(DockState.DockTop);
DockWindows[DockState.DockBottom].Height = GetDockWindowSize(DockState.DockBottom);
AutoHideWindow.Bounds = GetAutoHideWindowBounds(AutoHideWindowRectangle);
DockWindows[DockState.Document].BringToFront();
AutoHideWindow.BringToFront();
base.OnLayout(levent);
if (DocumentStyle == DocumentStyle.SystemMdi && MdiClientExists)
{
SetMdiClientBounds(SystemMdiClientBounds);
InvalidateWindowRegion();
}
else if (DocumentStyle == DocumentStyle.DockingMdi)
InvalidateWindowRegion();
ResumeLayout(true, true);
}
internal Rectangle GetTabStripRectangle(DockState dockState)
{
return AutoHideStripControl.GetTabStripRectangle(dockState);
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (DockBackColor == BackColor) return;
Graphics g = e.Graphics;
SolidBrush bgBrush = new SolidBrush(DockBackColor);
g.FillRectangle(bgBrush, ClientRectangle);
}
internal void AddContent(IDockContent content)
{
if (content == null)
throw(new ArgumentNullException());
if (!Contents.Contains(content))
{
Contents.Add(content);
OnContentAdded(new DockContentEventArgs(content));
}
}
internal void AddPane(DockPane pane)
{
if (Panes.Contains(pane))
return;
Panes.Add(pane);
}
internal void AddFloatWindow(FloatWindow floatWindow)
{
if (FloatWindows.Contains(floatWindow))
return;
FloatWindows.Add(floatWindow);
}
private void CalculateDockPadding()
{
DockPadding.All = 0;
int height = AutoHideStripControl.MeasureHeight();
if (AutoHideStripControl.GetNumberOfPanes(DockState.DockLeftAutoHide) > 0)
DockPadding.Left = height;
if (AutoHideStripControl.GetNumberOfPanes(DockState.DockRightAutoHide) > 0)
DockPadding.Right = height;
if (AutoHideStripControl.GetNumberOfPanes(DockState.DockTopAutoHide) > 0)
DockPadding.Top = height;
if (AutoHideStripControl.GetNumberOfPanes(DockState.DockBottomAutoHide) > 0)
DockPadding.Bottom = height;
}
internal void RemoveContent(IDockContent content)
{
if (content == null)
throw(new ArgumentNullException());
if (Contents.Contains(content))
{
Contents.Remove(content);
OnContentRemoved(new DockContentEventArgs(content));
}
}
internal void RemovePane(DockPane pane)
{
if (!Panes.Contains(pane))
return;
Panes.Remove(pane);
}
internal void RemoveFloatWindow(FloatWindow floatWindow)
{
if (!FloatWindows.Contains(floatWindow))
return;
FloatWindows.Remove(floatWindow);
}
public void SetPaneIndex(DockPane pane, int index)
{
int oldIndex = Panes.IndexOf(pane);
if (oldIndex == -1)
throw(new ArgumentException(Strings.DockPanel_SetPaneIndex_InvalidPane));
if (index < 0 || index > Panes.Count - 1)
if (index != -1)
throw(new ArgumentOutOfRangeException(Strings.DockPanel_SetPaneIndex_InvalidIndex));
if (oldIndex == index)
return;
if (oldIndex == Panes.Count - 1 && index == -1)
return;
Panes.Remove(pane);
if (index == -1)
Panes.Add(pane);
else if (oldIndex < index)
Panes.AddAt(pane, index - 1);
else
Panes.AddAt(pane, index);
}
public void SuspendLayout(bool allWindows)
{
FocusManager.SuspendFocusTracking();
SuspendLayout();
if (allWindows)
SuspendMdiClientLayout();
}
public void ResumeLayout(bool performLayout, bool allWindows)
{
FocusManager.ResumeFocusTracking();
ResumeLayout(performLayout);
if (allWindows)
ResumeMdiClientLayout(performLayout);
}
internal Form ParentForm
{
get
{
if (!IsParentFormValid())
throw new InvalidOperationException(Strings.DockPanel_ParentForm_Invalid);
return GetMdiClientController().ParentForm;
}
}
private bool IsParentFormValid()
{
if (DocumentStyle == DocumentStyle.DockingSdi || DocumentStyle == DocumentStyle.DockingWindow)
return true;
if (!MdiClientExists)
GetMdiClientController().RenewMdiClient();
return (MdiClientExists);
}
protected override void OnParentChanged(EventArgs e)
{
SetAutoHideWindowParent();
GetMdiClientController().ParentForm = (this.Parent as Form);
base.OnParentChanged (e);
}
private void SetAutoHideWindowParent()
{
Control parent;
if (DocumentStyle == DocumentStyle.DockingMdi ||
DocumentStyle == DocumentStyle.SystemMdi)
parent = this.Parent;
else
parent = this;
if (AutoHideWindow.Parent != parent)
{
AutoHideWindow.Parent = parent;
AutoHideWindow.BringToFront();
}
}
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged (e);
if (Visible)
SetMdiClient();
}
private Rectangle SystemMdiClientBounds
{
get
{
if (!IsParentFormValid() || !Visible)
return Rectangle.Empty;
Rectangle rect = ParentForm.RectangleToClient(RectangleToScreen(DocumentWindowBounds));
return rect;
}
}
internal Rectangle DocumentWindowBounds
{
get
{
Rectangle rectDocumentBounds = DisplayRectangle;
if (DockWindows[DockState.DockLeft].Visible)
{
rectDocumentBounds.X += DockWindows[DockState.DockLeft].Width;
rectDocumentBounds.Width -= DockWindows[DockState.DockLeft].Width;
}
if (DockWindows[DockState.DockRight].Visible)
rectDocumentBounds.Width -= DockWindows[DockState.DockRight].Width;
if (DockWindows[DockState.DockTop].Visible)
{
rectDocumentBounds.Y += DockWindows[DockState.DockTop].Height;
rectDocumentBounds.Height -= DockWindows[DockState.DockTop].Height;
}
if (DockWindows[DockState.DockBottom].Visible)
rectDocumentBounds.Height -= DockWindows[DockState.DockBottom].Height;
return rectDocumentBounds;
}
}
private PaintEventHandler m_dummyControlPaintEventHandler = null;
private void InvalidateWindowRegion()
{
if (DesignMode)
return;
if (m_dummyControlPaintEventHandler == null)
m_dummyControlPaintEventHandler = new PaintEventHandler(DummyControl_Paint);
DummyControl.Paint += m_dummyControlPaintEventHandler;
DummyControl.Invalidate();
}
void DummyControl_Paint(object sender, PaintEventArgs e)
{
DummyControl.Paint -= m_dummyControlPaintEventHandler;
UpdateWindowRegion();
}
private void UpdateWindowRegion()
{
if (this.DocumentStyle == DocumentStyle.DockingMdi)
UpdateWindowRegion_ClipContent();
else if (this.DocumentStyle == DocumentStyle.DockingSdi ||
this.DocumentStyle == DocumentStyle.DockingWindow)
UpdateWindowRegion_FullDocumentArea();
else if (this.DocumentStyle == DocumentStyle.SystemMdi)
UpdateWindowRegion_EmptyDocumentArea();
}
private void UpdateWindowRegion_FullDocumentArea()
{
SetRegion(null);
}
private void UpdateWindowRegion_EmptyDocumentArea()
{
Rectangle rect = DocumentWindowBounds;
SetRegion(new Rectangle[] { rect });
}
private void UpdateWindowRegion_ClipContent()
{
int count = 0;
foreach (DockPane pane in this.Panes)
{
if (!pane.Visible || pane.DockState != DockState.Document)
continue;
count ++;
}
if (count == 0)
{
SetRegion(null);
return;
}
Rectangle[] rects = new Rectangle[count];
int i = 0;
foreach (DockPane pane in this.Panes)
{
if (!pane.Visible || pane.DockState != DockState.Document)
continue;
rects[i] = RectangleToClient(pane.RectangleToScreen(pane.ContentRectangle));
i++;
}
SetRegion(rects);
}
private Rectangle[] m_clipRects = null;
private void SetRegion(Rectangle[] clipRects)
{
if (!IsClipRectsChanged(clipRects))
return;
m_clipRects = clipRects;
if (m_clipRects == null || m_clipRects.GetLength(0) == 0)
Region = null;
else
{
Region region = new Region(new Rectangle(0, 0, this.Width, this.Height));
foreach (Rectangle rect in m_clipRects)
region.Exclude(rect);
Region = region;
}
}
private bool IsClipRectsChanged(Rectangle[] clipRects)
{
if (clipRects == null && m_clipRects == null)
return false;
else if ((clipRects == null) != (m_clipRects == null))
return true;
foreach (Rectangle rect in clipRects)
{
bool matched = false;
foreach (Rectangle rect2 in m_clipRects)
{
if (rect == rect2)
{
matched = true;
break;
}
}
if (!matched)
return true;
}
foreach (Rectangle rect2 in m_clipRects)
{
bool matched = false;
foreach (Rectangle rect in clipRects)
{
if (rect == rect2)
{
matched = true;
break;
}
}
if (!matched)
return true;
}
return false;
}
private static readonly object ContentAddedEvent = new object();
[LocalizedCategory("Category_DockingNotification")]
[LocalizedDescription("DockPanel_ContentAdded_Description")]
public event EventHandler<DockContentEventArgs> ContentAdded
{
add { Events.AddHandler(ContentAddedEvent, value); }
remove { Events.RemoveHandler(ContentAddedEvent, value); }
}
protected virtual void OnContentAdded(DockContentEventArgs e)
{
EventHandler<DockContentEventArgs> handler = (EventHandler<DockContentEventArgs>)Events[ContentAddedEvent];
if (handler != null)
handler(this, e);
}
private static readonly object ContentRemovedEvent = new object();
[LocalizedCategory("Category_DockingNotification")]
[LocalizedDescription("DockPanel_ContentRemoved_Description")]
public event EventHandler<DockContentEventArgs> ContentRemoved
{
add { Events.AddHandler(ContentRemovedEvent, value); }
remove { Events.RemoveHandler(ContentRemovedEvent, value); }
}
protected virtual void OnContentRemoved(DockContentEventArgs e)
{
EventHandler<DockContentEventArgs> handler = (EventHandler<DockContentEventArgs>)Events[ContentRemovedEvent];
if (handler != null)
handler(this, e);
}
}
}
| |
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Moq;
using NUnit.Framework;
using umbraco.cms.businesslogic.contentitem;
using Umbraco.Core;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.IO;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Repositories;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Tests.TestHelpers;
using Umbraco.Tests.TestHelpers.Entities;
namespace Umbraco.Tests.Persistence.Repositories
{
[DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)]
[TestFixture]
public class DomainRepositoryTest : BaseDatabaseFactoryTest
{
private DomainRepository CreateRepository(IDatabaseUnitOfWork unitOfWork, out ContentTypeRepository contentTypeRepository, out ContentRepository contentRepository, out LanguageRepository languageRepository)
{
var templateRepository = new TemplateRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax, Mock.Of<IFileSystem>(), Mock.Of<IFileSystem>(), Mock.Of<ITemplatesSection>());
var tagRepository = new TagRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax);
contentTypeRepository = new ContentTypeRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax, templateRepository);
contentRepository = new ContentRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax, contentTypeRepository, templateRepository, tagRepository);
languageRepository = new LanguageRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax);
var domainRepository = new DomainRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax, contentRepository, languageRepository);
return domainRepository;
}
private int CreateTestData(string isoName, out ContentType ct)
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = new Language(isoName);
langRepo.AddOrUpdate(lang);
ct = MockedContentTypes.CreateBasicContentType("test", "Test");
contentTypeRepo.AddOrUpdate(ct);
var content = new Content("test", -1, ct) { CreatorId = 0, WriterId = 0 };
contentRepo.AddOrUpdate(content);
unitOfWork.Commit();
return content.Id;
}
}
[Test]
public void Can_Create_And_Get_By_Id()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
var domain = (IDomain)new UmbracoDomain("test.com") { RootContent = content, Language = lang };
repo.AddOrUpdate(domain);
unitOfWork.Commit();
//re-get
domain = repo.Get(domain.Id);
Assert.NotNull(domain);
Assert.IsTrue(domain.HasIdentity);
Assert.Greater(domain.Id, 0);
Assert.AreEqual("test.com", domain.DomainName);
Assert.AreEqual(content.Id, domain.RootContent.Id);
Assert.AreEqual(lang.Id, domain.Language.Id);
}
}
[Test]
public void Cant_Create_Duplicate_Domain_Name()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
var domain1 = (IDomain)new UmbracoDomain("test.com") { RootContent = content, Language = lang };
repo.AddOrUpdate(domain1);
unitOfWork.Commit();
var domain2 = (IDomain)new UmbracoDomain("test.com") { RootContent = content, Language = lang };
repo.AddOrUpdate(domain2);
Assert.Throws<DuplicateNameException>(unitOfWork.Commit);
}
}
[Test]
public void Can_Delete()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
var domain = (IDomain)new UmbracoDomain("test.com") { RootContent = content, Language = lang };
repo.AddOrUpdate(domain);
unitOfWork.Commit();
repo.Delete(domain);
unitOfWork.Commit();
//re-get
domain = repo.Get(domain.Id);
Assert.IsNull(domain);
}
}
[Test]
public void Can_Update()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId1 = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var content1 = contentRepo.Get(contentId1);
//more test data
var lang1 = langRepo.GetByIsoCode("en-AU");
var lang2 = new Language("es");
langRepo.AddOrUpdate(lang2);
var content2 = new Content("test", -1, ct) { CreatorId = 0, WriterId = 0 };
contentRepo.AddOrUpdate(content2);
unitOfWork.Commit();
var domain = (IDomain)new UmbracoDomain("test.com") { RootContent = content1, Language = lang1 };
repo.AddOrUpdate(domain);
unitOfWork.Commit();
//re-get
domain = repo.Get(domain.Id);
domain.DomainName = "blah.com";
domain.RootContent = content2;
domain.Language = lang2;
repo.AddOrUpdate(domain);
unitOfWork.Commit();
//re-get
domain = repo.Get(domain.Id);
Assert.AreEqual("blah.com", domain.DomainName);
Assert.AreEqual(content2.Id, domain.RootContent.Id);
Assert.AreEqual(lang2.Id, domain.Language.Id);
}
}
[Test]
public void Exists()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
for (int i = 0; i < 10; i++)
{
var domain = (IDomain)new UmbracoDomain("test" + i + ".com") { RootContent = content, Language = lang };
repo.AddOrUpdate(domain);
unitOfWork.Commit();
}
var found = repo.Exists("test1.com");
Assert.IsTrue(found);
}
}
[Test]
public void Get_By_Name()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
for (int i = 0; i < 10; i++)
{
var domain = (IDomain)new UmbracoDomain("test" + i + ".com") { RootContent = content, Language = lang };
repo.AddOrUpdate(domain);
unitOfWork.Commit();
}
var found = repo.GetByName("test1.com");
Assert.IsNotNull(found);
}
}
[Test]
public void Get_All()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
for (int i = 0; i < 10; i++)
{
var domain = (IDomain)new UmbracoDomain("test " + i + ".com") { RootContent = content, Language = lang };
repo.AddOrUpdate(domain);
unitOfWork.Commit();
}
var all = repo.GetAll();
Assert.AreEqual(10, all.Count());
}
}
[Test]
public void Get_All_Ids()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
var ids = new List<int>();
for (int i = 0; i < 10; i++)
{
var domain = (IDomain)new UmbracoDomain("test " + i + ".com") { RootContent = content, Language = lang };
repo.AddOrUpdate(domain);
unitOfWork.Commit();
ids.Add(domain.Id);
}
var all = repo.GetAll(ids.Take(8).ToArray());
Assert.AreEqual(8, all.Count());
}
}
[Test]
public void Get_All_Without_Wildcards()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var lang = langRepo.GetByIsoCode("en-AU");
var content = contentRepo.Get(contentId);
for (int i = 0; i < 10; i++)
{
var domain = (IDomain)new UmbracoDomain((i % 2 == 0) ? "test " + i + ".com" : ("*" + i))
{
RootContent = content,
Language = lang
};
repo.AddOrUpdate(domain);
unitOfWork.Commit();
}
var all = repo.GetAll(false);
Assert.AreEqual(5, all.Count());
}
}
[Test]
public void Get_All_For_Content()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var contentItems = new List<IContent>();
var lang = langRepo.GetByIsoCode("en-AU");
contentItems.Add(contentRepo.Get(contentId));
//more test data (3 content items total)
for (int i = 0; i < 2; i++)
{
var c = new Content("test" + i, -1, ct) { CreatorId = 0, WriterId = 0 };
contentRepo.AddOrUpdate(c);
unitOfWork.Commit();
contentItems.Add(c);
}
for (int i = 0; i < 10; i++)
{
var domain = (IDomain)new UmbracoDomain((i % 2 == 0) ? "test " + i + ".com" : ("*" + i))
{
RootContent = (i % 2 == 0) ? contentItems[0] : contentItems[1],
Language = lang
};
repo.AddOrUpdate(domain);
unitOfWork.Commit();
}
var all1 = repo.GetAssignedDomains(contentItems[0].Id, true);
Assert.AreEqual(5, all1.Count());
var all2 = repo.GetAssignedDomains(contentItems[1].Id, true);
Assert.AreEqual(5, all2.Count());
var all3 = repo.GetAssignedDomains(contentItems[2].Id, true);
Assert.AreEqual(0, all3.Count());
}
}
[Test]
public void Get_All_For_Content_Without_Wildcards()
{
var provider = new PetaPocoUnitOfWorkProvider(Logger);
var unitOfWork = provider.GetUnitOfWork();
ContentType ct;
var contentId = CreateTestData("en-AU", out ct);
ContentRepository contentRepo;
LanguageRepository langRepo;
ContentTypeRepository contentTypeRepo;
using (var repo = CreateRepository(unitOfWork, out contentTypeRepo, out contentRepo, out langRepo))
{
var contentItems = new List<IContent>();
var lang = langRepo.GetByIsoCode("en-AU");
contentItems.Add(contentRepo.Get(contentId));
//more test data (3 content items total)
for (int i = 0; i < 2; i++)
{
var c = new Content("test" + i, -1, ct) { CreatorId = 0, WriterId = 0 };
contentRepo.AddOrUpdate(c);
unitOfWork.Commit();
contentItems.Add(c);
}
for (int i = 0; i < 10; i++)
{
var domain = (IDomain)new UmbracoDomain((i % 2 == 0) ? "test " + i + ".com" : ("*" + i))
{
RootContent = (i % 2 == 0) ? contentItems[0] : contentItems[1],
Language = lang
};
repo.AddOrUpdate(domain);
unitOfWork.Commit();
}
var all1 = repo.GetAssignedDomains(contentItems[0].Id, false);
Assert.AreEqual(5, all1.Count());
var all2 = repo.GetAssignedDomains(contentItems[1].Id, false);
Assert.AreEqual(0, all2.Count());
}
}
}
}
| |
// Visual Studio Shared Project
// 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.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CSharp.RuntimeBinder;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudioTools.Project {
internal class ProjectReferenceNode : ReferenceNode {
#region fields
/// <summary>
/// The name of the assembly this refernce represents
/// </summary>
private Guid referencedProjectGuid;
private string referencedProjectName = String.Empty;
private string referencedProjectRelativePath = String.Empty;
private string referencedProjectFullPath = String.Empty;
private BuildDependency buildDependency;
/// <summary>
/// This is a reference to the automation object for the referenced project.
/// </summary>
private EnvDTE.Project referencedProject;
/// <summary>
/// This state is controlled by the solution events.
/// The state is set to false by OnBeforeUnloadProject.
/// The state is set to true by OnBeforeCloseProject event.
/// </summary>
private bool canRemoveReference = true;
/// <summary>
/// Possibility for solution listener to update the state on the dangling reference.
/// It will be set in OnBeforeUnloadProject then the nopde is invalidated then it is reset to false.
/// </summary>
private bool isNodeValid;
#endregion
#region properties
public override string Url {
get {
return this.referencedProjectFullPath;
}
}
public override string Caption {
get {
return this.referencedProjectName;
}
}
internal Guid ReferencedProjectGuid {
get {
return this.referencedProjectGuid;
}
}
internal string ReferencedProjectIdentity {
get {
var sln = (IVsSolution)ProjectMgr.GetService(typeof(SVsSolution));
var guid = ReferencedProjectGuid;
IVsHierarchy hier;
string projRef;
if (ErrorHandler.Succeeded(sln.GetProjectOfGuid(ref guid, out hier)) &&
ErrorHandler.Succeeded(sln.GetProjrefOfProject(hier, out projRef))) {
return projRef;
}
return null;
}
}
/// <summary>
/// Possiblity to shortcut and set the dangling project reference icon.
/// It is ussually manipulated by solution listsneres who handle reference updates.
/// </summary>
internal protected bool IsNodeValid {
get {
return this.isNodeValid;
}
set {
this.isNodeValid = value;
}
}
/// <summary>
/// Controls the state whether this reference can be removed or not. Think of the project unload scenario where the project reference should not be deleted.
/// </summary>
internal bool CanRemoveReference {
get {
return this.canRemoveReference;
}
set {
this.canRemoveReference = value;
}
}
internal string ReferencedProjectName {
get { return this.referencedProjectName; }
}
/// <summary>
/// Gets the automation object for the referenced project.
/// </summary>
internal EnvDTE.Project ReferencedProjectObject {
get {
// If the referenced project is null then re-read.
if (this.referencedProject == null) {
// Search for the project in the collection of the projects in the
// current solution.
var dte = (EnvDTE.DTE)ProjectMgr.GetService(typeof(EnvDTE.DTE));
if (null == dte || null == dte.Solution) {
return null;
}
var unmodeled = new Guid(EnvDTE.Constants.vsProjectKindUnmodeled);
referencedProject = dte.Solution.Projects
.Cast<EnvDTE.Project>()
.Where(prj => !Utilities.GuidEquals(unmodeled, prj.Kind))
.FirstOrDefault(prj => CommonUtils.IsSamePath(referencedProjectFullPath, prj.FullName));
}
return this.referencedProject;
}
set {
this.referencedProject = value;
}
}
private static string GetFilenameFromOutput(IVsOutput2 output) {
object propVal;
int hr;
try {
hr = output.get_Property("OUTPUTLOC", out propVal);
} catch (Exception ex) {
hr = Marshal.GetHRForException(ex);
propVal = null;
}
var path = propVal as string;
if (ErrorHandler.Succeeded(hr) && !string.IsNullOrEmpty(path)) {
return path;
}
ErrorHandler.ThrowOnFailure(output.get_DeploySourceURL(out path));
return new Uri(path).LocalPath;
}
private static IEnumerable<string> EnumerateOutputs(IVsProjectCfg2 config, string canonicalName) {
var actual = new uint[1];
ErrorHandler.ThrowOnFailure(config.get_OutputGroups(0, null, actual));
var groups = new IVsOutputGroup[actual[0]];
ErrorHandler.ThrowOnFailure(config.get_OutputGroups((uint)groups.Length, groups, actual));
var group = groups.FirstOrDefault(g => {
string name;
ErrorHandler.ThrowOnFailure(g.get_CanonicalName(out name));
return canonicalName.Equals(name, StringComparison.OrdinalIgnoreCase);
});
if (group == null) {
return Enumerable.Empty<string>();
}
string keyName;
if (!ErrorHandler.Succeeded(group.get_KeyOutput(out keyName))) {
keyName = null;
}
try {
ErrorHandler.ThrowOnFailure(group.get_Outputs(0, null, actual));
} catch (NotImplementedException) {
if (CommonUtils.IsValidPath(keyName)) {
return Enumerable.Repeat(keyName, 1);
}
throw;
}
var outputs = new IVsOutput2[actual[0]];
ErrorHandler.ThrowOnFailure(group.get_Outputs((uint)outputs.Length, outputs, actual));
string keyResult = null;
var results = new List<string>();
foreach (var o in outputs) {
string name;
if (keyName != null &&
ErrorHandler.Succeeded(o.get_CanonicalName(out name)) &&
keyName.Equals(name, StringComparison.OrdinalIgnoreCase)
) {
keyResult = GetFilenameFromOutput(o);
} else {
results.Add(GetFilenameFromOutput(o));
}
}
if (keyResult != null) {
results.Insert(0, keyResult);
}
return results;
}
internal virtual IEnumerable<string> ReferencedProjectBuildOutputs {
get {
var hier = VsShellUtilities.GetHierarchy(ProjectMgr.Site, ReferencedProjectGuid);
var bldMgr = (IVsSolutionBuildManager)ProjectMgr.GetService(typeof(SVsSolutionBuildManager));
var activeCfgArray = new IVsProjectCfg[1];
ErrorHandler.ThrowOnFailure(bldMgr.FindActiveProjectCfg(IntPtr.Zero, IntPtr.Zero, hier, activeCfgArray));
var activeCfg = activeCfgArray[0] as IVsProjectCfg2;
if (activeCfg == null) {
throw new InvalidOperationException("cannot get active configuration");
}
return EnumerateOutputs(activeCfg, "Built");
}
}
/// <summary>
/// Gets the full path to the assembly generated by this project.
/// </summary>
internal virtual string ReferencedProjectOutputPath {
get {
return ReferencedProjectBuildOutputs.FirstOrDefault();
}
}
internal string AssemblyName {
get {
// Now get the name of the assembly from the project.
// Some project system throw if the property does not exist. We expect an ArgumentException.
EnvDTE.Property assemblyNameProperty = null;
if (ReferencedProjectObject != null &&
!(ReferencedProjectObject is Automation.OAProject)) // our own projects don't have assembly names
{
try {
assemblyNameProperty = this.ReferencedProjectObject.Properties.Item(ProjectFileConstants.AssemblyName);
} catch (ArgumentException) {
}
if (assemblyNameProperty != null) {
return assemblyNameProperty.Value.ToString();
}
}
return null;
}
}
private Automation.OAProjectReference projectReference;
internal override object Object {
get {
if (null == projectReference) {
projectReference = new Automation.OAProjectReference(this);
}
return projectReference;
}
}
#endregion
#region ctors
/// <summary>
/// Constructor for the ReferenceNode. It is called when the project is reloaded, when the project element representing the refernce exists.
/// </summary>
public ProjectReferenceNode(ProjectNode root, ProjectElement element)
: base(root, element) {
this.referencedProjectRelativePath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectRelativePath), "Could not retrieve referenced project path form project file");
string guidString = this.ItemNode.GetMetadata(ProjectFileConstants.Project);
// Continue even if project setttings cannot be read.
try {
this.referencedProjectGuid = new Guid(guidString);
this.buildDependency = new BuildDependency(this.ProjectMgr, this.referencedProjectGuid);
this.ProjectMgr.AddBuildDependency(this.buildDependency);
} finally {
Debug.Assert(this.referencedProjectGuid != Guid.Empty, "Could not retrive referenced project guidproject file");
this.referencedProjectName = this.ItemNode.GetMetadata(ProjectFileConstants.Name);
Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectName), "Could not retrive referenced project name form project file");
}
// TODO: Maybe referenced projects should be relative to ProjectDir?
this.referencedProjectFullPath = CommonUtils.GetAbsoluteFilePath(this.ProjectMgr.ProjectHome, this.referencedProjectRelativePath);
}
/// <summary>
/// constructor for the ProjectReferenceNode
/// </summary>
public ProjectReferenceNode(ProjectNode root, string referencedProjectName, string projectPath, string projectReference)
: base(root) {
Debug.Assert(root != null && !String.IsNullOrEmpty(referencedProjectName) && !String.IsNullOrEmpty(projectReference)
&& !String.IsNullOrEmpty(projectPath), "Can not add a reference because the input for adding one is invalid.");
if (projectReference == null) {
throw new ArgumentNullException("projectReference");
}
this.referencedProjectName = referencedProjectName;
int indexOfSeparator = projectReference.IndexOf('|');
string fileName = String.Empty;
// Unfortunately we cannot use the path part of the projectReference string since it is not resolving correctly relative pathes.
if (indexOfSeparator != -1) {
string projectGuid = projectReference.Substring(0, indexOfSeparator);
this.referencedProjectGuid = new Guid(projectGuid);
if (indexOfSeparator + 1 < projectReference.Length) {
string remaining = projectReference.Substring(indexOfSeparator + 1);
indexOfSeparator = remaining.IndexOf('|');
if (indexOfSeparator == -1) {
fileName = remaining;
} else {
fileName = remaining.Substring(0, indexOfSeparator);
}
}
}
Debug.Assert(!String.IsNullOrEmpty(fileName), "Can not add a project reference because the input for adding one is invalid.");
string justTheFileName = Path.GetFileName(fileName);
this.referencedProjectFullPath = CommonUtils.GetAbsoluteFilePath(projectPath, justTheFileName);
// TODO: Maybe referenced projects should be relative to ProjectDir?
this.referencedProjectRelativePath = CommonUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, this.referencedProjectFullPath);
this.buildDependency = new BuildDependency(this.ProjectMgr, this.referencedProjectGuid);
}
#endregion
#region methods
protected override NodeProperties CreatePropertiesObject() {
return new ProjectReferencesProperties(this);
}
/// <summary>
/// The node is added to the hierarchy and then updates the build dependency list.
/// </summary>
public override void AddReference() {
if (this.ProjectMgr == null) {
return;
}
base.AddReference();
this.ProjectMgr.AddBuildDependency(this.buildDependency);
return;
}
/// <summary>
/// Overridden method. The method updates the build dependency list before removing the node from the hierarchy.
/// </summary>
public override bool Remove(bool removeFromStorage) {
if (this.ProjectMgr == null || !this.CanRemoveReference) {
return false;
}
this.ProjectMgr.RemoveBuildDependency(this.buildDependency);
return base.Remove(removeFromStorage);
}
/// <summary>
/// Links a reference node to the project file.
/// </summary>
protected override void BindReferenceData() {
Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectName), "The referencedProjectName field has not been initialized");
Debug.Assert(this.referencedProjectGuid != Guid.Empty, "The referencedProjectName field has not been initialized");
this.ItemNode = new MsBuildProjectElement(this.ProjectMgr, this.referencedProjectRelativePath, ProjectFileConstants.ProjectReference);
this.ItemNode.SetMetadata(ProjectFileConstants.Name, this.referencedProjectName);
this.ItemNode.SetMetadata(ProjectFileConstants.Project, this.referencedProjectGuid.ToString("B"));
this.ItemNode.SetMetadata(ProjectFileConstants.Private, true.ToString());
}
/// <summary>
/// Defines whether this node is valid node for painting the refererence icon.
/// </summary>
/// <returns></returns>
protected override bool CanShowDefaultIcon() {
if (this.referencedProjectGuid == Guid.Empty || this.ProjectMgr == null || this.ProjectMgr.IsClosed || this.isNodeValid) {
return false;
}
IVsHierarchy hierarchy = null;
hierarchy = VsShellUtilities.GetHierarchy(this.ProjectMgr.Site, this.referencedProjectGuid);
if (hierarchy == null) {
return false;
}
//If the Project is unloaded return false
if (this.ReferencedProjectObject == null) {
return false;
}
return File.Exists(this.referencedProjectFullPath);
}
/// <summary>
/// Checks if a project reference can be added to the hierarchy. It calls base to see if the reference is not already there, then checks for circular references.
/// </summary>
/// <param name="errorHandler">The error handler delegate to return</param>
/// <returns></returns>
protected override bool CanAddReference(out CannotAddReferenceErrorMessage errorHandler) {
// When this method is called this refererence has not yet been added to the hierarchy, only instantiated.
if (!base.CanAddReference(out errorHandler)) {
return false;
}
errorHandler = null;
if (this.IsThisProjectReferenceInCycle()) {
errorHandler = new CannotAddReferenceErrorMessage(ShowCircularReferenceErrorMessage);
return false;
}
return true;
}
private bool IsThisProjectReferenceInCycle() {
return IsReferenceInCycle(this.referencedProjectGuid);
}
private void ShowCircularReferenceErrorMessage() {
string message = SR.GetString(SR.ProjectContainsCircularReferences, this.referencedProjectName);
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, message, icon, buttons, defaultButton);
}
/// <summary>
/// Recursively search if this project reference guid is in cycle.
/// </summary>
private bool IsReferenceInCycle(Guid projectGuid) {
// TODO: This has got to be wrong, it doesn't work w/ other project types.
IVsHierarchy hierarchy = VsShellUtilities.GetHierarchy(this.ProjectMgr.Site, projectGuid);
IReferenceContainerProvider provider = hierarchy.GetProject().GetCommonProject() as IReferenceContainerProvider;
if (provider != null) {
IReferenceContainer referenceContainer = provider.GetReferenceContainer();
Utilities.CheckNotNull(referenceContainer, "Could not found the References virtual node");
foreach (ReferenceNode refNode in referenceContainer.EnumReferences()) {
ProjectReferenceNode projRefNode = refNode as ProjectReferenceNode;
if (projRefNode != null) {
if (projRefNode.ReferencedProjectGuid == this.ProjectMgr.ProjectIDGuid) {
return true;
}
if (this.IsReferenceInCycle(projRefNode.ReferencedProjectGuid)) {
return true;
}
}
}
}
return false;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using RRLab.PhysiologyWorkbench.Data;
namespace RRLab.PhysiologyWorkbench
{
public partial class CellInfoControl : UserControl
{
public event EventHandler DataSetChanged;
private PhysiologyDataSet _DataSet;
[Bindable(true)]
public PhysiologyDataSet DataSet
{
get { return _DataSet; }
set {
_DataSet = value;
if (DataSet != null)
{
CellBindingSource.DataSource = value;
GenotypesBindingSource.DataSource = value;
UsersBindingSource.DataSource = value;
}
else
{
CellBindingSource.DataSource = typeof(PhysiologyDataSet);
GenotypesBindingSource.DataSource = typeof(PhysiologyDataSet);
UsersBindingSource.DataSource = typeof(PhysiologyDataSet);
}
if (DataSetChanged != null) DataSetChanged(this, EventArgs.Empty);
}
}
public event EventHandler CellChanged;
private PhysiologyDataSet.CellsRow _Cell;
[Bindable(true)]
public PhysiologyDataSet.CellsRow Cell
{
get { return _Cell; }
set {
_Cell = value;
OnCellChanged(EventArgs.Empty);
}
}
public event EventHandler NormalColorChanged;
private Color _NormalColor = System.Drawing.SystemColors.Window;
[SettingsBindable(true)]
public Color NormalColor
{
get { return _NormalColor; }
set {
_NormalColor = value;
if (NormalColorChanged != null) NormalColorChanged(this, EventArgs.Empty);
}
}
public event EventHandler WarningColorChanged;
private Color _WarningColor = Color.Gold;
[SettingsBindable(true)]
public Color WarningColor
{
get { return _WarningColor; }
set {
_WarningColor = value;
if (WarningColorChanged != null) WarningColorChanged(this, EventArgs.Empty);
}
}
public event EventHandler UsingElectrophysiologyValidationChanged;
private bool _UsingElectrophysiologyValidation = false;
[DefaultValue(false)]
[SettingsBindable(true)]
[Bindable(true)]
public bool UsingElectrophysiologyValidation
{
get { return _UsingElectrophysiologyValidation; }
set {
_UsingElectrophysiologyValidation = value;
if (UsingElectrophysiologyValidationChanged != null) UsingElectrophysiologyValidationChanged(this, EventArgs.Empty);
}
}
public CellInfoControl()
{
InitializeComponent();
}
protected override void OnValidating(CancelEventArgs e)
{
e.Cancel = !ValidateChildren(ValidationConstraints.TabStop);
base.OnValidating(e);
}
protected override void OnValidated(EventArgs e)
{
//CellBindingSource.EndEdit();
//UsersBindingSource.EndEdit();
//GenotypesBindingSource.EndEdit();
base.OnValidated(e);
}
protected virtual void OnCellChanged(EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action<EventArgs>(OnCellChanged), e);
return;
}
Enabled = DataSet != null && Cell != null;
CellBindingSource.EndEdit();
UsersBindingSource.EndEdit();
GenotypesBindingSource.EndEdit();
if (Cell == null)
{
CellBindingSource.Position = -1;
System.Diagnostics.Debug.WriteLine("CellInfoControl: Cell set to null.");
}
if (Cell != null)
{
int position = CellBindingSource.Find("CellID", Cell.CellID);
System.Diagnostics.Debug.Assert(position >= 0, "CellInfoControl: Cell not found.");
CellBindingSource.Position = position;
System.Diagnostics.Debug.WriteLine("CellInfoControl: Cell set to " + Cell.CellID);
}
if (CellChanged != null) CellChanged(this, EventArgs.Empty);
}
protected virtual void OnGenotypeValidating(object sender, CancelEventArgs e)
{
if (InvokeRequired)
{
Invoke(new CancelEventHandler(OnGenotypeValidating), sender, e);
return;
}
if (GenotypesComboBox.Text == null || GenotypesComboBox.Text == "")
{
GenotypesComboBox.BackColor = WarningColor;
e.Cancel = true;
}
else
{
GenotypesComboBox.BackColor = NormalColor;
}
}
public event EventHandler MinimumMembranePotentialChanged;
private float _MinimumMembranePotential = -20;
[SettingsBindable(true)]
[Bindable(true)]
[DefaultValue(-20)]
public float MinimumMembranePotential
{
get { return _MinimumMembranePotential; }
set {
_MinimumMembranePotential = value;
if (MinimumMembranePotentialChanged != null)
MinimumMembranePotentialChanged(this, EventArgs.Empty);
}
}
protected virtual void OnVMembraneValidating(object sender, CancelEventArgs e)
{
if (InvokeRequired)
{
Invoke(new CancelEventHandler(OnVMembraneValidating), sender, e);
return;
}
if (VMembraneTextbox.Text == null || VMembraneTextbox.Text == "")
{
if (UsingElectrophysiologyValidation)
{
VMembraneTextbox.BackColor = WarningColor;
// Can be null, so don't cancel
}
}
else
{
float value;
if (Single.TryParse(VMembraneTextbox.Text, out value))
{
if (value > MinimumMembranePotential)
VMembraneTextbox.BackColor = WarningColor;
else VMembraneTextbox.BackColor = NormalColor;
}
else VMembraneTextbox.BackColor = WarningColor;
}
}
private void OnRPipetteValidating(object sender, CancelEventArgs e)
{
}
public event EventHandler MinimumSealResistanceChanged;
private float _MinimumSealResistance = 1;
[SettingsBindable(true)]
[Bindable(true)]
[DefaultValue(1)]
public float MinimumSealResistance
{
get { return _MinimumSealResistance; }
set {
_MinimumSealResistance = value;
if (MinimumSealResistanceChanged != null) MinimumSealResistanceChanged(this, EventArgs.Empty);
}
}
protected virtual void OnRSealValidating(object sender, CancelEventArgs e)
{
if (InvokeRequired)
{
Invoke(new CancelEventHandler(OnRSealValidating), sender, e);
return;
}
if (RSealTextBox.Text == null || RSealTextBox.Text == "")
{
if (UsingElectrophysiologyValidation)
{
RSealTextBox.BackColor = WarningColor;
// Can be null, so don't cancel
}
}
else
{
float value;
if (Single.TryParse(RSealTextBox.Text, out value))
{
if (value < MinimumSealResistance)
RSealTextBox.BackColor = WarningColor;
else RSealTextBox.BackColor = NormalColor;
}
else RSealTextBox.BackColor = WarningColor;
}
}
private void OnRMembraneValidating(object sender, CancelEventArgs e)
{
}
public event EventHandler MinimumCellCapacitanceChanged;
private float _MinimumCellCapacitance = 20;
[Bindable(true)]
[SettingsBindable(true)]
[DefaultValue(20)]
public float MinimumCellCapacitance
{
get { return _MinimumCellCapacitance; }
set {
_MinimumCellCapacitance = value;
if (MinimumCellCapacitanceChanged != null) MinimumCellCapacitanceChanged(this, EventArgs.Empty);
}
}
private void OnCellCapacValidating(object sender, CancelEventArgs e)
{
if (InvokeRequired)
{
Invoke(new CancelEventHandler(OnCellCapacValidating), sender, e);
return;
}
if (CellCapacitanceTextBox.Text == null
|| CellCapacitanceTextBox.Text == "")
{
if (UsingElectrophysiologyValidation)
{
CellCapacitanceTextBox.BackColor = WarningColor;
// Can be null, so don't cancel
}
}
else
{
float value;
if (Single.TryParse(CellCapacitanceTextBox.Text, out value))
{
if (value < MinimumCellCapacitance)
CellCapacitanceTextBox.BackColor = WarningColor;
else CellCapacitanceTextBox.BackColor = NormalColor;
}
else CellCapacitanceTextBox.BackColor = WarningColor;
}
}
private void OnRSeriesValidating(object sender, CancelEventArgs e)
{
}
private void useElectrophysiologyValidationToolStripMenuItem_CheckedChanged(object sender, EventArgs e)
{
UsingElectrophysiologyValidation = true;
}
private void OnCellDataBinding(object sender, BindingCompleteEventArgs e)
{
System.Diagnostics.Debug.WriteLine(String.Format(
"CellInfoControl: Databound {0}.{1} {2}.", e.Binding.Control.Name, e.Binding.PropertyName, e.BindingCompleteContext), "DataBinding");
}
private void OnCellDataError(object sender, BindingManagerDataErrorEventArgs e)
{
System.Diagnostics.Debug.Fail("CellInfoControl: Error during databinding.", e.Exception.Message);
}
private void OnCellPositionChanged(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("CellInfoControl: Cell position changed.");
}
private void OnCellCurrentChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(OnCellCurrentChanged), sender, e);
return;
}
//CellBindingSource.CancelEdit();
System.Diagnostics.Debug.WriteLine("CellInfoControl: Current item updated.");
}
private void OnUsersDataError(object sender, BindingManagerDataErrorEventArgs e)
{
if (UserComboBox.Items.Count == 0)
{
UserComboBox.SelectedIndex = -1;
return;
}
System.Diagnostics.Debug.Fail("CellInfoControl: Error during users databinding.", e.Exception.Message);
}
private void OnGenotypesDataError(object sender, BindingManagerDataErrorEventArgs e)
{
if (GenotypesComboBox.Items.Count == 0)
{
GenotypesComboBox.SelectedIndex = -1;
return;
}
System.Diagnostics.Debug.Fail("CellInfoControl: Error during genotypes databinding.", e.Exception.Message);
}
private void OnRoughnessTrackBarValueChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(OnRoughnessTrackBarValueChanged), sender, e);
return;
}
RoughnessNumericUpDown.Value = RoughnessTrackBar.Value;
}
private void OnLengthTrackBarValueChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(OnLengthTrackBarValueChanged), sender, e);
return;
}
LengthNumericUpDown.Value = LengthTrackBar.Value;
}
private void OnBlebbinessTrackBarValueChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(OnBlebbinessTrackBarValueChanged), sender, e);
return;
}
BlebbinessNumericUpDown.Value = BlebbinessTrackBar.Value;
}
private void OnRoughnessNumericUpDownValueChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(OnRoughnessNumericUpDownValueChanged), sender, e);
return;
}
System.Diagnostics.Debug.WriteLine("RoughnessNumericUpDown value changed.");
if (RoughnessTrackBar.Value != RoughnessNumericUpDown.Value)
RoughnessTrackBar.Value = Convert.ToInt32(RoughnessNumericUpDown.Value);
}
private void OnLengthNumericUpDownValueChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(OnLengthNumericUpDownValueChanged), sender, e);
return;
}
if (LengthTrackBar.Value != LengthNumericUpDown.Value)
LengthTrackBar.Value = Convert.ToInt32(LengthNumericUpDown.Value);
}
private void OnBlebbinessNumericUpDownValueChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(OnBlebbinessNumericUpDownValueChanged), sender, e);
return;
}
if (BlebbinessTrackBar.Value != BlebbinessNumericUpDown.Value)
BlebbinessTrackBar.Value = Convert.ToInt32(BlebbinessNumericUpDown.Value);
}
public virtual void SuspendDataBinding()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(SuspendDataBinding));
return;
}
CellBindingSource.SuspendBinding();
GenotypesBindingSource.SuspendBinding();
UsersBindingSource.SuspendBinding();
}
public virtual void ResumeDataBinding()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(ResumeDataBinding));
return;
}
CellBindingSource.ResumeBinding();
GenotypesBindingSource.ResumeBinding();
UsersBindingSource.ResumeBinding();
OnCellChanged(EventArgs.Empty);
CellBindingSource.ResetCurrentItem();
GenotypesBindingSource.ResetCurrentItem();
UsersBindingSource.ResetCurrentItem();
}
}
}
| |
// Copyright (c) Pomelo Foundation. All rights reserved.
// Licensed under the MIT. See LICENSE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal;
using Pomelo.EntityFrameworkCore.MySql.Storage.Internal;
namespace Pomelo.EntityFrameworkCore.MySql.Metadata.Internal
{
public class MySqlAnnotationProvider : RelationalAnnotationProvider
{
[NotNull] private readonly IMySqlOptions _options;
public MySqlAnnotationProvider(
[NotNull] RelationalAnnotationProviderDependencies dependencies,
[NotNull] IMySqlOptions options)
: base(dependencies)
{
_options = options;
}
public override IEnumerable<IAnnotation> For(IRelationalModel model, bool designTime)
{
if (!designTime)
{
yield break;
}
if (GetActualModelCharSet(model.Model, DelegationModes.ApplyToDatabases) is string charSet)
{
yield return new Annotation(
MySqlAnnotationNames.CharSet,
charSet);
}
// If a collation delegation modes has been set, but does not contain DelegationModes.ApplyToDatabase, we reset the EF Core
// handled Collation property in MySqlMigrationsModelDiffer.
// Handle other annotations (including the delegation annotations).
foreach (var annotation in model.Model.GetAnnotations()
.Where(a => a.Name is MySqlAnnotationNames.CharSetDelegation or
MySqlAnnotationNames.CollationDelegation))
{
yield return annotation;
}
}
public override IEnumerable<IAnnotation> For(ITable table, bool designTime)
{
if (!designTime)
{
yield break;
}
// Model validation ensures that these facets are the same on all mapped entity types
var entityType = table.EntityTypeMappings.First().EntityType;
// Use an explicitly defined character set, if set.
// Otherwise, explicitly use the model/database character set, if delegation is enabled.
if (GetActualEntityTypeCharSet(entityType, DelegationModes.ApplyToTables) is string charSet)
{
yield return new Annotation(
MySqlAnnotationNames.CharSet,
charSet);
}
// Use an explicitly defined collation, if set.
// Otherwise, explicitly use the model/database collation, if delegation is enabled.
if (GetActualEntityTypeCollation(entityType, DelegationModes.ApplyToTables) is string collation)
{
yield return new Annotation(
RelationalAnnotationNames.Collation,
collation);
}
// Handle other annotations (including the delegation annotations).
foreach (var annotation in entityType.GetAnnotations()
.Where(a => a.Name is MySqlAnnotationNames.CharSetDelegation or
MySqlAnnotationNames.CollationDelegation or
MySqlAnnotationNames.StoreOptions))
{
yield return annotation;
}
}
public override IEnumerable<IAnnotation> For(IUniqueConstraint constraint, bool designTime)
{
if (!designTime)
{
yield break;
}
// Model validation ensures that these facets are the same on all mapped indexes
var key = constraint.MappedKeys.First();
var prefixLength = key.PrefixLength();
if (prefixLength != null &&
prefixLength.Length > 0)
{
yield return new Annotation(
MySqlAnnotationNames.IndexPrefixLength,
prefixLength);
}
}
public override IEnumerable<IAnnotation> For(ITableIndex index, bool designTime)
{
if (!designTime)
{
yield break;
}
// Model validation ensures that these facets are the same on all mapped indexes
var modelIndex = index.MappedIndexes.First();
var prefixLength = modelIndex.PrefixLength();
if (prefixLength != null &&
prefixLength.Length > 0)
{
yield return new Annotation(
MySqlAnnotationNames.IndexPrefixLength,
prefixLength);
}
var isFullText = modelIndex.IsFullText();
if (isFullText.HasValue)
{
yield return new Annotation(
MySqlAnnotationNames.FullTextIndex,
isFullText.Value);
}
var fullTextParser = modelIndex.FullTextParser();
if (!string.IsNullOrEmpty(fullTextParser))
{
yield return new Annotation(
MySqlAnnotationNames.FullTextParser,
fullTextParser);
}
var isSpatial = modelIndex.IsSpatial();
if (isSpatial.HasValue)
{
yield return new Annotation(
MySqlAnnotationNames.SpatialIndex,
isSpatial.Value);
}
}
public override IEnumerable<IAnnotation> For(IColumn column, bool designTime)
{
if (!designTime)
{
yield break;
}
var table = StoreObjectIdentifier.Table(column.Table.Name, column.Table.Schema);
var properties = column.PropertyMappings.Select(m => m.Property).ToArray();
if (column.PropertyMappings.Where(
m => m.TableMapping.IsSharedTablePrincipal &&
m.TableMapping.EntityType == m.Property.DeclaringEntityType)
.Select(m => m.Property)
.FirstOrDefault(p => p.GetValueGenerationStrategy(table) == MySqlValueGenerationStrategy.IdentityColumn) is IProperty identityProperty)
{
var valueGenerationStrategy = identityProperty.GetValueGenerationStrategy(table);
yield return new Annotation(
MySqlAnnotationNames.ValueGenerationStrategy,
valueGenerationStrategy);
}
else if (properties.FirstOrDefault(
p => p.GetValueGenerationStrategy(table) == MySqlValueGenerationStrategy.ComputedColumn) is IProperty computedProperty)
{
var valueGenerationStrategy = computedProperty.GetValueGenerationStrategy(table);
yield return new Annotation(
MySqlAnnotationNames.ValueGenerationStrategy,
valueGenerationStrategy);
}
// Use an explicitly defined character set, if set.
// Otherwise, explicitly use the entity/table or model/database character set, if delegation is enabled.
if (GetActualPropertyCharSet(properties, DelegationModes.ApplyToColumns) is string charSet)
{
yield return new Annotation(
MySqlAnnotationNames.CharSet,
charSet);
}
// Use an explicitly defined collation, if set.
// Otherwise, explicitly use the entity/table or model/database collation, if delegation is enabled.
if (GetActualPropertyCollation(properties, DelegationModes.ApplyToColumns) is string collation)
{
yield return new Annotation(
RelationalAnnotationNames.Collation,
collation);
}
if (column.PropertyMappings.Select(m => m.Property.GetSpatialReferenceSystem())
.FirstOrDefault(c => c != null) is int srid)
{
yield return new Annotation(
MySqlAnnotationNames.SpatialReferenceSystemId,
srid);
}
}
protected virtual string GetActualModelCharSet(IModel model, DelegationModes currentLevel)
{
// If neither character set nor collation has been explicitly defined for the model, and no delegation has been setup, we use
// Pomelo's universal fallback default character set (which is `utf8mb4`) and apply it to all database objects.
return model.GetCharSet() is null &&
model.GetCharSetDelegation() is null &&
model.GetCollation() is null &&
model.GetCollationDelegation() is null
? _options.DefaultCharSet.Name
: model.GetActualCharSetDelegation().HasFlag(currentLevel)
? model.GetCharSet()
: null;
}
protected virtual string GetActualModelCollation(IModel model, DelegationModes currentLevel)
{
return model.GetActualCollationDelegation().HasFlag(currentLevel)
? model.GetCollation()
: null;
}
protected virtual string GetActualEntityTypeCharSet(IEntityType entityType, DelegationModes currentLevel)
{
// 1. Use explicitly defined charset:
// entityTypeBuilder.HasCharSet(null, currentLevel)
// entityTypeBuilder.HasCharSet("latin1", null)
// entityTypeBuilder.HasCharSet("latin1", currentLevel)
// 2. Check charset and delegation at the database level:
// entityTypeBuilder.HasCharSet(null, null) [or no call at all]
// entityTypeBuilder.HasCharSet(null, !currentLevel)
// entityTypeBuilder.HasCharSet("latin1", !currentLevel)
// 3: Do not explicitly use any charset:
// all other cases
var entityTypeCharSet = entityType.GetCharSet();
var entityTypeCharSetDelegation = entityType.GetCharSetDelegation();
var actualEntityTypeCharSetDelegation = entityType.GetActualCharSetDelegation();
// Cases 1:
// An explicitly set charset (which can be null) on the entity level.
// We return it, if it also applies to the current level (which could be the property level, instead of the entity level).
// This enables users to set a default charset for properties of an entity, without having to also necessarily apply it to
// the entity itself.
if (actualEntityTypeCharSetDelegation.HasFlag(currentLevel) &&
(entityTypeCharSet is not null || entityTypeCharSetDelegation is not null))
{
return entityTypeCharSet;
}
//
// At this point, no charset has been explicitly setup at the entity level, that applies to the current (entity/property) level.
//
// Case 2:
// Use an explicitly set collation at the entity level, an inherited collation from the model level, or an inherited charset
// from the model level.
if (!actualEntityTypeCharSetDelegation.HasFlag(currentLevel) ||
entityTypeCharSet is null && entityTypeCharSetDelegation is null)
{
var entityTypeCollation = entityType.GetCollation();
var actualCollationDelegation = entityType.GetActualCollationDelegation();
var actualModelCharSet = GetActualModelCharSet(entityType.Model, currentLevel);
// An explicitly defined collation on the entity level takes precedence over an inherited charset from the model
// level.
if (entityTypeCollation is not null &&
actualCollationDelegation.HasFlag(currentLevel))
{
// However, if the collation on the entity level is compatible with the inheritable charset from the model level, then
// we can apply the charset after all, since there should be no harm in doing so and it is probably the behavior that
// users expect.
return actualModelCharSet is not null &&
entityTypeCollation.StartsWith(actualModelCharSet, StringComparison.OrdinalIgnoreCase)
? actualModelCharSet
: null;
}
var actualModelCollation = GetActualModelCollation(entityType.Model, currentLevel);
// An inheritable collation from the model level takes precedence over an inheritable charset from the model level.
if (actualModelCollation is not null)
{
// However, if the inheritable collation from the model level is compatible with the inheritable charset from the model
// level (which is usually the case), then we can apply the charset after all, since there should be no harm in doing
// so and it is probably the behavior that users expect.
return actualModelCharSet is not null &&
actualModelCollation.StartsWith(actualModelCharSet, StringComparison.OrdinalIgnoreCase)
? actualModelCharSet
: null;
}
// Return either the inherited model charset, or null if none applies to the current level.
return actualModelCharSet;
}
// Case 3:
// All remaining cases don't set a charset.
return null;
// return (entityType.GetCharSet() is not null || // 3abc
// entityType.GetCharSet() is null && entityType.GetCharSetDelegation() is not null) && // 2ab
// entityType.GetActualCharSetDelegation().HasFlag(currentLevel) // 3abc, 2ab
// ? entityType.GetCharSet()
// // An explicitly defined collation on the current entity level takes precedence over an inherited charset.
// : GetActualModelCharSet(entityType.Model, currentLevel) is string charSet && // 1
// (currentLevel != DelegationModes.ApplyToTables ||
// entityType.GetCollation() is not string collation ||
// !entityType.GetActualCollationDelegation().HasFlag(DelegationModes.ApplyToTables) ||
// collation.StartsWith(charSet, StringComparison.OrdinalIgnoreCase))
// ? charSet
// : null;
}
protected virtual string GetActualEntityTypeCollation(IEntityType entityType, DelegationModes currentLevel)
{
// 1. Use explicitly defined collation:
// entityTypeBuilder.HasCollation(null, currentLevel)
// entityTypeBuilder.HasCollation("latin1_general_ci", null)
// entityTypeBuilder.HasCollation("latin1_general_ci", currentLevel)
// 2. Check collation and delegation at the database level:
// entityTypeBuilder.HasCollation(null, null) [or no call at all]
// entityTypeBuilder.HasCollation(null, !currentLevel)
// entityTypeBuilder.HasCollation("latin1_general_ci", !currentLevel)
// 3: Do not explicitly use any collation:
// all other cases
var entityTypeCollation = entityType.GetCollation();
var entityTypeCollationDelegation = entityType.GetCollationDelegation();
var actualEntityTypeCollationDelegation = entityType.GetActualCollationDelegation();
// Cases 1:
// An explicitly set collation (which can be null) on the entity level.
// We return it, if it applies to the current level (which could be the property level, instead of the entity level).
// This enables users to set a default collation for properties of an entity, without having to also necessarily apply it to
// the entity itself.
if (actualEntityTypeCollationDelegation.HasFlag(currentLevel) &&
(entityTypeCollation is not null || entityTypeCollationDelegation is not null))
{
return entityTypeCollation;
}
//
// At this point, no collation has been explicitly setup at the entity level, that applies to the current (entity/property) level.
//
// Case 2:
// Use an explicitly set charset at the entity level, an inheritable collation from the model level, or an inheritable charset
// from the model level.
if (!actualEntityTypeCollationDelegation.HasFlag(currentLevel) ||
entityTypeCollation is null && entityTypeCollationDelegation is null)
{
var entityTypeCharSet = entityType.GetCharSet();
var actualCharSetDelegation = entityType.GetActualCharSetDelegation();
var actualModelCollation = GetActualModelCollation(entityType.Model, currentLevel);
// An explicitly defined charset on the entity level takes precedence over an inherited collation from the model
// level.
if (entityTypeCharSet is not null &&
actualCharSetDelegation.HasFlag(currentLevel))
{
// However, if the charset on the entity level is compatible with the inheritable collation from the model level, then
// we can apply the collation after all, since there should be no harm in doing so and it is probably the behavior that
// users expect.
return actualModelCollation is not null &&
actualModelCollation.StartsWith(entityTypeCharSet, StringComparison.OrdinalIgnoreCase)
? actualModelCollation
: null;
}
// Return either the inherited model collation, or null if none applies to the current level.
return actualModelCollation;
}
// Case 3:
// All remaining cases don't set a collation.
return null;
// return (entityType.GetCollation() is not null || // 3abc
// entityType.GetCollation() is null && entityType.GetCollationDelegation() is not null) && // 2ab
// entityType.GetActualCollationDelegation().HasFlag(currentLevel)
// ? entityType.GetCollation()
// // An explicitly defined charset on the current entity level takes precedence over an inherited collation.
// : GetActualModelCollation(entityType.Model, currentLevel) is string collation && // 1
// (currentLevel != DelegationModes.ApplyToTables ||
// entityType.GetCharSet() is not string charSet ||
// !entityType.GetActualCharSetDelegation().HasFlag(DelegationModes.ApplyToTables) ||
// collation.StartsWith(charSet, StringComparison.OrdinalIgnoreCase))
// ? collation
// : null;
}
protected virtual string GetActualPropertyCharSet(IProperty[] properties, DelegationModes currentLevel)
{
return properties.Select(p => p.GetCharSet()).FirstOrDefault(s => s is not null) ??
properties.Select(
p => p.FindTypeMapping() is MySqlStringTypeMapping {IsNationalChar: false}
// An explicitly defined collation on the current property level takes precedence over an inherited charset.
? GetActualEntityTypeCharSet(p.DeclaringEntityType, currentLevel) is string charSet &&
(p.GetCollation() is not string collation ||
collation.StartsWith(charSet, StringComparison.OrdinalIgnoreCase))
? charSet
: null
: null)
.FirstOrDefault(s => s is not null);
}
protected virtual string GetActualPropertyCollation(IProperty[] properties, DelegationModes currentLevel)
{
Debug.Assert(currentLevel == DelegationModes.ApplyToColumns);
// We have been using the `MySql:Collation` annotation before EF Core added collation support.
// Our `MySqlPropertyExtensions.GetMySqlLegacyCollation()` method handles the legacy case, so we explicitly
// call it here and setup the relational annotation, even though EF Core sets it up as well.
// This ensures, that from this point onwards, only the `Relational:Collation` annotation is being used.
//
// If no collation has been set, explicitly use the the model/database collation, if delegation is enabled.
//
// The exception are Guid properties when the GuidFormat has been set to a char-based format, in which case we will use the
// default guid collation setup for the model, or the fallback default from our options if none has been set, to optimize space
// and performance for those columns. (We ignore the binary format, because its charset and collation is always `binary`.)
return properties.All(p => p.GetCollation() is null)
? properties.Select(p => p.GetMySqlLegacyCollation()).FirstOrDefault(c => c is not null) ??
properties.Select(
// An explicitly defined charset on the current property level takes precedence over an inherited collation.
p => (p.FindTypeMapping() is MySqlStringTypeMapping {IsNationalChar: false}
? GetActualEntityTypeCollation(p.DeclaringEntityType, currentLevel)
: p.FindTypeMapping() is MySqlGuidTypeMapping {IsCharBasedStoreType: true}
? p.DeclaringEntityType.Model.GetActualGuidCollation(_options.DefaultGuidCollation)
: null) is string collation &&
(p.GetCharSet() is not string charSet ||
collation.StartsWith(charSet, StringComparison.OrdinalIgnoreCase))
? collation
: null)
.FirstOrDefault(s => s is not null)
: null;
}
}
}
| |
#if ANDROID
#define REQUIRES_PRIMARY_THREAD_LOADING
#endif
using BitmapFont = FlatRedBall.Graphics.BitmapFont;
using Cursor = FlatRedBall.Gui.Cursor;
using GuiManager = FlatRedBall.Gui.GuiManager;
#if XNA4 || WINDOWS_8
using Color = Microsoft.Xna.Framework.Color;
#elif FRB_MDX
using Color = System.Drawing.Color;
#else
using Color = Microsoft.Xna.Framework.Graphics.Color;
#endif
#if FRB_XNA || SILVERLIGHT
using Keys = Microsoft.Xna.Framework.Input.Keys;
using Vector3 = Microsoft.Xna.Framework.Vector3;
using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D;
using Microsoft.Xna.Framework.Media;
#endif
// Generated Usings
using FrbTicTacToe.Entities;
using FlatRedBall;
using FlatRedBall.Screens;
using System;
using System.Collections.Generic;
using System.Text;
namespace FrbTicTacToe.Screens
{
public partial class FrbSplashScreen : Screen
{
// Generated Fields
#if DEBUG
static bool HasBeenLoadedWithGlobalContentManager = false;
#endif
public enum VariableState
{
Uninitialized = 0, //This exists so that the first set call actually does something
Unknown = 1, //This exists so that if the entity is actually a child entity and has set a child state, you will get this
Opaque = 2,
Transparent = 3
}
protected int mCurrentState = 0;
public Screens.FrbSplashScreen.VariableState CurrentState
{
get
{
if (Enum.IsDefined(typeof(VariableState), mCurrentState))
{
return (VariableState)mCurrentState;
}
else
{
return VariableState.Unknown;
}
}
set
{
mCurrentState = (int)value;
switch(CurrentState)
{
case VariableState.Uninitialized:
break;
case VariableState.Unknown:
break;
case VariableState.Opaque:
SpriteObjectAlpha = 1f;
break;
case VariableState.Transparent:
SpriteObjectAlpha = 0f;
break;
}
}
}
protected FlatRedBall.Scene SceneFile;
private FlatRedBall.Sprite SpriteObject;
public float SpriteObjectAlpha
{
get
{
return SpriteObject.Alpha;
}
set
{
SpriteObject.Alpha = value;
}
}
public FrbSplashScreen()
: base("FrbSplashScreen")
{
}
public override void Initialize(bool addToManagers)
{
// Generated Initialize
LoadStaticContent(ContentManagerName);
if (!FlatRedBallServices.IsLoaded<FlatRedBall.Scene>(@"content/screens/splashscreen/scenefile.scnx", ContentManagerName))
{
}
SceneFile = FlatRedBallServices.Load<FlatRedBall.Scene>(@"content/screens/splashscreen/scenefile.scnx", ContentManagerName);
SpriteObject = SceneFile.Sprites.FindByName("frblogo5121");
this.NextScreen = typeof(FrbTicTacToe.Screens.CcgSplashScreen).FullName;
PostInitialize();
base.Initialize(addToManagers);
if (addToManagers)
{
AddToManagers();
}
}
// Generated AddToManagers
public override void AddToManagers ()
{
SceneFile.AddToManagers(mLayer);
base.AddToManagers();
AddToManagersBottomUp();
CustomInitialize();
}
public override void Activity(bool firstTimeCalled)
{
// Generated Activity
if (!IsPaused)
{
}
else
{
}
base.Activity(firstTimeCalled);
if (!IsActivityFinished)
{
CustomActivity(firstTimeCalled);
}
SceneFile.ManageAll();
// After Custom Activity
}
public override void Destroy()
{
// Generated Destroy
if (this.UnloadsContentManagerWhenDestroyed && ContentManagerName != "Global")
{
SceneFile.RemoveFromManagers(ContentManagerName != "Global");
}
else
{
SceneFile.RemoveFromManagers(false);
}
base.Destroy();
CustomDestroy();
}
// Generated Methods
public virtual void PostInitialize ()
{
bool oldShapeManagerSuppressAdd = FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue;
FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue = true;
FlatRedBall.Math.Geometry.ShapeManager.SuppressAddingOnVisibilityTrue = oldShapeManagerSuppressAdd;
}
public virtual void AddToManagersBottomUp ()
{
CameraSetup.ResetCamera(SpriteManager.Camera);
AssignCustomVariables(false);
}
public virtual void RemoveFromManagers ()
{
}
public virtual void AssignCustomVariables (bool callOnContainedElements)
{
if (callOnContainedElements)
{
}
SpriteObjectAlpha = 0f;
}
public virtual void ConvertToManuallyUpdated ()
{
SceneFile.ConvertToManuallyUpdated();
}
public static void LoadStaticContent (string contentManagerName)
{
if (string.IsNullOrEmpty(contentManagerName))
{
throw new ArgumentException("contentManagerName cannot be empty or null");
}
#if DEBUG
if (contentManagerName == FlatRedBallServices.GlobalContentManager)
{
HasBeenLoadedWithGlobalContentManager = true;
}
else if (HasBeenLoadedWithGlobalContentManager)
{
throw new Exception("This type has been loaded with a Global content manager, then loaded with a non-global. This can lead to a lot of bugs");
}
#endif
CustomLoadStaticContent(contentManagerName);
}
static VariableState mLoadingState = VariableState.Uninitialized;
public static VariableState LoadingState
{
get
{
return mLoadingState;
}
set
{
mLoadingState = value;
}
}
public FlatRedBall.Instructions.Instruction InterpolateToState (VariableState stateToInterpolateTo, double secondsToTake)
{
switch(stateToInterpolateTo)
{
case VariableState.Opaque:
SpriteObject.AlphaRate = (1f - SpriteObject.Alpha) / (float)secondsToTake;
break;
case VariableState.Transparent:
SpriteObject.AlphaRate = (0f - SpriteObject.Alpha) / (float)secondsToTake;
break;
}
var instruction = new FlatRedBall.Instructions.DelegateInstruction<VariableState>(StopStateInterpolation, stateToInterpolateTo);
instruction.TimeToExecute = FlatRedBall.TimeManager.CurrentTime + secondsToTake;
FlatRedBall.Instructions.InstructionManager.Add(instruction);
return instruction;
}
public void StopStateInterpolation (VariableState stateToStop)
{
switch(stateToStop)
{
case VariableState.Opaque:
SpriteObject.AlphaRate = 0;
break;
case VariableState.Transparent:
SpriteObject.AlphaRate = 0;
break;
}
CurrentState = stateToStop;
}
public void InterpolateBetween (VariableState firstState, VariableState secondState, float interpolationValue)
{
#if DEBUG
if (float.IsNaN(interpolationValue))
{
throw new Exception("interpolationValue cannot be NaN");
}
#endif
bool setSpriteObjectAlpha = true;
float SpriteObjectAlphaFirstValue= 0;
float SpriteObjectAlphaSecondValue= 0;
switch(firstState)
{
case VariableState.Opaque:
SpriteObjectAlphaFirstValue = 1f;
break;
case VariableState.Transparent:
SpriteObjectAlphaFirstValue = 0f;
break;
}
switch(secondState)
{
case VariableState.Opaque:
SpriteObjectAlphaSecondValue = 1f;
break;
case VariableState.Transparent:
SpriteObjectAlphaSecondValue = 0f;
break;
}
if (setSpriteObjectAlpha)
{
SpriteObjectAlpha = SpriteObjectAlphaFirstValue * (1 - interpolationValue) + SpriteObjectAlphaSecondValue * interpolationValue;
}
if (interpolationValue < 1)
{
mCurrentState = (int)firstState;
}
else
{
mCurrentState = (int)secondState;
}
}
[System.Obsolete("Use GetFile instead")]
public static object GetStaticMember (string memberName)
{
return null;
}
public static object GetFile (string memberName)
{
return null;
}
object GetMember (string memberName)
{
switch(memberName)
{
case "SceneFile":
return SceneFile;
}
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.
/*============================================================
**
**
**
** Purpose: A wrapper class for the primitive type float.
**
**
===========================================================*/
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Internal.Runtime.CompilerServices;
namespace System
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public readonly struct Single : IComparable, IConvertible, IFormattable, IComparable<float>, IEquatable<float>, ISpanFormattable
{
private readonly float m_value; // Do not rename (binary serialization)
//
// Public constants
//
public const float MinValue = (float)-3.40282346638528859e+38;
public const float Epsilon = (float)1.4e-45;
public const float MaxValue = (float)3.40282346638528859e+38;
public const float PositiveInfinity = (float)1.0 / (float)0.0;
public const float NegativeInfinity = (float)-1.0 / (float)0.0;
public const float NaN = (float)0.0 / (float)0.0;
// We use this explicit definition to avoid the confusion between 0.0 and -0.0.
internal const float NegativeZero = (float)-0.0;
//
// Constants for manipulating the private bit-representation
//
internal const uint SignMask = 0x8000_0000;
internal const int SignShift = 31;
internal const int ShiftedSignMask = (int)(SignMask >> SignShift);
internal const uint ExponentMask = 0x7F80_0000;
internal const int ExponentShift = 23;
internal const int ShiftedExponentMask = (int)(ExponentMask >> ExponentShift);
internal const uint SignificandMask = 0x007F_FFFF;
internal const byte MinSign = 0;
internal const byte MaxSign = 1;
internal const byte MinExponent = 0x00;
internal const byte MaxExponent = 0xFF;
internal const uint MinSignificand = 0x0000_0000;
internal const uint MaxSignificand = 0x007F_FFFF;
/// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsFinite(float f)
{
var bits = BitConverter.SingleToInt32Bits(f);
return (bits & 0x7FFFFFFF) < 0x7F800000;
}
/// <summary>Determines whether the specified value is infinite.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsInfinity(float f)
{
var bits = BitConverter.SingleToInt32Bits(f);
return (bits & 0x7FFFFFFF) == 0x7F800000;
}
/// <summary>Determines whether the specified value is NaN.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsNaN(float f)
{
var bits = BitConverter.SingleToInt32Bits(f);
return (bits & 0x7FFFFFFF) > 0x7F800000;
}
/// <summary>Determines whether the specified value is negative.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsNegative(float f)
{
return BitConverter.SingleToInt32Bits(f) < 0;
}
/// <summary>Determines whether the specified value is negative infinity.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsNegativeInfinity(float f)
{
return (f == float.NegativeInfinity);
}
/// <summary>Determines whether the specified value is normal.</summary>
[NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public static unsafe bool IsNormal(float f)
{
var bits = BitConverter.SingleToInt32Bits(f);
bits &= 0x7FFFFFFF;
return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) != 0);
}
/// <summary>Determines whether the specified value is positive infinity.</summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe bool IsPositiveInfinity(float f)
{
return (f == float.PositiveInfinity);
}
/// <summary>Determines whether the specified value is subnormal.</summary>
[NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public static unsafe bool IsSubnormal(float f)
{
var bits = BitConverter.SingleToInt32Bits(f);
bits &= 0x7FFFFFFF;
return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) == 0);
}
internal static int ExtractExponentFromBits(uint bits)
{
return (int)(bits >> ExponentShift) & ShiftedExponentMask;
}
internal static uint ExtractSignificandFromBits(uint bits)
{
return bits & SignificandMask;
}
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Single, this method throws an ArgumentException.
//
public int CompareTo(object? value)
{
if (value == null)
{
return 1;
}
if (value is float)
{
float f = (float)value;
if (m_value < f) return -1;
if (m_value > f) return 1;
if (m_value == f) return 0;
// At least one of the values is NaN.
if (IsNaN(m_value))
return (IsNaN(f) ? 0 : -1);
else // f is NaN.
return 1;
}
throw new ArgumentException(SR.Arg_MustBeSingle);
}
public int CompareTo(float value)
{
if (m_value < value) return -1;
if (m_value > value) return 1;
if (m_value == value) return 0;
// At least one of the values is NaN.
if (IsNaN(m_value))
return (IsNaN(value) ? 0 : -1);
else // f is NaN.
return 1;
}
[NonVersionable]
public static bool operator ==(float left, float right)
{
return left == right;
}
[NonVersionable]
public static bool operator !=(float left, float right)
{
return left != right;
}
[NonVersionable]
public static bool operator <(float left, float right)
{
return left < right;
}
[NonVersionable]
public static bool operator >(float left, float right)
{
return left > right;
}
[NonVersionable]
public static bool operator <=(float left, float right)
{
return left <= right;
}
[NonVersionable]
public static bool operator >=(float left, float right)
{
return left >= right;
}
public override bool Equals(object? obj)
{
if (!(obj is float))
{
return false;
}
float temp = ((float)obj).m_value;
if (temp == m_value)
{
return true;
}
return IsNaN(temp) && IsNaN(m_value);
}
public bool Equals(float obj)
{
if (obj == m_value)
{
return true;
}
return IsNaN(obj) && IsNaN(m_value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetHashCode()
{
var bits = Unsafe.As<float, int>(ref Unsafe.AsRef(in m_value));
// Optimized check for IsNan() || IsZero()
if (((bits - 1) & 0x7FFFFFFF) >= 0x7F800000)
{
// Ensure that all NaNs and both zeros have the same hash code
bits &= 0x7F800000;
}
return bits;
}
public override string ToString()
{
return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo);
}
public string ToString(IFormatProvider? provider)
{
return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider));
}
public string ToString(string? format)
{
return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo);
}
public string ToString(string? format, IFormatProvider? provider)
{
return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider));
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null)
{
return Number.TryFormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten);
}
// Parses a float from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
//
// This method will not throw an OverflowException, but will return
// PositiveInfinity or NegativeInfinity for a number that is too
// large or too small.
//
public static float Parse(string s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
}
public static float Parse(string s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseSingle(s, style, NumberFormatInfo.CurrentInfo);
}
public static float Parse(string s, IFormatProvider? provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
}
public static float Parse(string s, NumberStyles style, IFormatProvider? provider)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider));
}
public static float Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Float | NumberStyles.AllowThousands, IFormatProvider? provider = null)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider));
}
public static bool TryParse(string? s, out float result)
{
if (s == null)
{
result = 0;
return false;
}
return TryParse((ReadOnlySpan<char>)s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(ReadOnlySpan<char> s, out float result)
{
return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(string? s, NumberStyles style, IFormatProvider? provider, out float result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
if (s == null)
{
result = 0;
return false;
}
return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result);
}
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out float result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out float result)
{
return Number.TryParseSingle(s, style, info, out result);
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.Single;
}
bool IConvertible.ToBoolean(IFormatProvider? provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider? provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "Char"));
}
sbyte IConvertible.ToSByte(IFormatProvider? provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider? provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider? provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider? provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider? provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider? provider)
{
return Convert.ToUInt32(m_value);
}
long IConvertible.ToInt64(IFormatProvider? provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider? provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider? provider)
{
return m_value;
}
double IConvertible.ToDouble(IFormatProvider? provider)
{
return Convert.ToDouble(m_value);
}
decimal IConvertible.ToDecimal(IFormatProvider? provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider? provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "DateTime"));
}
object IConvertible.ToType(Type type, IFormatProvider? provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
/* Copyright (c) 2006, 2007 Stefanos Apostolopoulos
* Contributions from Erik Ylvisaker
* See license.txt for license info
*/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics;
using OpenTK.Graphics;
namespace OpenTK.Platform.Windows
{
/// \internal
/// <summary>
/// Provides methods to create and control an opengl context on the Windows platform.
/// This class supports OpenTK, and is not intended for use by OpenTK programs.
/// </summary>
internal sealed class WinGLContext : DesktopGraphicsContext
{
private static readonly object LoadLock = new object();
private bool vsync_supported;
private bool vsync_tear_supported;
private readonly WinGraphicsMode ModeSelector;
// We need to create a temp context in order to load
// wgl extensions (e.g. for multisampling or GL3).
// We cannot rely on any WGL extensions before
// we load them with the temporary context.
private class TemporaryContext : IDisposable
{
public ContextHandle Context;
public TemporaryContext(INativeWindow native)
{
Debug.WriteLine("[WGL] Creating temporary context to load extensions");
if (native == null)
{
throw new ArgumentNullException();
}
// Create temporary context and load WGL entry points
// First, set a compatible pixel format to the device context
// of the temp window
WinWindowInfo window = native.WindowInfo as WinWindowInfo;
WinGraphicsMode selector = new WinGraphicsMode(window.DeviceContext);
WinGLContext.SetGraphicsModePFD(selector, GraphicsMode.Default, window);
bool success = false;
// Then, construct a temporary context and load all wgl extensions
Context = new ContextHandle(Wgl.CreateContext(window.DeviceContext));
if (Context != ContextHandle.Zero)
{
// Make the context current.
// Note: on some video cards and on some virtual machines, wglMakeCurrent
// may fail with an errorcode of 6 (INVALID_HANDLE). The suggested workaround
// is to call wglMakeCurrent in a loop until it succeeds.
// See https://www.opengl.org/discussion_boards/showthread.php/171058-nVidia-wglMakeCurrent()-multiple-threads
// Sigh...
for (int retry = 0; retry < 5 && !success; retry++)
{
success = Wgl.MakeCurrent(window.DeviceContext, Context.Handle);
if (!success)
{
Debug.Print("wglMakeCurrent failed with error: {0}. Retrying", Marshal.GetLastWin32Error());
System.Threading.Thread.Sleep(10);
}
}
}
else
{
Debug.Print("[WGL] CreateContext failed with error: {0}", Marshal.GetLastWin32Error());
}
if (!success)
{
Debug.WriteLine("[WGL] Failed to create temporary context");
}
}
public void Dispose()
{
if (Context != ContextHandle.Zero)
{
Wgl.MakeCurrent(IntPtr.Zero, IntPtr.Zero);
Wgl.DeleteContext(Context.Handle);
}
}
}
public WinGLContext(GraphicsMode format, WinWindowInfo window, IGraphicsContext sharedContext,
int major, int minor, GraphicsContextFlags flags)
{
// There are many ways this code can break when accessed by multiple threads. The biggest offender is
// the sharedContext stuff, which will only become valid *after* this constructor returns.
// The easiest solution is to serialize all context construction - hence the big lock, below.
lock (LoadLock)
{
if (window == null)
{
throw new ArgumentNullException("window", "Must point to a valid window.");
}
if (window.Handle == IntPtr.Zero)
{
throw new ArgumentException("window", "Must be a valid window.");
}
IntPtr current_context = Wgl.GetCurrentContext();
INativeWindow temp_window = null;
TemporaryContext temp_context = null;
try
{
if (current_context == IntPtr.Zero)
{
// Create temporary context to load WGL extensions
temp_window = new NativeWindow();
temp_context = new TemporaryContext(temp_window);
current_context = Wgl.GetCurrentContext();
if (current_context != IntPtr.Zero && current_context == temp_context.Context.Handle)
{
new Wgl().LoadEntryPoints();
}
}
Debug.Print("OpenGL will be bound to window:{0} on thread:{1}", window.Handle,
System.Threading.Thread.CurrentThread.ManagedThreadId);
ModeSelector = new WinGraphicsMode(window.DeviceContext);
Mode = SetGraphicsModePFD(ModeSelector, format, (WinWindowInfo)window);
if (Wgl.SupportsFunction("wglCreateContextAttribsARB"))
{
try
{
Debug.Write("Using WGL_ARB_create_context... ");
List<int> attributes = new List<int>();
attributes.Add((int)ArbCreateContext.MajorVersion);
attributes.Add(major);
attributes.Add((int)ArbCreateContext.MinorVersion);
attributes.Add(minor);
if (flags != 0)
{
attributes.Add((int)ArbCreateContext.ContextFlags);
attributes.Add((int)GetARBContextFlags(flags));
attributes.Add((int)ArbCreateContext.ProfileMask);
attributes.Add((int)GetARBContextProfile(flags));
}
// According to the docs, " <attribList> specifies a list of attributes for the context.
// The list consists of a sequence of <name,value> pairs terminated by the
// value 0. [...]"
// Is this a single 0, or a <0, 0> pair? (Defensive coding: add two zeroes just in case).
attributes.Add(0);
attributes.Add(0);
Handle = new ContextHandle(
Wgl.Arb.CreateContextAttribs(
window.DeviceContext,
sharedContext != null ? (sharedContext as IGraphicsContextInternal).Context.Handle : IntPtr.Zero,
attributes.ToArray()));
if (Handle == ContextHandle.Zero)
{
Debug.Print("failed. (Error: {0})", Marshal.GetLastWin32Error());
}
}
catch (Exception e) { Debug.Print(e.ToString()); }
}
if (Handle == ContextHandle.Zero)
{
// Failed to create GL3-level context, fall back to GL2.
Debug.Write("Falling back to GL2... ");
Handle = new ContextHandle(Wgl.CreateContext(window.DeviceContext));
if (Handle == ContextHandle.Zero)
{
Handle = new ContextHandle(Wgl.CreateContext(window.DeviceContext));
}
if (Handle == ContextHandle.Zero)
{
throw new GraphicsContextException(
String.Format("Context creation failed. Wgl.CreateContext() error: {0}.",
Marshal.GetLastWin32Error()));
}
}
Debug.WriteLine(String.Format("success! (id: {0})", Handle));
}
finally
{
if (temp_context != null)
{
temp_context.Dispose();
temp_context = null;
}
if (temp_window != null)
{
temp_window.Dispose();
temp_window = null;
}
}
}
// Todo: is this comment still true?
// On intel drivers, wgl entry points appear to change
// when creating multiple contexts. As a workaround,
// we reload Wgl entry points every time we create a
// new context - this solves the issue without any apparent
// side-effects (i.e. the old contexts can still be handled
// using the new entry points.)
// Sigh...
MakeCurrent(window);
new Wgl().LoadEntryPoints();
if (sharedContext != null)
{
Marshal.GetLastWin32Error();
Debug.Write(String.Format("Sharing state with context {0}: ", sharedContext));
bool result = Wgl.ShareLists((sharedContext as IGraphicsContextInternal).Context.Handle, Handle.Handle);
Debug.WriteLine(result ? "success!" : "failed with win32 error " + Marshal.GetLastWin32Error());
}
}
private static ArbCreateContext GetARBContextFlags(GraphicsContextFlags flags)
{
ArbCreateContext result = 0;
result |= (flags & GraphicsContextFlags.ForwardCompatible) != 0 ?
ArbCreateContext.CoreProfileBit : ArbCreateContext.CompatibilityProfileBit;
return result;
}
private static ArbCreateContext GetARBContextProfile(GraphicsContextFlags flags)
{
ArbCreateContext result = 0;
result |= (flags & GraphicsContextFlags.Debug) != 0 ? ArbCreateContext.DebugBit : 0;
return result;
}
public WinGLContext(ContextHandle handle, WinWindowInfo window, IGraphicsContext sharedContext,
int major, int minor, GraphicsContextFlags flags)
{
if (handle == ContextHandle.Zero)
{
throw new ArgumentException("handle");
}
if (window == null)
{
throw new ArgumentNullException("window");
}
Handle = handle;
}
public override void SwapBuffers()
{
if (!Functions.SwapBuffers(DeviceContext))
{
throw new GraphicsContextException(String.Format(
"Failed to swap buffers for context {0} current. Error: {1}", this, Marshal.GetLastWin32Error()));
}
}
public override void MakeCurrent(IWindowInfo window)
{
lock (LoadLock)
{
bool success;
WinWindowInfo wnd = window as WinWindowInfo;
if (wnd != null)
{
if (wnd.Handle == IntPtr.Zero)
{
throw new ArgumentException("window", "Must point to a valid window.");
}
success = Wgl.MakeCurrent(wnd.DeviceContext, Handle.Handle);
DeviceContext = wnd.DeviceContext;
}
else
{
success = Wgl.MakeCurrent(IntPtr.Zero, IntPtr.Zero);
DeviceContext = IntPtr.Zero;
}
if (!success)
{
throw new GraphicsContextException(String.Format(
"Failed to make context {0} current. Error: {1}", this, Marshal.GetLastWin32Error()));
}
}
}
public override bool IsCurrent
{
get { return Wgl.GetCurrentContext() == Handle.Handle; }
}
public override int SwapInterval
{
get
{
lock (LoadLock)
{
if (vsync_supported)
{
return Wgl.Ext.GetSwapInterval();
}
else
{
return 0;
}
}
}
set
{
lock (LoadLock)
{
if (vsync_supported)
{
if (value < 0 && !vsync_tear_supported)
{
value = 1;
}
if (!Wgl.Ext.SwapInterval(value))
{
Debug.Print("wglSwapIntervalEXT call failed.");
}
}
}
}
}
public override void LoadAll()
{
lock (LoadLock)
{
new Wgl().LoadEntryPoints();
vsync_supported =
Wgl.SupportsExtension(DeviceContext, "WGL_EXT_swap_control") &&
Wgl.SupportsFunction("wglGetSwapIntervalEXT") &&
Wgl.SupportsFunction("wglSwapIntervalEXT");
vsync_tear_supported =
Wgl.SupportsExtension(DeviceContext, "WGL_EXT_swap_control_tear");
}
base.LoadAll();
}
/*
IWindowInfo IGraphicsContextInternal.Info
{
get { return (IWindowInfo)windowInfo; }
}
*/
public override IntPtr GetAddress(IntPtr function_string)
{
IntPtr address = Wgl.GetProcAddress(function_string);
if (!IsValid(address))
{
address = Functions.GetProcAddress(WinFactory.OpenGLHandle, function_string);
}
return address;
}
private static bool IsValid(IntPtr address)
{
// See https://www.opengl.org/wiki/Load_OpenGL_Functions
long a = address.ToInt64();
bool is_valid = (a < -1) || (a > 3);
return is_valid;
}
// Note: there is no relevant ARB function.
internal static GraphicsMode SetGraphicsModePFD(WinGraphicsMode mode_selector,
GraphicsMode mode, WinWindowInfo window)
{
Debug.Write("Setting pixel format... ");
if (window == null)
{
throw new ArgumentNullException("window", "Must point to a valid window.");
}
if (!mode.Index.HasValue)
{
mode = mode_selector.SelectGraphicsMode(
mode.ColorFormat, mode.Depth, mode.Stencil,
mode.Samples, mode.AccumulatorFormat,
mode.Buffers, mode.Stereo);
}
PixelFormatDescriptor pfd = new PixelFormatDescriptor();
Functions.DescribePixelFormat(
window.DeviceContext, (int)mode.Index.Value,
API.PixelFormatDescriptorSize, ref pfd);
Debug.WriteLine(mode.Index.ToString());
if (!Functions.SetPixelFormat(window.DeviceContext, (int)mode.Index.Value, ref pfd))
{
throw new GraphicsContextException(String.Format(
"Requested GraphicsMode not available. SetPixelFormat error: {0}",
Marshal.GetLastWin32Error()));
}
return mode;
}
internal IntPtr DeviceContext { get; private set; }
/// <summary>Returns a System.String describing this OpenGL context.</summary>
/// <returns>A System.String describing this OpenGL context.</returns>
public override string ToString()
{
return (this as IGraphicsContextInternal).Context.ToString();
}
protected override void Dispose(bool calledManually)
{
if (!IsDisposed)
{
if (calledManually)
{
DestroyContext();
}
IsDisposed = true;
}
}
private void DestroyContext()
{
if (Handle != ContextHandle.Zero)
{
try
{
// This will fail if the user calls Dispose() on thread X when the context is current on thread Y.
if (!Wgl.DeleteContext(Handle.Handle))
{
Debug.Print("Failed to destroy OpenGL context {0}. Error: {1}",
Handle.ToString(), Marshal.GetLastWin32Error());
}
}
catch (AccessViolationException e)
{
Debug.WriteLine("An access violation occured while destroying the OpenGL context. Please report at https://github.com/opentk/opentk/issues");
Debug.Indent();
Debug.Print("Marshal.GetLastWin32Error(): {0}", Marshal.GetLastWin32Error().ToString());
Debug.WriteLine(e.ToString());
Debug.Unindent();
}
Handle = ContextHandle.Zero;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Win32;
using System.ServiceProcess;
namespace ZBrad.FabricLib.Utilities
{
/// <summary>
/// WindowsFabric control methods and settings
/// </summary>
public class Control
{
#region private data
internal const string WindowsFabricRegKey = @"SOFTWARE\Microsoft\Windows Fabric";
internal const string WindowsFabricHostSvcKey = @"SYSTEM\CurrentControlSet\Services\FabricHostSvc";
internal const string VsWebProjectKey = @"Software\Microsoft\VisualStudio\12.0\WebProjects";
static NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();
static bool isEnvValid = false;
static string[] cleanDirs = { "\\ImageStore", "\\Node1\\Fabric\\work", "\\Node2\\Fabric\\work", "\\Node3\\Fabric\\work", "\\Node4\\Fabric\\work", "\\Node5\\Fabric\\work" };
static string logmanPath = Environment.ExpandEnvironmentVariables("%SystemRoot%\\system32\\logman.exe");
//// static string powershellPath = Environment.ExpandEnvironmentVariables("%SystemRoot%\\system32\\WindowsPowerShell\\v1.0\\powershell.exe");
static string fabricHostPath = null;
// TODO: replace with psh
static string fabricDeployerPath = null;
static string imageClientPath = null;
static string tracePat = @"(?<Collector>Fabric\w+)\s+(?<Type>\w+)\s+(?<Status>\w+)";
static Regex traceRegex = new Regex(tracePat, RegexOptions.Compiled);
private PackageSettings currentPackage = new PackageSettings();
private ClusterSettings currentCluster = new ClusterSettings();
private List<string> stoppedTraces;
#endregion
static Control()
{
try
{
using (RegistryKey hklm64 = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
{
using (RegistryKey key = hklm64.OpenSubKey(WindowsFabricRegKey))
{
FabricDataRoot = ((string)key.GetValue("FabricDataRoot", string.Empty)).TrimEnd('\\'); // remove any trailing backslash
FabricBinRoot = ((string)key.GetValue("FabricBinRoot", string.Empty)).TrimEnd('\\'); // remove any trailing backslash
FabricCodePath = ((string)key.GetValue("FabricCodePath", string.Empty)).TrimEnd('\\'); // remove any trailing backslash
}
}
fabricHostPath = Path.Combine(FabricBinRoot, "FabricHost.exe");
fabricDeployerPath = Path.Combine(FabricCodePath, "FabricDeployer.exe");
imageClientPath = Path.Combine(FabricCodePath, "ImageStoreClient.exe");
isEnvValid = true;
}
catch (Exception e)
{
log.Error(e, "Get Variables Failed");
}
}
#region public static properties
/// <summary>
/// gets the WindowsFabric data path
/// </summary>
public static string FabricDataRoot { get; private set; }
/// <summary>
/// gets the WindowsFabric binary path
/// </summary>
public static string FabricBinRoot { get; private set; }
/// <summary>
/// gets the WindowsFabric code path
/// </summary>
public static string FabricCodePath { get; private set; }
#endregion
#region public properties
/// <summary>
/// gets or sets current package settings
/// </summary>
public PackageSettings Package { get { return this.currentPackage; } set { this.currentPackage = value; } }
/// <summary>
/// gets or sets current cluster settings
/// </summary>
public ClusterSettings Cluster
{
get { return this.currentCluster; }
set { this.currentCluster = value; }
}
/// <summary>
/// gets the last exception
/// </summary>
public Exception LastException { get; private set; }
/// <summary>
/// gets the last error text
/// </summary>
public string LastError { get; private set; }
/// <summary>
/// gets the last informational text
/// </summary>
public string LastInfo { get; private set; }
/// <summary>
/// gets status of host running
/// </summary>
public bool IsHostRunning
{
get
{
Process p;
if (this.IsHostConsoleRunning(out p))
{
this.Cluster.HostType = HostType.Console;
return true;
}
if (isRunningAsService())
{
this.Cluster.HostType = HostType.Service;
return true;
}
return false;
}
}
#endregion
#region public static methods
/// <summary>
/// tests if environment is ok
/// </summary>
/// <returns>true if valid environment</returns>
public static bool IsEnvironmentOk()
{
return isEnvValid;
}
#endregion
#region public methods
/// <summary>
/// test if environment has been initialized
/// </summary>
/// <returns></returns>
public bool IsInitializedForDevelopment()
{
if (!isFabricHostSvcManual())
{
this.Info("FabricHostSvc is not set to manual");
return false;
}
if (!isUseX64Web())
{
this.Info("IISExpress not configured for x64 development");
return false;
}
return true;
}
/// <summary>
/// sets tracing status
/// </summary>
/// <param name="isLogging">status of tracing</param>
public void SetLogging(bool isLogging)
{
if (isLogging)
NLog.LogManager.EnableLogging();
else
NLog.LogManager.DisableLogging();
}
public bool TryClusterStart()
{
if (!IsEnvironmentOk())
{
this.Error("environment check failed, development cluster not initialized");
return false;
}
bool wasCleaned = false;
ServiceController sc;
if (!this.IsHostServiceRunning(out sc))
{
// if running as a service, shut it down (permanently)
if (!TryServiceStop(sc))
return false;
// make sure we clean up from service run
this.TryClusterRemove();
this.TryLogsClean();
wasCleaned = true;
}
// set service start to manual (if not already set)
// HKLM:\SYSTEM\CurrentControlSet\Services\FabricHostSvc
object value = Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\FabricHostSvc", "Start", -1);
if (value != null && value is int && ((int)value) != 3)
{
Microsoft.Win32.Registry.SetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\FabricHostSvc", "Start", 3);
if (!wasCleaned)
{
// if possibly previously running as a service, make sure it's fully cleaned up
this.TryClusterRemove();
this.TryLogsClean();
}
}
return TryHostConsoleStart();
}
/// <summary>
/// stop currently running cluster, stop/flush any traces
/// </summary>
/// <returns>true if successful</returns>
public bool TryClusterStop()
{
if (!IsEnvironmentOk())
{
this.Error("environment check failed");
return false;
}
if (!this.IsHostRunning)
{
this.Error("host is not running");
return false;
}
switch (this.Cluster.HostType)
{
case HostType.Console:
return this.TryHostConsoleStop();
case HostType.Service:
return this.TryHostServiceStop();
default:
this.Error("unhandled host type {0}", this.Cluster.HostType);
return false;
}
}
/// <summary>
/// try to stop traces
/// </summary>
/// <param name="stoppedTraces">the stopped traces</param>
/// <returns>true if successful</returns>
public bool TryTracesStop(out List<string> stoppedTraces)
{
stoppedTraces = null;
if (!IsEnvironmentOk())
{
return false;
}
if (this.IsHostRunning)
{
this.Info("cannot stop traces while host is running");
return false;
}
this.Info("stopping traces");
List<LogmanTrace> list = this.GetTraces();
if (list == null || list.Count == 0)
{
this.Info("no logman traces found");
return true;
}
stoppedTraces = new List<string>();
foreach (LogmanTrace lt in list)
{
if (lt.Status == "Running")
{
string response;
int rc = this.ExecuteProgram(logmanPath, "stop " + lt.DataCollectorSet, out response);
if (rc != 0)
{
this.Info("Could not stop trace " + lt.DataCollectorSet + "\nlogman response:\n" + response);
return false;
}
stoppedTraces.Add(lt.DataCollectorSet);
}
}
this.Info("traces stopped");
return true;
}
/// <summary>
/// try to stop fabric host service
/// </summary>
/// <returns>true if not running or successfully stopped</returns>
public bool TryHostServiceStop()
{
if (!IsEnvironmentOk())
{
return false;
}
ServiceController sc;
if (!this.IsHostServiceRunning(out sc))
{
this.Error("service is not running");
return false;
}
if (!TryServiceStop(sc))
return false;
return true;
}
private bool TryServiceStop(ServiceController sc)
{
try
{
if (sc.Status == ServiceControllerStatus.Running)
{
sc.Stop();
}
int limit = Defaults.WaitRetryLimit;
while (isRunningAsService() && limit >= 0)
{
Task.Delay(Defaults.WaitDelay);
this.Info("waiting for service to stop");
}
if (limit < 0)
{
this.Error("failed to stop windows fabric service");
return false;
}
return true;
}
catch (Exception e)
{
this.Info("service stop failed, error=" + e.Message);
return false;
}
}
/// <summary>
/// clean the cluster completely
/// </summary>
/// <returns>true if successful</returns>
public bool TryClusterClean()
{
if (!IsEnvironmentOk())
{
return false;
}
if (this.IsHostRunning)
{
this.Error("Cannot clean cluster while running");
return false;
}
bool wasSuccessful = true;
IEnumerator<string> dirs = SafeEnumerator.GetDirectoryEnumerator(Control.FabricDataRoot, "work");
while (dirs.MoveNext())
{
try
{
Directory.Delete(dirs.Current, true);
}
catch (Exception e)
{
wasSuccessful = false;
this.Error("delete work folder failed: {0}", e.Message);
}
}
if (Directory.Exists(ClusterSettings.DevImageStoreFolder))
{
try
{
Directory.Delete(ClusterSettings.DevImageStoreFolder, true);
Directory.CreateDirectory(ClusterSettings.DevImageStoreFolder);
}
catch (Exception e)
{
wasSuccessful = false;
this.Error("delete image store folder failed: {0}", e.InnerException != null ? e.InnerException.Message : e.Message);
}
}
else
{
Directory.CreateDirectory(ClusterSettings.DevImageStoreFolder);
}
IEnumerator<string> logFiles = SafeEnumerator.GetFileEnumerator(FabricDataRoot, "ReplicatorShared.log");
while (logFiles.MoveNext())
{
try
{
File.Delete(logFiles.Current);
}
catch (Exception e)
{
wasSuccessful = false;
this.Error("delete replication log failed: {0}", e.Message);
}
}
if (!wasSuccessful)
{
this.Info("failed to clean cluster");
return false;
}
this.Info("Cluster clean successful");
return true;
}
/// <summary>
/// try to delete the cluster
/// </summary>
/// <returns>true if successful</returns>
public bool TryClusterDelete()
{
if (!IsEnvironmentOk())
{
return false;
}
if (!this.TryClusterStop())
{
return false;
}
this.TryClusterRemove();
this.TryLogsClean();
return true;
}
/// <summary>
/// Initialize this environment for Windows Fabric Development
///
/// Actions are:
/// - set WinFabSvc to manual start
/// - set Visual Studio IISExpress to default to x64 (for vs2013)
/// </summary>
public bool TryInitializeForDevelopment()
{
if (IsInitializedForDevelopment())
return true;
if (!IsEnvironmentOk())
{
Error("Windows Fabric not installed");
return false;
}
if (this.IsHostRunning)
{
if (!TryClusterStop())
return false;
}
if (!this.TryClusterRemove())
return false;
if (!this.TryLogsClean())
return false;
if (!trySetFabricHostSvcManual())
{
Error("could not set fabric host service to manual start");
return false;
}
if (!trySetUseX64Web())
{
Error("could not set iisexpress default to x64");
return false;
}
return IsInitializedForDevelopment();
}
static bool isFabricHostSvcManual()
{
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default))
{
using (RegistryKey key = hklm.OpenSubKey(WindowsFabricHostSvcKey))
{
if (key == null)
return false;
// get service start options
object o = key.GetValue("Start");
if (o != null && o is int)
{
ServiceStartMode startValue = (ServiceStartMode)o;
return startValue == ServiceStartMode.Manual;
}
return false;
}
}
}
static bool trySetFabricHostSvcManual()
{
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default))
{
using (RegistryKey key = hklm.OpenSubKey(WindowsFabricHostSvcKey, true))
{
if (key == null)
return false;
// set service to manual start
key.SetValue("Start", ((int) ServiceStartMode.Manual));
return true;
}
}
}
static bool trySetUseX64Web()
{
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default))
{
using (RegistryKey key = hklm.OpenSubKey(VsWebProjectKey, true))
{
if (key == null)
return false;
// set iisexpress default to x64
key.SetValue("Use64BitIISExpress", 1);
return true;
}
}
}
static bool isUseX64Web()
{
using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default))
{
using (RegistryKey key = hklm.OpenSubKey(VsWebProjectKey, true))
{
if (key == null)
return false;
// get iisexpress default HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\12.0\WebProjects Use64BitIISExpress
object o = key.GetValue("Use64BitIISExpress");
if (o == null)
return false;
int value = (int)o;
bool result = value == 1;
return result;
}
}
}
static bool isRunningAsService()
{
ServiceController sc = GetFabricService();
if (sc == null)
return false;
return sc.Status == ServiceControllerStatus.Running;
}
/// <summary>
/// gets service host info
/// </summary>
/// <param name="sc">the service controller</param>
/// <returns>true if running</returns>
public bool IsHostServiceRunning(out ServiceController sc)
{
sc = null;
if (!IsEnvironmentOk())
{
return false;
}
sc = GetFabricService();
if (sc == null)
{
return false;
}
if (sc.Status == ServiceControllerStatus.Running)
{
this.currentCluster.HostType = HostType.Service;
return true;
}
return false;
}
/// <summary>
/// removes tickets
/// </summary>
/// <returns>true if successful</returns>
public bool TryTicketsClean()
{
if (!IsEnvironmentOk())
{
return false;
}
if (this.IsHostRunning)
{
return false;
}
bool wasDeleted = false;
string[] exts = { "*.tkt", "*.sni" };
foreach (string ext in exts)
{
IEnumerable<string> files = Directory.EnumerateFiles(FabricDataRoot, ext, SearchOption.AllDirectories);
foreach (string s in files)
{
try
{
File.Delete(s);
wasDeleted = true;
}
catch (Exception e)
{
this.Error("failed to delete ticket {0}, exception: {1}", s, e.Message);
return false;
}
}
}
if (wasDeleted)
{
this.Info("Deleted tickets successfully");
}
else
{
this.Info("%No tickets found to delete");
}
return true;
}
/// <summary>
/// try to remove from image store
/// </summary>
/// <returns>true if successful</returns>
public bool TryImageStoreRemove()
{
if (!IsEnvironmentOk())
{
return false;
}
if (this.Package.ApplicationTypeName == null)
{
return false;
}
StringBuilder sb = new StringBuilder();
sb.Append(" Delete -c \"");
sb.Append(this.Cluster.ImageStoreConnection);
sb.Append("\" -x \"");
sb.Append(this.Package.ImageStoreRelativePath);
sb.Append("\"");
string args = sb.ToString();
string response;
int rc = this.ExecuteProgram(imageClientPath, args, out response);
if (rc != 0)
{
this.Error("ImageStoreClient failed, response:\n{0}", response);
return false;
}
this.Info("ImageStoreClient successfully removed application");
return true;
}
/// <summary>
/// try to upload to image store
/// </summary>
/// <returns>true if successful</returns>
public bool TryImageStoreUpload()
{
if (!IsEnvironmentOk())
{
return false;
}
StringBuilder sb = new StringBuilder();
#if POWERSHELL
sb.Append(" -Command Copy-WindowsFabricApplicationPackage -ImageStoreConnectionString \"");
sb.Append(this.Cluster.ImageStoreConnection);
sb.Append("\" -RelativePath \"");
sb.Append(this.Package.ImageStoreRelativePath);
sb.Append("\" -ApplicationPackagePath \"");
sb.Append(this.Package.PackagePath.TrimEnd('\\'));
sb.Append("\" -Force");
#endif
sb.Append(" Upload -c \"");
sb.Append(this.Cluster.ImageStoreConnection);
sb.Append("\" -x \"");
sb.Append(this.Package.ImageStoreRelativePath);
sb.Append("\" -l \"");
sb.Append(this.Package.PackagePath.TrimEnd('\\'));
sb.Append("\" -g AtomicCopy");
string args = sb.ToString();
// TODO: replace with powershell command
string response;
int rc = this.ExecuteProgram(imageClientPath, args, out response);
if (rc != 0)
{
this.Error("ImageStoreClient failed, response:\n{0}", response);
return false;
}
this.Info("ImageStoreClient upload successful");
return true;
}
/// <summary>
/// test if cluster has been deployed
/// </summary>
/// <returns>true if cluster has been deployed</returns>
public bool IsClusterDeployed()
{
if (File.Exists(FabricDataRoot + "\\FabricHostSettings.xml"))
{
return true;
}
return false;
}
/// <summary>
/// try to create dev cluster
/// </summary>
/// <returns>true if successful</returns>
public bool TryClusterCreate()
{
if (!IsEnvironmentOk())
{
return false;
}
if (!this.TryClusterRemove())
{
return false;
}
if (this.Cluster.FilePath == null)
{
if (!this.TryClusterFileCreate())
{
this.Error("could not find or create default cluster file");
return false;
}
}
if (!TestClusterManifest())
return false;
return this.TryClusterDeploy();
}
private bool TryClusterDeploy()
{
FileInfo fi = new FileInfo(this.Cluster.FilePath);
if (!fi.Exists)
{
this.Error("Could not find cluster manifest at: " + this.Cluster.FilePath);
return false;
}
StringBuilder sb = new StringBuilder("/operation:");
string operation;
if (this.Cluster.Data.TryGetValue("DeploymentType", out operation))
{
this.Info("deployment operation specified: {0}", operation);
}
else
{
operation = "CREATE";
this.Info("defaulting deployment operation to: CREATE");
}
sb.Append(operation);
sb.Append(" \"/cm:");
sb.Append(fi.FullName);
sb.Append('"');
string args = sb.ToString();
string response;
int rc = this.ExecuteProgram(fabricDeployerPath, args, out response);
if (rc != 0)
{
this.Error("FabricDeployer failed, response:\n{0}", response);
return false;
}
this.Info("Cluster create successful");
return true;
}
/// <summary>
/// try to remove cluster
/// </summary>
/// <returns>true if successful</returns>
public bool TryClusterRemove()
{
if (!IsEnvironmentOk())
{
return false;
}
if (this.IsHostRunning)
{
this.Info("Cannot remove cluster with running host");
return false;
}
string args = "/operation:Remove";
string response;
int rc = this.ExecuteProgram(fabricDeployerPath, args, out response);
if (rc != 0)
{
this.Error("FabricDeployer failed, response:\n{0}", response);
return false;
}
if (File.Exists(FabricDataRoot + @"\FabricHostSettings.xml"))
File.Delete(FabricDataRoot + @"\FabricHostSettings.xml");
this.Info("Cluster remove successful");
return true;
}
/// <summary>
/// try to clean logs
/// </summary>
/// <returns>true if successful</returns>
public bool TryLogsClean()
{
if (!IsEnvironmentOk())
{
return false;
}
if (this.IsHostRunning)
{
this.Error("Cannot clean logs while cluster running");
return false;
}
if (!this.TryTracesStop(out stoppedTraces))
{
this.Error("Unable to stop traces");
return false;
}
string logFolder = FabricDataRoot + @"\log";
if (Directory.Exists(logFolder))
{
try
{
Directory.Delete(logFolder, true);
}
catch (Exception e)
{
this.Error("failed to clean trace logs, exception: {0}", e.Message);
return false;
}
if (Directory.Exists(logFolder))
{
this.Error("unable to remove log folder");
return false;
}
}
string diagFolder = FabricDataRoot + @"\DiagnosticsStore";
if (Directory.Exists(diagFolder))
{
try
{
Directory.Delete(diagFolder, true);
}
catch (Exception e)
{
this.Error("failed to clean diagnostics logs, exception: {0}", e.Message);
return false;
}
}
this.Info("Logs removed successfully");
return true;
}
/// <summary>
/// start the specified traces
/// </summary>
/// <param name="tracesToStart">list of traces</param>
/// <returns>true if successful</returns>
public bool TryTracesStart(List<string> tracesToStart)
{
if (!IsEnvironmentOk())
{
return false;
}
this.Info("starting traces");
if (tracesToStart == null || tracesToStart.Count == 0)
{
this.Info("No traces specified to start");
return true;
}
foreach (string traceName in tracesToStart)
{
string response;
int rc = this.ExecuteProgram(logmanPath, "start " + traceName, out response);
if (rc != 0)
{
this.Error("Could not start trace {0} logman response: {1}", traceName, response);
return false;
}
}
this.Info("traces started");
return true;
}
/// <summary>
/// try to start traces
/// </summary>
/// <returns>true if successful</returns>
public bool TryTracesStart()
{
if (!IsEnvironmentOk())
{
return false;
}
List<LogmanTrace> list = this.GetTraces();
if (list == null || list.Count == 0)
{
this.Info("%No logman traces found");
return true;
}
List<string> tracesToStart = new List<string>();
foreach (LogmanTrace lt in list)
{
if (lt.Status == "Stopped")
{
tracesToStart.Add(lt.DataCollectorSet);
}
}
return this.TryTracesStart(tracesToStart);
}
/// <summary>
/// gets host console process
/// </summary>
/// <param name="p">the <see cref="Process"/> instance</param>
/// <returns>true if running</returns>
public bool IsHostConsoleRunning(out Process p)
{
p = null;
if (!IsEnvironmentOk())
{
return false;
}
// filter out condition of service FabricHost is running
if (isRunningAsService())
return false;
try
{
Process[] list = null;
try
{
list = Process.GetProcessesByName("FabricHost");
}
catch
{
return false;
}
if (list == null || list.Length == 0)
{
return false;
}
p = list[0];
this.currentPackage.Data[PackageSettings.Pid] = p.Id.ToString(CultureInfo.InvariantCulture);
this.currentPackage.Data[PackageSettings.ProcessName] = p.ProcessName;
return true;
}
catch
{
return false;
}
}
/// <summary>
/// try to start service host
/// </summary>
/// <returns>true if successful</returns>
public bool TryHostServiceStart()
{
if (!IsEnvironmentOk())
{
return false;
}
if (this.IsHostRunning)
{
this.Error("Host already running");
return false;
}
// if no process or service running, then first delete tickets (for faster startup)
if (!this.TryTicketsClean())
{
this.Error("Ticket clean failed");
return false;
}
this.Cluster.HostType = HostType.Service;
ServiceController sc = GetFabricService();
try
{
sc.Start();
}
catch (Exception e)
{
this.LastException = e;
if (e.InnerException != null)
{
this.Error("Start failed, exception: {0}", e.InnerException.Message);
}
else
{
this.Error("Start failed, exception: {0}", e.Message);
}
return false;
}
return true;
}
/// <summary>
/// try to start console host
/// </summary>
/// <returns>true if successful</returns>
public bool TryHostConsoleStart()
{
if (!IsEnvironmentOk())
{
return false;
}
try
{
if (this.IsHostRunning)
{
this.Error("Host already running");
return false;
}
// if no process or service running, then first delete tickets (for faster startup)
if (!this.TryTicketsClean())
{
this.Error("Ticket clean failed");
return false;
}
this.Cluster.HostType = HostType.Console;
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = fabricHostPath;
psi.Arguments = "-c -activateHidden"; // console
this.Info("tryStartHost cmd=" + psi.FileName + " " + psi.Arguments);
Process p = Process.Start(psi);
this.currentPackage.Data[PackageSettings.ProcessName] = p.ProcessName;
this.currentPackage.Data[PackageSettings.Pid] = p.Id.ToString(CultureInfo.InvariantCulture);
Task.Factory.StartNew(() =>
{
p.WaitForExit();
string temp;
this.currentPackage.Data.TryRemove(PackageSettings.ProcessName, out temp);
this.currentPackage.Data.TryRemove(PackageSettings.Pid, out temp);
});
return true;
}
catch
{
return false;
}
}
/// <summary>
/// try to stop fabric host console process
/// </summary>
/// <returns>true if host was not running or was successfully stopped</returns>
public bool TryHostConsoleStop()
{
if (!IsEnvironmentOk())
{
return false;
}
Process p;
if (!this.IsHostConsoleRunning(out p))
{
return true;
}
try
{
p.Kill();
int retry = Defaults.WaitRetryLimit;
while (!p.HasExited)
{
if (retry <= 0)
{
return false;
}
Task.Delay(Defaults.WaitDelay).Wait();
retry--;
}
return true;
}
catch
{
}
return false;
}
/// <summary>
/// try to create cluster file
/// </summary>
/// <returns>true if successful</returns>
public bool TryClusterFileCreate()
{
if (File.Exists(this.Cluster.FilePath))
{
return true;
}
this.Info("No default cluster found, creating default cluster file");
// see if we know the file?
Assembly assembly = Assembly.GetExecutingAssembly();
if (this.Cluster.ClusterPath == null)
{
this.Cluster.ClusterPath = Path.GetDirectoryName(assembly.Location);
}
if (this.Cluster.ClusterFile == null)
{
this.Cluster.ClusterFile = ClusterSettings.DefaultClusterName;
}
else
{
if (this.Cluster.ClusterFile != ClusterSettings.DefaultClusterName)
{
this.Error("Unknown cluster file '{0}' cannot be created", this.Cluster.ClusterFile);
return false;
}
}
// uncomment this code if you need to find out what the embedded assembly resource name is
// string[] names = assembly.GetManifestResourceNames();
try
{
Stream stream = assembly.GetManifestResourceStream(ClusterSettings.DefaultClusterResourceFile);
if (stream == null)
{
return false;
}
// else get it out of our resources
using (StreamReader sr = new StreamReader(stream))
using (StreamWriter sw = new StreamWriter(this.Cluster.FilePath))
{
sw.Write(sr.ReadToEnd());
}
return true;
}
catch
{
return false;
}
}
#endregion
#region static methods
static ServiceController GetFabricService()
{
return new ServiceController("FabricHostSvc");
}
/// <summary>
/// executes the provided program
/// </summary>
/// <param name="program">program path</param>
/// <param name="arg">program arguments</param>
/// <param name="response">any console responses</param>
/// <returns>exit code</returns>
private int ExecuteProgram(string program, string arg, out string response)
{
string args = string.Empty;
response = string.Empty;
if (arg != null)
{
args = arg;
}
program = GetNative(program);
if (program == null)
return -1;
this.Info("ExecuteProgram: calling '{0}' with '{1}'", program, args);
string progInfo = null;
string progError = null;
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = program;
psi.Arguments = args;
psi.WorkingDirectory = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process p = new Process();
p.StartInfo = psi;
p.Start();
Task<string> asyncOut = p.StandardOutput.ReadToEndAsync();
Task<string> asyncErr = p.StandardError.ReadToEndAsync();
p.WaitForExit();
progInfo = asyncOut.Result;
if (!string.IsNullOrWhiteSpace(progInfo))
{
this.Info(progInfo);
}
progError = asyncErr.Result;
if (!string.IsNullOrWhiteSpace(progError))
{
this.Error(progError);
}
response = progInfo + progError;
return p.ExitCode;
}
static string windir = System.Environment.GetEnvironmentVariable("WINDIR");
private string GetNative(string program)
{
FileInfo fi = new FileInfo(program);
if (fi.Exists)
return fi.FullName;
string path = windir + @"\sysnative" + program;
fi = new FileInfo(path);
if (fi.Exists)
return fi.FullName;
path = windir + @"\system32" + program;
fi = new FileInfo(path);
if (fi.Exists)
return fi.FullName;
this.Error("could not find program: {0}", program);
return null;
}
private List<LogmanTrace> GetTraces()
{
string response;
int exitCode = this.ExecuteProgram(logmanPath, string.Empty, out response);
if (exitCode != 0)
{
return null;
}
List<LogmanTrace> list = new List<LogmanTrace>();
using (StringReader sr = new StringReader(response))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Match m = traceRegex.Match(line);
if (m.Success)
{
LogmanTrace lt = new LogmanTrace();
lt.DataCollectorSet = m.Groups["Collector"].Value;
lt.Type = m.Groups["Type"].Value;
lt.Status = m.Groups["Status"].Value;
list.Add(lt);
}
}
}
return list;
}
#endregion
private void Info(string s)
{
this.LastInfo = s;
log.Info(s);
}
private void Info(string s, params object[] args)
{
this.LastInfo = string.Format(s, args);
log.Info(s, args);
}
private void Error(string s)
{
this.LastError = s;
log.Error(s);
}
private void Error(string s, params object[] args)
{
this.LastError = string.Format(s, args);
log.Error(s, args);
}
private const string PowershellExe = @"\WindowsPowerShell\v1.0\Powershell.exe";
private const string CmdExe = @"\cmd.exe";
public bool TestClusterManifest()
{
if (!this.IsClusterDeployed())
{
if (!this.TryClusterFileCreate())
return false;
}
// test is bad, in that if it returns false, then the reason shows up in console out
string response;
int rc = ExecuteProgram(PowershellExe, "Test-WindowsFabricClusterManifest '" + this.Cluster.FilePath + "'", out response);
if (rc != 0)
return false;
string[] results = response.Split('\r', '\n');
if (results.Length > 0 && results[0].StartsWith("True"))
return true;
if (results.Length > 2 && results[2].StartsWith("False"))
this.Error(results[0]); // reason is in first line
else
this.Error("unexpected response from Test-WindowsFabricClusterManifest");
return false;
}
#region private classes
private class LogmanTrace
{
/// <summary>
/// data collector set
/// </summary>
public string DataCollectorSet { get; set; }
/// <summary>
/// trace type
/// </summary>
public string Type { get; set; }
/// <summary>
/// trace status
/// </summary>
public string Status { get; set; }
}
#endregion
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Structure;
namespace Revit.SDK.Samples.Reinforcement.CS
{
/// <summary>
/// The geometry support for reinforcement creation on beam.
/// It can prepare the geometry information for top rebar, bottom and transverse rebar creation
/// </summary>
public class BeamGeometrySupport : GeometrySupport
{
// Private members
double m_beamLength; //the length of the beam
double m_beamWidth; //the width of the beam
double m_beamHeight; //the height of the beam
/// <summary>
/// constructor
/// </summary>
/// <param name="element">the beam which the rebars are placed on</param>
/// <param name="geoOptions">the geometry option</param>
public BeamGeometrySupport(FamilyInstance element, Options geoOptions)
: base(element, geoOptions)
{
// assert the host element is a beam
if (!element.StructuralType.Equals(StructuralType.Beam))
{
throw new Exception("BeamGeometrySupport can only work for beam instance.");
}
// Get the length, width and height of the beam.
m_beamLength = GetDrivingLineLength();
m_beamWidth = GetBeamWidth();
m_beamHeight = GetBeamHeight();
}
/// <summary>
/// Get the geometry information for top rebar
/// </summary>
/// <param name="location">indicate where top rebar is placed</param>
/// <returns>the gotten geometry information</returns>
public RebarGeometry GetTopRebar(TopRebarLocation location)
{
// sort the points of the swept profile
XYZHeightComparer comparer = new XYZHeightComparer();
m_points.Sort(comparer);
// Get the normal parameter for rebar creation
List<Autodesk.Revit.DB.XYZ > directions = GetRelatedVectors(m_points[3]);
directions.Sort(comparer);
Autodesk.Revit.DB.XYZ normal = directions[1];
double offset = 0; //the offset from the beam surface to the rebar
double startPointOffset = 0; // the offset of start point from swept profile
double rebarLength = m_beamLength / 3; //the length of the rebar
int rebarNumber = BeamRebarData.TopRebarNumber; //the number of the rebar
// set offset and startPointOffset according to the location of rebar
switch (location)
{
case TopRebarLocation.Start: // top start rebar
offset = BeamRebarData.TopEndOffset;
break;
case TopRebarLocation.Center: // top center rebar
offset = BeamRebarData.TopCenterOffset;
startPointOffset = m_beamLength / 3 - 0.5;
rebarLength = m_beamLength / 3 + 1;
break;
case TopRebarLocation.End: // top end rebar
offset = BeamRebarData.TopEndOffset;
startPointOffset = m_beamLength * 2 / 3;
break;
default:
throw new Exception("The program should never go here.");
}
// Get the curve which define the shape of the top rebar curve
List<Autodesk.Revit.DB.XYZ > movedPoints = OffsetPoints(offset);
Autodesk.Revit.DB.XYZ startPoint = movedPoints[movedPoints.Count - 1];
// offset the start point according startPointOffset
startPoint = GeomUtil.OffsetPoint(startPoint, m_drivingVector, startPointOffset);
// get the coordinate of endpoint
Autodesk.Revit.DB.XYZ endPoint = GeomUtil.OffsetPoint(startPoint, m_drivingVector, rebarLength);
IList<Curve> curves = new List<Curve>(); //the profile of the top rebar
curves.Add(Line.get_Bound(startPoint, endPoint));
// the spacing of the rebar
double spacing = spacing = (m_beamWidth - 2 * offset) / (rebarNumber - 1);
// return the rebar geometry information
return new RebarGeometry(normal, curves, rebarNumber, spacing);
}
/// <summary>
/// Get the geometry information of bottom rebar
/// </summary>
/// <returns>the gotten geometry information</returns>
public RebarGeometry GetBottomRebar()
{
// sort the points of the swept profile
XYZHeightComparer comparer = new XYZHeightComparer();
m_points.Sort(comparer);
// Get the normal parameter for bottom rebar creation
List<Autodesk.Revit.DB.XYZ > directions = GetRelatedVectors(m_points[0]);
directions.Sort(comparer);
Autodesk.Revit.DB.XYZ normal = directions[0];
double offset = BeamRebarData.BottomOffset; //offset value of the rebar
int rebarNumber = BeamRebarData.BottomRebarNumber; //the number of the rebar
// the spacing of the rebar
double spacing = (m_beamWidth - 2 * offset) / (rebarNumber - 1);
// Get the curve which define the shape of the bottom rebar curve
List<Autodesk.Revit.DB.XYZ > movedPoints = OffsetPoints(offset);
Autodesk.Revit.DB.XYZ startPoint = movedPoints[0]; //get the coordinate of startpoint
//get the coordinate of endpoint
Autodesk.Revit.DB.XYZ endPoint = GeomUtil.OffsetPoint(startPoint, m_drivingVector, m_beamLength);
IList<Curve> curves = new List<Curve>(); //the profile of the bottom rebar
curves.Add(Line.get_Bound(startPoint, endPoint));
// return the rebar geometry information
return new RebarGeometry(normal, curves, rebarNumber, spacing);
}
/// <summary>
/// Get the geometry information of transverse rebar
/// </summary>
/// <param name="location">indicate which part of transverse rebar</param>
/// <param name="spacing">the spacing of the rebar</param>
/// <returns>the gotten geometry information</returns>
public RebarGeometry GetTransverseRebar(TransverseRebarLocation location, double spacing)
{
// sort the points of the swept profile
XYZHeightComparer comparer = new XYZHeightComparer();
m_points.Sort(comparer);
// the offset from the beam surface to the rebar
double offset = BeamRebarData.TransverseOffset;
// the offset from the beam end to the transverse end
double endOffset = BeamRebarData.TransverseEndOffset;
// the offset between two transverses
double betweenOffset = BeamRebarData.TransverseSpaceBetween;
// the length of the transverse rebar
double rebarLength = (m_beamLength - 2 * endOffset - 2 * betweenOffset) / 3;
// the number of the transverse rebar
int rebarNumber = (int)(rebarLength / spacing) + 1;
// get the origin and normal parameter for rebar creation
Autodesk.Revit.DB.XYZ normal = m_drivingVector;
double curveOffset = 0;
//judge the coordinate of transverse rebar according to the location
switch (location)
{
case TransverseRebarLocation.Start: // start transverse rebar
curveOffset = endOffset;
break;
case TransverseRebarLocation.Center: // center transverse rebar
curveOffset = endOffset + rebarLength + betweenOffset;
curveOffset = curveOffset + (rebarLength % spacing) / 2;
break;
case TransverseRebarLocation.End: // end transverse rebar
curveOffset = m_beamLength - endOffset - rebarLength + (rebarLength % spacing);
break;
default:
throw new Exception("The program should never go here.");
}
// get the profile of the transverse rebar
List<Autodesk.Revit.DB.XYZ > movedPoints = OffsetPoints(offset);
// Translate curves points
List<Autodesk.Revit.DB.XYZ > translatedPoints = new List<Autodesk.Revit.DB.XYZ >();
foreach (Autodesk.Revit.DB.XYZ point in movedPoints)
{
translatedPoints.Add(GeomUtil.OffsetPoint(point, m_drivingVector, curveOffset));
}
IList<Curve> curves = new List<Curve>();
Autodesk.Revit.DB.XYZ first = translatedPoints[0];
Autodesk.Revit.DB.XYZ second = translatedPoints[1];
Autodesk.Revit.DB.XYZ third = translatedPoints[2];
Autodesk.Revit.DB.XYZ fourth = translatedPoints[3];
curves.Add(Line.get_Bound(first, second));
curves.Add(Line.get_Bound(second, fourth));
curves.Add(Line.get_Bound(fourth, third));
curves.Add(Line.get_Bound(third, first));
// return the rebar geometry information
return new RebarGeometry(normal, curves, rebarNumber, spacing);
}
/// <summary>
/// Get the down direction, which stand for the top hook direction
/// </summary>
/// <returns>the down direction</returns>
public Autodesk.Revit.DB.XYZ GetDownDirection()
{
XYZHeightComparer comparer = new XYZHeightComparer();
m_points.Sort(comparer);
Autodesk.Revit.DB.XYZ refPoint = m_points[3];
List<Autodesk.Revit.DB.XYZ > directions = GetRelatedVectors(refPoint);
directions.Sort(comparer);
return directions[0];
}
/// <summary>
/// Get the width of the beam
/// </summary>
/// <returns>the width data</returns>
private double GetBeamWidth()
{
XYZHeightComparer comparer = new XYZHeightComparer();
m_points.Sort(comparer);
Autodesk.Revit.DB.XYZ refPoint = m_points[0];
List<Autodesk.Revit.DB.XYZ > directions = GetRelatedVectors(refPoint);
directions.Sort(comparer);
return GeomUtil.GetLength(directions[0]);
}
/// <summary>
/// Get the height of the beam
/// </summary>
/// <returns>the height data</returns>
private double GetBeamHeight()
{
XYZHeightComparer comparer = new XYZHeightComparer();
m_points.Sort(comparer);
Autodesk.Revit.DB.XYZ refPoint = m_points[0];
List<Autodesk.Revit.DB.XYZ > directions = GetRelatedVectors(refPoint);
directions.Sort(comparer);
return GeomUtil.GetLength(directions[1]);
}
}
}
| |
using Pearl.DataAccessObjects;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class activities : System.Web.UI.Page
{
private IDACManager dac = DACManagerFactory.GetDACManager(ConfigurationManager.ConnectionStrings["DataConnectionString"].ConnectionString, DACManagers.SqlServerDACManager);
int cat_id=0;
int op_id=0;
protected void Page_Load(object sender, EventArgs e)
{
//string des_id = Session["des_id"].ToString();
//GetDestinationbyid(Convert.ToInt32(des_id));
if (!IsPostBack)
{
SearchCustomers(txtContactsSearch2.Text);
rptTours.DataSource = Getalltours();
rptTours.DataBind();
rblCategories.DataSource = GetCategories();
rblCategories.DataTextField = "cat_Title";
rblCategories.DataValueField = "cat_Id";
rblCategories.DataBind();
rblDuration.DataSource = GetDuration();
rblDuration.DataTextField = "Duration";
rblDuration.DataValueField = "dur_id";
rblDuration.DataBind();
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
Get_destinationkeybyname(txtContactsSearch2.Text.Trim());
Session["mon"] = ddlMonth.SelectedItem.Value;
string des = Session["destination_id"].ToString();
string da = "";
if (ddlMonth.SelectedItem.ToString() != "Month of Travel")
{
da = ddlMonth.SelectedItem.ToString();
rptTours.DataSource = GetToursbydestandmonth(des, da);
rptTours.DataBind();
}
//var queryParams = new NameValueCollection()
//{
// { "des", des.Trim() },
// { "Month", da.Trim() }
//};
//string url = "http://localhost:49915/Searchresult.aspx" + ToQueryString(queryParams);
//Response.Redirect(url);
}
public DataTable GetToursbydestandmonth(string des, string mon)
{
SqlParameter[] param = new SqlParameter[]
{
new SqlParameter("Destination_Id",des),
new SqlParameter("Month",mon)
};
DataTable dt = dac.GetDataTable("Get_tours_by_destin_and_month", param);
return dt;
}
public string Get_destinationkeybyname(string dest)
{
SqlParameter[] param = new SqlParameter[] { new SqlParameter("ds_Name", dest) };
IDataReader idr = dac.ExecuteDataReader("Get_destination_id", param);
string desid = "";
if (idr.Read())
{
desid = idr[0].ToString();
}
dac.Connection.Close();
Session["destination_id"] = desid;
return desid;
}
public string ToQueryString(NameValueCollection nvc)
{
StringBuilder sb = new StringBuilder("?");
bool first = true;
foreach (string key in nvc.AllKeys)
{
foreach (string value in nvc.GetValues(key))
{
if (!first)
{
sb.Append("&");
}
sb.AppendFormat("{0}={1}", Uri.EscapeDataString(key), Uri.EscapeDataString(value));
first = false;
}
}
return sb.ToString();
}
public DataTable GetDestination()
{
DataTable dt = dac.GetDataTable("Select_Destination");
return dt;
}
public DataTable GetCategories()
{
DataTable dt = dac.GetDataTable("Select_Categories");
return dt;
}
protected void rblPrice_SelectedIndexChanged(object sender, EventArgs e)
{
if (rblPrice.SelectedValue == "10000 to 30000")
{
int min_p = 10000;
int max_p = 30000;
SqlParameter[] param = new SqlParameter[] { new SqlParameter("minprice", min_p), new SqlParameter("maxprice", max_p) };
DataTable dt = dac.GetDataTable("Get_tour_by_price", param);
rptTours.DataSource = dt;
rptTours.DataBind();
}
else if (rblPrice.SelectedValue == "31000 to 60000")
{
int min_p = 31000;
int max_p = 60000;
SqlParameter[] param = new SqlParameter[] { new SqlParameter("minprice", min_p), new SqlParameter("maxprice", max_p) };
DataTable dt = dac.GetDataTable("Get_tour_by_price", param);
rptTours.DataSource = dt;
rptTours.DataBind();
}
else if (rblPrice.SelectedValue == "61000 to 100000")
{
int min_p = 61000;
int max_p = 100000;
SqlParameter[] param = new SqlParameter[] { new SqlParameter("minprice", min_p), new SqlParameter("maxprice", max_p) };
DataTable dt = dac.GetDataTable("Get_tour_by_price", param);
rptTours.DataSource = dt;
rptTours.DataBind();
}
}
protected void rblDuration_SelectedIndexChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(rblDuration.SelectedValue)< 12)
{
int d = Convert.ToInt32(rblDuration.SelectedValue) - 1;
SqlParameter[] param = new SqlParameter[] { new SqlParameter("Duration_day", d)};
DataTable dt = dac.GetDataTable("Get_tour_by_duration", param);
rptTours.DataSource = dt;
rptTours.DataBind();
}
else
{
SqlParameter[] param = new SqlParameter[] { new SqlParameter("Duration_day", 12) };
DataTable dt = dac.GetDataTable("Get_tour_by_duration", param);
rptTours.DataSource = dt;
rptTours.DataBind();
}
// int star = 5;
// SqlParameter[] param = new SqlParameter[] { new SqlParameter("Rating", star) };
// DataTable dt = dac.GetDataTable("Get_tour_by_rating", param);
// rptTours.DataSource = dt;
// rptTours.DataBind();
//}
//else if (rblRating.SelectedValue == "4")
//{
// int star = 4;
// SqlParameter[] param = new SqlParameter[] { new SqlParameter("Rating", star) };
// DataTable dt = dac.GetDataTable("Get_tour_by_rating", param);
// rptTours.DataSource = dt;
// rptTours.DataBind();
//}
//else if (rblRating.SelectedValue == "3")
//{
// int star = 3;
// SqlParameter[] param = new SqlParameter[] { new SqlParameter("Rating", star) };
// DataTable dt = dac.GetDataTable("Get_tour_by_rating", param);
// rptTours.DataSource = dt;
// rptTours.DataBind();
//}
//else if (rblRating.SelectedValue == "2")
//{
// int star = 2;
// SqlParameter[] param = new SqlParameter[] { new SqlParameter("Rating", star) };
// DataTable dt = dac.GetDataTable("Get_tour_by_rating", param);
// rptTours.DataSource = dt;
// rptTours.DataBind();
//}
//else if (rblRating.SelectedValue == "1")
//{
// int star = 1;
// SqlParameter[] param = new SqlParameter[] { new SqlParameter("Rating", star) };
// DataTable dt = dac.GetDataTable("Get_tour_by_rating", param);
// rptTours.DataSource = dt;
// rptTours.DataBind();
//}
}
protected void rblCategories_SelectedIndexChanged(object sender, EventArgs e)
{
SqlParameter[] param = new SqlParameter[] { new SqlParameter("Category_id", rblCategories.SelectedValue) };
DataTable dt = dac.GetDataTable("Get_tours_by_cat", param);
rptTours.DataSource = dt;
rptTours.DataBind();
}
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchCustomers(string prefixText)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["DataConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select ds_Name from ns_Destinations where " +
"ds_Name like @SearchText + '%'";
cmd.Parameters.AddWithValue("@SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> customers = new List<string>();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(sdr["ds_Name"].ToString());
}
}
conn.Close();
return customers;
}
}
}
public void GetDestinationbyid(int d_id)
{
SqlParameter[] param = new SqlParameter[] { new SqlParameter("Id",d_id) };
IDataReader idr = dac.ExecuteDataReader("GetDestinationbyid",param);
if (idr.Read())
{
banheader.Style.Add("background-image", "url(../"+idr["Profile_Image"].ToString()+")");
lbldTitle.Text = idr["ds_Name"].ToString();
// lblContent.InnerText = idr["ds_Content"].ToString();
}
dac.Connection.Close();
}
protected void rptTours_ItemCommand(object source, RepeaterCommandEventArgs e)
{
Session["tour_id"] = e.CommandArgument;
SqlParameter[] param = new SqlParameter[]
{
new SqlParameter("Id", Session["tour_id"])
};
DataTable dt = dac.GetDataTable("Select_event_by_id", param);
cat_id = Convert.ToInt32(dt.Rows[0]["Category_id"]);
op_id = Convert.ToInt32(dt.Rows[0]["o_id"]);
dac.Connection.Close();
Response.Redirect("tour.aspx?id=" + Session["tour_id"] + "&cat_id=" + cat_id + "&op_id=" + op_id);
}
public DataTable Gettoursbydestination(string destination)
{
SqlParameter[] param = new SqlParameter[]
{
new SqlParameter("Destination_Id", destination)
};
DataTable dt = dac.GetDataTable("Get_Data_by_destination", param);
dac.Connection.Close();
return dt;
}
public DataTable Getalltours()
{
DataTable dt = dac.GetDataTable("Get_alltours");
return dt;
}
public DataTable GetDuration()
{
DataTable dt = dac.GetDataTable("Get_duration_fil");
return dt;
}
}
| |
/*
* Copyright (c) 2005 Mike Bridge <[email protected]>
*
* Permission is hereby granted, free of charge, to any
* person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the
* Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice
* shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
* ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
* SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using DotNetOpenMail.SmtpAuth;
//using log4net;
namespace DotNetOpenMail
{
/// <summary>
/// A proxy to access an SMTP server. This drives
/// the protocol interaction.
/// </summary>
public class SmtpProxy : TcpClient, ISmtpProxy
{
//private static readonly ILog log = LogManager.GetLogger(typeof(SmtpProxy));
private SmtpServer _smtpserver=null;
internal static readonly String ENDOFLINE="\r\n";
private bool _isConnected=false;
private bool _captureConversation=false;
private static readonly String SERVER_LOG_PROMPT="READ> ";
private static readonly String CLIENT_LOG_PROMPT="SENT> ";
//private StringBuilder _conversation=new StringBuilder();
//private IPEndPoint _iEndPoint=null;
/*
#region SmtpProxy
private SmtpProxy(System.Net.IPAddress ipaddress, int portno)
{
_iendpoint = new IPEndPoint (ipaddress, portno);
}
#endregion
*/
#region SmtpProxy
private SmtpProxy(SmtpServer smtpserver)
{
_smtpserver=smtpserver;
}
#endregion
#region GetInstance
/// <summary>
/// Get an instance of the SMTP Proxy
/// </summary>
/// <param name="smtpserver"></param>
/// <returns></returns>
public static SmtpProxy GetInstance(SmtpServer smtpserver)
{
return new SmtpProxy(smtpserver);
}
#endregion
#region Open
/// <summary>
/// Connect to the server and return the initial
/// welcome string. Throw a MailException if we
/// can't connect.
/// </summary>
/// <returns></returns>
public SmtpResponse Open()
{
this.ReceiveTimeout=_smtpserver.ServerTimeout;
IPEndPoint ipendpoint=_smtpserver.GetIPEndPoint();
try
{
Connect(ipendpoint);
}
catch (Exception ex)
{
//throw new MailException("Could not connect to "+ipendpoint+":"+ipendpoint.Port, ex);
throw new MailException("Could not connect to "+ipendpoint, ex);
}
_isConnected=true;
return ReadSmtpResponse();
}
#endregion
#region Helo
/// <summary>
/// Send the HELO string.
/// Throw a MailException if we can't connect.
/// </summary>
/// <returns>the SMTP response</returns>
public SmtpResponse Helo(String localHostName)
{
if (!_isConnected)
{
throw new MailException("The connection is closed.");
}
String message = "HELO "+localHostName+SmtpProxy.ENDOFLINE;
//LogDebug("SENDING: "+message);
Write(message);
return ReadSmtpResponse();
}
#endregion
#region Ehlo
/// <summary>
/// Send the EHLO string.
/// Throw a MailException if we can't connect.
/// </summary>
/// <returns>the SMTP response</returns>
public EhloSmtpResponse Ehlo(String localHostName)
{
if (!_isConnected)
{
throw new MailException("The connection is closed.");
}
String message = "EHLO "+localHostName+SmtpProxy.ENDOFLINE;
//LogDebug("SENDING: "+message);
Write(message);
return ReadEhloSmtpResponse();
}
#endregion
#region MailFrom
/// <summary>
/// Send the MAIL FROM command
/// Throw a MailException if we can't connect.
/// </summary>
/// <param name="mailfrom">The Envelope-From address</param>
/// <returns>the SMTP response</returns>
public SmtpResponse MailFrom(EmailAddress mailfrom)
{
if (!_isConnected)
{
throw new MailException("The connection is closed.");
}
String message = "MAIL FROM: <"+mailfrom.Email+">"+SmtpProxy.ENDOFLINE;
Write(message);
return ReadSmtpResponse();
}
#endregion
#region RcptTo
/// <summary>
/// Send the MAIL FROM command
/// Throw a MailException if we can't connect.
/// </summary>
/// <param name="rcpttoaddress">A recipient's address</param>
/// <returns>the SMTP response</returns>
public SmtpResponse RcptTo(EmailAddress rcpttoaddress)
{
if (!_isConnected)
{
throw new MailException("The connection is closed.");
}
String message= "RCPT TO: <"+rcpttoaddress.Email+">"+SmtpProxy.ENDOFLINE;
//LogDebug("SENDING: "+message);
//OnLogWriteSmtp
Write(message);
return ReadSmtpResponse();
}
#endregion
#region Data
/// <summary>
/// Send the DATA string (without the data)
/// Throw a MailException if we can't connect.
/// </summary>
/// <returns>the SMTP response</returns>
public SmtpResponse Data()
{
if (!_isConnected)
{
throw new MailException("The connection is closed.");
}
String message = "DATA"+SmtpProxy.ENDOFLINE;
//LogDebug("SENDING: "+message);
Write(message);
return ReadSmtpResponse();
}
#endregion
#region WriteData
/// <summary>
/// Send the message content string
/// Throw a MailException if we can't
/// connect.
/// </summary>
/// <returns>the SMTP response</returns>
public SmtpResponse WriteData(String message)
{
if (!_isConnected)
{
throw new MailException("The connection is closed.");
}
StringReader reader=new StringReader(message);
String line=null;
while ((line=reader.ReadLine())!=null)
{
// checking for dot at the beginning of the
// line (RFC821 sec. 4.5.2)
if (line.Length > 0 && line[0]=='.')
{
Write("."+line+SmtpProxy.ENDOFLINE);
}
else
{
Write(line+SmtpProxy.ENDOFLINE);
}
}
Write(SmtpProxy.ENDOFLINE+"."+SmtpProxy.ENDOFLINE);
return ReadSmtpResponse();
}
#endregion
#region ReadSmtpResponse
private SmtpResponse ReadSmtpResponse()
{
String response=ReadResponse();
if (response.Length < 3)
{
throw new MailException("Invalid response from server: \""+response+"\"");
}
String responseCodeStr=response.Substring(0, 3);
String responseMessage="";
if (response.Length > 4)
{
responseMessage=response.Substring(4);
}
try
{
int responseCode=Convert.ToInt32(responseCodeStr);
return new SmtpResponse(responseCode, responseMessage);
}
catch
{
throw new MailException("Could not understand response from server: "+response);
}
}
#endregion
#region ReadEhloSmtpResponse
/// <summary>
/// Parse the response from the EHLO into an
/// EhloSmtpResponse. Returns 250 "OK" if successful.
/// </summary>
/// <returns></returns>
private EhloSmtpResponse ReadEhloSmtpResponse()
{
//log.Debug("READ THE RESPONSE");
EhloSmtpResponse ehloResponse=new EhloSmtpResponse();
String multiLineResponse=ReadResponse();
StringReader sr=new StringReader(multiLineResponse);
String line=null;
//log.Debug("READING...");
while ((line=sr.ReadLine()) !=null)
{
try
{
String responseMessage=String.Empty;
if (line.Length > 4)
{
responseMessage=line.Substring(4).Trim();
}
//log.Debug("Reading "+line);
int responseCode=Convert.ToInt32(line.Substring(0, 3));
if (responseCode==250)
{
if (responseMessage.ToLower().IndexOf("auth")==0)
{
// parse the auth types from the response
if (responseMessage.Length > 4)
{
// RFC 2554 SMTP Authentication:
// (3) The AUTH EHLO keyword contains as a parameter a space separated
// list of the names of supported SASL mechanisms.
foreach (String authtype in responseMessage.Substring(5).Split(' '))
{
ehloResponse.AddAvailableAuthType(authtype.ToLower());
}
}
// return new SmtpResponse(responseCode, responseMessage);
}
}
else
{
ehloResponse.ResponseCode=responseCode;
ehloResponse.Message=responseMessage;
return ehloResponse;
}
}
catch
{
throw new MailException("Could not understand response from server: "+multiLineResponse);
}
}
ehloResponse.ResponseCode=250;
ehloResponse.Message="OK";
return ehloResponse;
}
#endregion
#region Auth
/// <summary>
/// Send the AUTH command
/// Throw a MailException if we can't connect.
/// </summary>
/// <returns>the SMTP response</returns>
public SmtpResponse Auth(String authtype)
{
if (!_isConnected)
{
throw new MailException("The connection is closed.");
}
Write("AUTH "+authtype+SmtpProxy.ENDOFLINE);
return ReadSmtpResponse();
}
#endregion
#region SendString
/// <summary>
/// Send any old string to the proxy
/// </summary>
/// <returns>the SMTP response</returns>
public SmtpResponse SendString(String str)
{
if (!_isConnected)
{
throw new MailException("The connection is closed.");
}
Write(str+SmtpProxy.ENDOFLINE);
return ReadSmtpResponse();
}
#endregion
#region Write
/// <summary>
/// Write a string to the current connection.
/// </summary>
/// <param name="message"></param>
private void Write(string message)
{
try
{
//log.Debug(message);
_smtpserver.OnLogWriteSmtp(this, message);
if (_captureConversation)
{
_smtpserver.AppendConversation(SmtpProxy.CLIENT_LOG_PROMPT+message);
}
System.Text.ASCIIEncoding en = new System.Text.ASCIIEncoding() ;
byte[] WriteBuffer = new byte[1024] ;
WriteBuffer = en.GetBytes(message) ;
NetworkStream stream = GetStream() ;
if (!stream.CanWrite)
{
throw new MailException("Stream could not be opened for writing.");
}
stream.Write(WriteBuffer,0,WriteBuffer.Length);
}
catch (Exception ex)
{
//LogError(ex.Message);
throw new MailException("Error while sending data to the server: "+ex.Message, ex);
}
}
#endregion
#region Quit
/// <summary>
/// Send the QUIT command
/// Throw a MailException if we can't connect.
/// </summary>
/// <returns>the SMTP response</returns>
public SmtpResponse Quit()
{
if (!_isConnected)
{
throw new MailException("The connection is closed.");
}
Write("QUIT"+SmtpProxy.ENDOFLINE);
return ReadSmtpResponse();
}
#endregion
#region ReadResponse
private string ReadResponse()
{
try
{
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"\d{3}\s.+");
string response = String.Empty;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] serverbuff = new Byte[1024];
NetworkStream stream = GetStream();
if (!stream.CanRead)
{
throw new MailException("Stream could not be read.");
}
int count = 0;
// read until last response has been received
// (indicated by whitespace after the numerical response code)
do
{
int LoopTimeout = 0;
if (stream.DataAvailable)
{
count = stream.Read(serverbuff, 0, serverbuff.Length);
response = String.Concat(response, enc.GetString(serverbuff, 0, count));
}
if ((LoopTimeout += 100) > this._smtpserver.ServerTimeout)
{
throw new MailException("Multiline server response timed out");
}
Thread.Sleep(100);
}
while(! regex.IsMatch(response));
_smtpserver.OnLogReceiveSmtp(this, response);
if (_captureConversation)
{
this._smtpserver.AppendConversation(SmtpProxy.SERVER_LOG_PROMPT+response);
}
return response;
}
catch (Exception ex)
{
//LogError(ex.Message);
throw new MailException("Error while receiving data from server: "+ex.Message, ex);
}
}
#endregion
#region CaptureSmtpConversation
/// <summary>
/// Set this to "true" if you want to capture the SMTP negotiation.
/// Once the conversation has finished, use "GetConversation" to
/// view it.
/// </summary>
public bool CaptureSmtpConversation
{
get {return this._captureConversation;}
set {this._captureConversation=value;}
}
#endregion
/*
#region LogError
private void LogError(String message)
{
//System.Console.Error.WriteLine(message);
//log.Error(message);
}
#endregion
#region LogDebug
private void LogDebug(String message)
{
//System.Console.Out.WriteLine(message);
//log.Debug(message);
}
#endregion
*/
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Data.dll
// Description: The data access libraries for the DotSpatial project.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 3/8/2008 7:36:02 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
namespace DotSpatial.Data
{
/// <summary>
/// A list that also includes several events during its existing activities.
/// List is fussy about inheritance, unfortunately, so this wraps a list
/// and then makes this class much more inheritable
/// </summary>
public class ChangeEventList<T> : CopyList<T>, IChangeEventList<T> where T : class, IChangeItem
{
#region Events
/// <summary>
/// This event is for when it is necessary to do something if any of the internal
/// members changes. It will also forward the original item calling the message.
/// </summary>
public event EventHandler ItemChanged;
/// <summary>
/// Occurs when this list should be removed from its container
/// </summary>
public event EventHandler RemoveItem;
#endregion
#region variables
private bool _hasChanged;
private int _suspension;
#endregion
#region Constructors
#endregion
#region Methods
#region Add
/// <summary>
/// Adds the elements of the specified collection to the end of the System.Collections.Generic.List<T>
/// </summary>
/// <param name="collection">collection: The collection whose elements should be added to the end of the
/// System.Collections.Generic.List<T>. The collection itself cannot be null, but it can contain elements that are null,
/// if type T is a reference type.</param>
/// <exception cref="System.ApplicationException">Unable to add while the ReadOnly property is set to true.</exception>
public virtual void AddRange(IEnumerable<T> collection)
{
SuspendEvents();
foreach (T item in collection)
{
Add(item);
}
ResumeEvents();
}
#endregion
/// <summary>
/// Resumes event sending and fires a ListChanged event if any changes have taken place.
/// This will not track all the individual changes that may have fired in the meantime.
/// </summary>
public void ResumeEvents()
{
_suspension--;
if (_suspension == 0)
{
OnResumeEvents();
if (_hasChanged)
{
OnListChanged();
}
}
if (_suspension < 0) _suspension = 0;
}
/// <summary>
/// Temporarilly suspends notice events, allowing a large number of changes.
/// </summary>
public void SuspendEvents()
{
if (_suspension == 0) _hasChanged = false;
_suspension++;
}
/// <summary>
/// An overriding event handler so that we can signfiy the list has changed
/// when the inner list has been set to a new list.
/// </summary>
protected override void OnInnerListSet()
{
OnItemChanged(this);
}
/// <summary>
/// Overrides the normal clear situation so that we only update after all the members are cleared.
/// </summary>
protected override void OnClear()
{
SuspendEvents();
base.OnClear();
ResumeEvents();
}
/// <summary>
/// Occurs during the copy process and overrides the base behavior so that events are suspended.
/// </summary>
/// <param name="copy"></param>
protected override void OnCopy(CopyList<T> copy)
{
ChangeEventList<T> myCopy = copy as ChangeEventList<T>;
if (myCopy != null)
{
RemoveHandlers(myCopy);
myCopy.SuspendEvents();
}
base.OnCopy(copy);
if (myCopy != null) myCopy.ResumeEvents();
}
private static void RemoveHandlers(ChangeEventList<T> myCopy)
{
if (myCopy.ItemChanged != null)
{
foreach (var handler in myCopy.ItemChanged.GetInvocationList())
{
myCopy.ItemChanged -= (EventHandler)handler;
}
}
if (myCopy.RemoveItem != null)
{
foreach (var handler in myCopy.RemoveItem.GetInvocationList())
{
myCopy.RemoveItem -= (EventHandler)handler;
}
}
}
/// <summary>
/// Occurs when ResumeEvents has been called enough times so that events are re-enabled.
/// </summary>
protected virtual void OnResumeEvents()
{
}
#region Reverse
/// <summary>
/// Reverses the order of the elements in the specified range.
/// </summary>
/// <param name="index">The zero-based starting index of the range to reverse.</param>
/// <param name="count">The number of elements in the range to reverse.</param>
/// <exception cref="System.ArgumentException">index and count do not denote a valid range of elements in the EventList<T>.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">index is less than 0.-or-count is less than 0.</exception>
/// <exception cref="System.ApplicationException">Unable to reverse while the ReadOnly property is set to true.</exception>
public virtual void Reverse(int index, int count)
{
InnerList.Reverse(index, count);
OnListChanged();
}
/// <summary>
/// Reverses the order of the elements in the entire EventList<T>.
/// </summary>
/// <exception cref="System.ApplicationException">Unable to reverse while the ReadOnly property is set to true.</exception>
public virtual void Reverse()
{
InnerList.Reverse();
OnListChanged();
}
#endregion
#region Insert
/// <summary>
/// Inserts the elements of a collection into the EventList<T> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which the new elements should be inserted.</param>
/// <param name="collection">The collection whose elements should be inserted into the EventList<T>. The collection itself cannot be null, but it can contain elements that are null, if type T is a reference type.</param>
/// <exception cref="System.ArgumentOutOfRangeException">index is less than 0.-or-index is greater than EventList<T>.Count.</exception>
/// <exception cref="System.ArgumentNullException">collection is null.</exception>
/// <exception cref="System.ApplicationException">Unable to insert while the ReadOnly property is set to true.</exception>
public virtual void InsertRange(int index, IEnumerable<T> collection)
{
int c = index;
SuspendEvents();
foreach (T item in collection)
{
Include(item);
InnerList.Insert(c, item);
c++;
}
ResumeEvents();
}
#endregion
#region Remove
/// <summary>
/// Removes a range of elements from the EventList<T>.
/// </summary>
/// <param name="index">The zero-based starting index of the range of elements to remove.</param>
/// <param name="count">The number of elements to remove.</param>
/// <exception cref="System.ArgumentOutOfRangeException">index is less than 0.-or-count is less than 0.</exception>
/// <exception cref="System.ArgumentException">index and count do not denote a valid range of elements in the EventList<T>.</exception>
/// <exception cref="System.ApplicationException">Unable to remove while the ReadOnly property is set to true.</exception>
public virtual void RemoveRange(int index, int count)
{
T[] temp = new T[count];
InnerList.CopyTo(index, temp, 0, count);
InnerList.RemoveRange(index, count);
SuspendEvents();
foreach (T item in temp)
{
Exclude(item);
}
ResumeEvents();
}
#endregion
#region BinarySearch
/// <summary>
/// Searches the entire sorted System.Collections.Generic.List<T> for an element using the default comparer and returns the zero-based index of the element.
/// </summary>
/// <param name="item">The object to locate. The value can be null for reference types.</param>
/// <returns>The zero-based index of item in the sorted System.Collections.Generic.List<T>, if item is found; otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of System.Collections.Generic.List<T>.Count.</returns>
/// <exception cref="System.InvalidOperationException">The default comparer System.Collections.Generic.Comparer<T>.Default cannot find an implementation of the System.IComparable<T> generic interface or the System.IComparable interface for type T.</exception>
public virtual int BinarySearch(T item)
{
return InnerList.BinarySearch(item);
}
#endregion
#endregion
#region Properties
/// <summary>
/// Gets whether or not the list is currently suspended
/// </summary>
public bool EventsSuspended
{
get
{
return (_suspension > 0);
}
}
#endregion
#region Event Handlers
/// <summary>
/// This is a notification that characteristics of one of the members of the list may have changed,
/// requiring a refresh, but may not involve a change to the the list itself
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ItemItemChanged(object sender, EventArgs e)
{
OnItemChanged(sender);
}
/// <summary>
/// Occurs when the item is changed. If this list is not suspended, it will forward the change event
/// on. Otherwise, it will ensure that when resume events is called that the on change method
/// is fired at that time.
/// </summary>
/// <param name="sender"></param>
protected virtual void OnItemChanged(object sender)
{
if (EventsSuspended)
{
_hasChanged = true;
}
else
{
if (ItemChanged != null) ItemChanged(sender, EventArgs.Empty);
}
}
private void ItemRemoveItem(object sender, EventArgs e)
{
Remove((T)sender);
OnListChanged();
}
#endregion
#region Protected Methods
/// <summary>
/// Fires the ListChanged Event
/// </summary>
protected virtual void OnListChanged()
{
if (EventsSuspended == false)
{
if (ItemChanged != null)
{
// activate this remarked code to test if the handlers are getting copied somewhere.
//int count = ItemChanged.GetInvocationList().Length;
//if (count > 1) Debug.WriteLine(this + " has " + count + " item changed handlers.");
ItemChanged(this, EventArgs.Empty);
}
}
else
{
_hasChanged = true;
}
}
/// <summary>
/// This is either a layer collection or a colorbreak collection, and so
/// this won't be called by us, but someone might want to override this for their own reasons.
/// </summary>
protected virtual void OnRemoveItem()
{
if (RemoveItem != null) RemoveItem(this, EventArgs.Empty);
}
#endregion
#region Protected Methods
/// <summary>
/// Occurs when wiring events on a new item
/// </summary>
/// <param name="item"></param>
protected override void OnInclude(T item)
{
item.ItemChanged += ItemItemChanged;
item.RemoveItem += ItemRemoveItem;
OnListChanged();
}
/// <summary>
/// Occurs when unwiring events on new items
/// </summary>
/// <param name="item"></param>
protected override void OnExclude(T item)
{
item.ItemChanged -= ItemItemChanged;
item.RemoveItem -= ItemRemoveItem;
OnListChanged();
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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.Net;
using Aurora.Framework;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
namespace OpenSim.Services.Interfaces
{
public interface IGridService
{
IGridService InnerService { get; }
/// <summary>
/// The max size a region can be (meters)
/// </summary>
int GetMaxRegionSize();
/// <summary>
/// The size (in meters) of how far neighbors will be found
/// </summary>
int GetRegionViewSize();
/// <summary>
/// Register a region with the grid service.
/// </summary>
/// <param name="regionInfos"> </param>
/// <param name="oldSessionID"></param>
/// <returns></returns>
/// <exception cref="System.Exception">Thrown if region registration failed</exception>
RegisterRegion RegisterRegion(GridRegion regionInfos, UUID oldSessionID);
/// <summary>
/// Deregister a region with the grid service.
/// </summary>
/// <param name="region"></param>
/// <returns></returns>
/// <exception cref="System.Exception">Thrown if region deregistration failed</exception>
bool DeregisterRegion(GridRegion region);
/// <summary>
/// Get a specific region by UUID in the given scope
/// </summary>
/// <param name="scopeID"></param>
/// <param name="regionID"></param>
/// <returns></returns>
GridRegion GetRegionByUUID(UUID scopeID, UUID regionID);
/// <summary>
/// Get the region at the given position (in meters)
/// </summary>
/// <param name="scopeID"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
GridRegion GetRegionByPosition(UUID scopeID, int x, int y);
/// <summary>
/// Get the first returning region by name in the given scope
/// </summary>
/// <param name="scopeID"></param>
/// <param name="regionName"></param>
/// <returns></returns>
GridRegion GetRegionByName(UUID scopeID, string regionName);
/// <summary>
/// Get information about regions starting with the provided name.
/// </summary>
/// <param name="scopeID"></param>
/// <param name="name">
/// The name to match against.
/// </param>
/// <param name="maxNumber">
/// The maximum number of results to return.
/// </param>
/// <returns>
/// A list of <see cref="RegionInfo"/>s of regions with matching name. If the
/// grid-server couldn't be contacted or returned an error, return null.
/// </returns>
List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber);
/// <summary>
/// Get all regions within the range of (xmin - xmax, ymin - ymax) (in meters)
/// </summary>
/// <param name="scopeID"></param>
/// <param name="xmin"></param>
/// <param name="xmax"></param>
/// <param name="ymin"></param>
/// <param name="ymax"></param>
/// <returns></returns>
List<GridRegion> GetRegionRange (UUID scopeID, int xmin, int xmax, int ymin, int ymax);
/// <summary>
/// Get all regions within the range of specified center.
/// </summary>
/// <param name="scopeID"></param>
/// <param name="centerX"></param>
/// <param name="centerY"></param>
/// <param name="squareRangeFromCenterInMeters"></param>
/// <returns></returns>
List<GridRegion> GetRegionRange(UUID scopeID, float centerX, float centerY, uint squareRangeFromCenterInMeters);
/// <summary>
/// Get the neighbors of the given region
/// </summary>
/// <param name="region"></param>
/// <returns></returns>
List<GridRegion> GetNeighbors (GridRegion region);
/// <summary>
/// Get any default regions that have been set for users that are logging in that don't have a region to log into
/// </summary>
/// <param name="scopeID"></param>
/// <returns></returns>
List<GridRegion> GetDefaultRegions(UUID scopeID);
/// <summary>
/// If all the default regions are down, find any fallback regions that have been set near x,y
/// </summary>
/// <param name="scopeID"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y);
/// <summary>
/// If there still are no regions after fallbacks have been checked, find any region near x,y
/// </summary>
/// <param name="scopeID"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
List<GridRegion> GetSafeRegions(UUID scopeID, int x, int y);
/// <summary>
/// Get the current flags of the given region
/// </summary>
/// <param name="scopeID"></param>
/// <param name="regionID"></param>
/// <returns></returns>
int GetRegionFlags(UUID scopeID, UUID regionID);
/// <summary>
/// Update the map of the given region if the sessionID is correct
/// </summary>
/// <param name="region"></param>
/// <returns></returns>
string UpdateMap(GridRegion region);
/// <summary>
/// Get all map items of the given type for the given region
/// </summary>
/// <param name="regionHandle"></param>
/// <param name="gridItemType"></param>
/// <returns></returns>
multipleMapItemReply GetMapItems (ulong regionHandle, GridItemType gridItemType);
/// <summary>
/// The region (RegionID) has been determined to be unsafe, don't let agents log into it if no other region is found
/// </summary>
/// <param name="RegionID"></param>
void SetRegionUnsafe (UUID RegionID);
/// <summary>
/// The region (RegionID) has been determined to be safe, allow agents to log into it again
/// </summary>
/// <param name="RegionID"></param>
void SetRegionSafe (UUID RegionID);
/// <summary>
/// Verify the given SessionID for the given region
/// </summary>
/// <param name="r"></param>
/// <param name="SessionID"></param>
/// <returns></returns>
bool VerifyRegionSessionID(GridRegion r, UUID SessionID);
void Configure (Nini.Config.IConfigSource config, IRegistryCore registry);
void Start (Nini.Config.IConfigSource config, IRegistryCore registry);
void FinishedStartup ();
}
public class RegisterRegion : IDataTransferable
{
public string Error;
public List<GridRegion> Neighbors = new List<GridRegion>();
public UUID SessionID;
public int RegionFlags = 0;
public OSDMap Urls = new OSDMap();
public override OSDMap ToOSD()
{
OSDMap map = new OSDMap();
map["Error"] = Error;
map["Neighbors"] = new OSDArray(Neighbors.ConvertAll<OSD>((region) => region.ToOSD()));
map["SessionID"] = SessionID;
map["RegionFlags"] = RegionFlags;
map["Urls"] = Urls;
return map;
}
public override void FromOSD(OSDMap map)
{
Error = map["Error"];
OSDArray n = (OSDArray)map["Neighbors"];
Neighbors = n.ConvertAll<GridRegion>((osd) => { GridRegion r = new GridRegion(); r.FromOSD((OSDMap)osd); return r; });
SessionID = map["SessionID"];
RegionFlags = map["RegionFlags"];
Urls = (OSDMap)map["Urls"];
}
}
public class GridRegion : IDataTransferable
{
#region GridRegion
/// <summary>
/// The port by which http communication occurs with the region
/// </summary>
public uint HttpPort
{
get { return m_httpPort; }
set { m_httpPort = value; }
}
protected uint m_httpPort;
/// <summary>
/// A well-formed URI for the host region server (namely "http://" + ExternalHostName + : + HttpPort)
/// </summary>
public string ServerURI
{
get
{
if(string.IsNullOrEmpty(m_serverURI))
return "http://" + ExternalHostName + ":" + HttpPort;
return m_serverURI;
}
set { m_serverURI = value; }
}
protected string m_serverURI;
public string RegionName
{
get { return m_regionName; }
set { m_regionName = value; }
}
protected string m_regionName = String.Empty;
public string RegionType
{
get { return m_regionType; }
set { m_regionType = value; }
}
protected string m_regionType = String.Empty;
public int RegionLocX
{
get { return m_regionLocX; }
set { m_regionLocX = value; }
}
protected int m_regionLocX;
public int RegionLocY
{
get { return m_regionLocY; }
set { m_regionLocY = value; }
}
protected int m_regionLocY;
public int RegionLocZ
{
get { return m_regionLocZ; }
set { m_regionLocZ = value; }
}
protected int m_regionLocZ;
protected UUID m_estateOwner;
public UUID EstateOwner
{
get { return m_estateOwner; }
set { m_estateOwner = value; }
}
public int RegionSizeX
{
get { return m_RegionSizeX; }
set { m_RegionSizeX = value; }
}
public int RegionSizeY
{
get { return m_RegionSizeY; }
set { m_RegionSizeY = value; }
}
public int RegionSizeZ
{
get { return m_RegionSizeZ; }
}
public int Flags { get; set; }
public UUID SessionID
{
get { return m_SessionID; }
set { m_SessionID = value; }
}
private int m_RegionSizeX = 256;
private int m_RegionSizeY = 256;
private int m_RegionSizeZ = 256;
public UUID RegionID = UUID.Zero;
public UUID ScopeID = UUID.Zero;
private UUID m_SessionID = UUID.Zero;
public UUID TerrainImage = UUID.Zero;
public UUID TerrainMapImage = UUID.Zero;
public UUID ParcelMapImage = UUID.Zero;
public byte Access;
public string AuthToken = string.Empty;
private IPEndPoint m_remoteEndPoint = null;
protected string m_externalHostName;
protected IPEndPoint m_internalEndPoint;
public int LastSeen = 0;
protected OSDMap m_genericMap = new OSDMap();
public OSDMap GenericMap
{
get { return m_genericMap; }
set { m_genericMap = value; }
}
public bool IsOnline
{
get { return (Flags & (int)Aurora.Framework.RegionFlags.RegionOnline) == 1; }
set
{
if (value)
Flags |= (int)Aurora.Framework.RegionFlags.RegionOnline;
else
Flags &= (int)Aurora.Framework.RegionFlags.RegionOnline;
}
}
public GridRegion()
{
Flags = 0;
}
public GridRegion(RegionInfo ConvertFrom)
{
Flags = 0;
m_regionName = ConvertFrom.RegionName;
m_regionType = ConvertFrom.RegionType;
m_regionLocX = ConvertFrom.RegionLocX;
m_regionLocY = ConvertFrom.RegionLocY;
m_regionLocZ = ConvertFrom.RegionLocZ;
m_internalEndPoint = ConvertFrom.InternalEndPoint;
m_externalHostName = MainServer.Instance.HostName;
m_externalHostName = m_externalHostName.Replace("https://", "");
m_externalHostName = m_externalHostName.Replace("http://", "");
m_httpPort = MainServer.Instance.Port;
RegionID = ConvertFrom.RegionID;
ServerURI = MainServer.Instance.ServerURI;
TerrainImage = ConvertFrom.RegionSettings.TerrainImageID;
TerrainMapImage = ConvertFrom.RegionSettings.TerrainMapImageID;
ParcelMapImage = ConvertFrom.RegionSettings.ParcelMapImageID;
Access = ConvertFrom.AccessLevel;
if(ConvertFrom.EstateSettings != null)
EstateOwner = ConvertFrom.EstateSettings.EstateOwner;
m_RegionSizeX = ConvertFrom.RegionSizeX;
m_RegionSizeY = ConvertFrom.RegionSizeY;
m_RegionSizeZ = ConvertFrom.RegionSizeZ;
ScopeID = ConvertFrom.ScopeID;
SessionID = ConvertFrom.GridSecureSessionID;
Flags |= (int)Aurora.Framework.RegionFlags.RegionOnline;
}
#region Definition of equality
/// <summary>
/// Define equality as two regions having the same, non-zero UUID.
/// </summary>
public bool Equals(GridRegion region)
{
if (region == null)
return false;
// Return true if the non-zero UUIDs are equal:
return (RegionID != UUID.Zero) && RegionID.Equals(region.RegionID);
}
public override bool Equals(Object obj)
{
if (obj == null)
return false;
return Equals(obj as GridRegion);
}
public override int GetHashCode()
{
return RegionID.GetHashCode() ^ TerrainImage.GetHashCode();
}
#endregion
/// <value>
/// This accessor can throw all the exceptions that Dns.GetHostAddresses can throw.
///
/// XXX Isn't this really doing too much to be a simple getter, rather than an explict method?
/// </value>
public IPEndPoint ExternalEndPoint
{
get
{
if (m_remoteEndPoint == null && m_externalHostName != null && m_internalEndPoint != null)
m_remoteEndPoint = NetworkUtils.ResolveEndPoint(m_externalHostName, m_internalEndPoint.Port);
return m_remoteEndPoint;
}
}
public string ExternalHostName
{
get { return m_externalHostName; }
set { m_externalHostName = value; }
}
public IPEndPoint InternalEndPoint
{
get { return m_internalEndPoint; }
set { m_internalEndPoint = value; }
}
public ulong RegionHandle
{
get { return Util.IntsToUlong(RegionLocX, RegionLocY); }
set
{
Util.UlongToInts(value, out m_regionLocX, out m_regionLocY);
}
}
#endregion
#region IDataTransferable
public override OSDMap ToOSD()
{
OSDMap map = new OSDMap();
map["uuid"] = RegionID;
map["locX"] = RegionLocX;
map["locY"] = RegionLocY;
map["locZ"] = RegionLocZ;
map["regionName"] = RegionName;
map["regionType"] = RegionType;
map["serverIP"] = ExternalHostName; //ExternalEndPoint.Address.ToString();
map["serverHttpPort"] = HttpPort;
map["serverURI"] = ServerURI;
if(InternalEndPoint != null)
map["serverPort"] = InternalEndPoint.Port;
map["regionMapTexture"] = TerrainImage;
map["regionTerrainTexture"] = TerrainMapImage;
map["ParcelMapImage"] = ParcelMapImage;
map["access"] = (int)Access;
map["owner_uuid"] = EstateOwner;
map["AuthToken"] = AuthToken;
map["sizeX"] = RegionSizeX;
map["sizeY"] = RegionSizeY;
map["sizeZ"] = RegionSizeZ;
map["LastSeen"] = LastSeen;
map["SessionID"] = SessionID;
map["Flags"] = Flags;
map["GenericMap"] = GenericMap;
map["EstateOwner"] = EstateOwner;
// We send it along too so that it doesn't need resolved on the other end
if (ExternalEndPoint != null)
{
map["remoteEndPointIP"] = ExternalEndPoint.Address.GetAddressBytes ();
map["remoteEndPointPort"] = ExternalEndPoint.Port;
}
return map;
}
public override void FromOSD(OSDMap map)
{
if (map.ContainsKey("uuid"))
RegionID = map["uuid"].AsUUID();
if (map.ContainsKey("locX"))
RegionLocX = map["locX"].AsInteger();
if (map.ContainsKey("locY"))
RegionLocY = map["locY"].AsInteger();
if (map.ContainsKey("locZ"))
RegionLocZ = map["locZ"].AsInteger();
if (map.ContainsKey("regionName"))
RegionName = map["regionName"].AsString();
if (map.ContainsKey("regionType"))
RegionType = map["regionType"].AsString();
ExternalHostName = map.ContainsKey("serverIP") ? map["serverIP"].AsString() : "127.0.0.1";
if (map.ContainsKey("serverPort"))
{
Int32 port = map["serverPort"].AsInteger();
InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), port);
}
if (map.ContainsKey("serverHttpPort"))
{
UInt32 port = map["serverHttpPort"].AsUInteger();
HttpPort = port;
}
if (map.ContainsKey("serverURI"))
ServerURI = map["serverURI"];
if (map.ContainsKey("regionMapTexture"))
TerrainImage = map["regionMapTexture"].AsUUID();
if (map.ContainsKey("regionTerrainTexture"))
TerrainMapImage = map["regionTerrainTexture"].AsUUID();
if (map.ContainsKey("ParcelMapImage"))
ParcelMapImage = map["ParcelMapImage"].AsUUID();
if (map.ContainsKey("access"))
Access = (byte)map["access"].AsInteger();
if (map.ContainsKey("owner_uuid"))
EstateOwner = map["owner_uuid"].AsUUID();
if (map.ContainsKey("EstateOwner"))
EstateOwner = map["EstateOwner"].AsUUID();
if (map.ContainsKey("AuthToken"))
AuthToken = map["AuthToken"].AsString();
if (map.ContainsKey("sizeX"))
m_RegionSizeX = map["sizeX"].AsInteger();
if (map.ContainsKey("sizeY"))
m_RegionSizeY = map["sizeY"].AsInteger();
if (map.ContainsKey("sizeZ"))
m_RegionSizeZ = map["sizeZ"].AsInteger();
if (map.ContainsKey("LastSeen"))
LastSeen = map["LastSeen"].AsInteger();
if (map.ContainsKey("SessionID"))
SessionID = map["SessionID"].AsUUID();
if (map.ContainsKey("Flags"))
Flags = map["Flags"].AsInteger();
if (map.ContainsKey("GenericMap"))
GenericMap = (OSDMap)map["GenericMap"];
if (map.ContainsKey("remoteEndPointIP"))
{
IPAddress add = new IPAddress(map["remoteEndPointIP"].AsBinary());
int port = map["remoteEndPointPort"].AsInteger();
m_remoteEndPoint = new IPEndPoint(add, port);
}
}
public override Dictionary<string, object> ToKVP()
{
return Util.OSDToDictionary(ToOSD());
}
public override void FromKVP(Dictionary<string, object> KVP)
{
FromOSD(Util.DictionaryToOSD(KVP));
}
#endregion
}
/// <summary>
/// This is the main service that collects URLs for registering clients.
/// Call this if you want to get secure URLs for the given SessionID
/// </summary>
public interface IGridRegistrationService
{
/// <summary>
/// Time before handlers will need to reregister (in hours)
/// </summary>
float ExpiresTime { get; }
/// <summary>
/// Gets a list of secure URLs for the given RegionHandle and SessionID
/// </summary>
/// <param name="SessionID"></param>
/// <returns></returns>
OSDMap GetUrlForRegisteringClient(string SessionID);
/// <summary>
/// Registers a module that will be requested when GetUrlForRegisteringClient is called
/// </summary>
/// <param name="module"></param>
void RegisterModule(IGridRegistrationUrlModule module);
/// <summary>
/// Remove the URLs for the given region
/// </summary>
/// <param name="SessionID"></param>
void RemoveUrlsForClient(string SessionID);
/// <summary>
/// Checks that the given client can access the function that it is calling
/// </summary>
/// <param name="SessionID"></param>
/// <param name="function"></param>
/// <param name="defaultThreatLevel"></param>
/// <returns></returns>
bool CheckThreatLevel(string SessionID, string function, ThreatLevel defaultThreatLevel);
/// <summary>
/// Updates the time so that the region does not timeout
/// </summary>
/// <param name="p"></param>
void UpdateUrlsForClient(string SessionID);
}
/// <summary>
/// The threat level enum
/// Tells how much we trust another host
/// </summary>
public enum ThreatLevel
{
None = 1,
Low = 2,
Medium = 4,
High = 8,
Full = 16
}
/// <summary>
/// This is the sub service of the IGridRegistrationService that is implemented by other modules
/// so that they can be queried for URLs to return.
/// </summary>
public interface IGridRegistrationUrlModule
{
/// <summary>
/// Name of the Url
/// </summary>
string UrlName { get; }
/// <summary>
/// Give the region all of the ports assigned for this module
/// </summary>
bool DoMultiplePorts { get; }
/// <summary>
/// Get the Url for the given sessionID
/// </summary>
/// <param name="SessionID"></param>
/// <param name="port"></param>
/// <returns></returns>
string GetUrlForRegisteringClient (string SessionID, uint port);
/// <summary>
/// Adds an existing URL to the module for the given SessionID and RegionHandle
/// </summary>
/// <param name="SessionID"></param>
/// <param name="url"></param>
/// <param name="port"></param>
void AddExistingUrlForClient (string SessionID, string url, uint port);
/// <summary>
/// Removes the given region from the http server so that the URLs cannot be used anymore
/// </summary>
/// <param name="sessionID"></param>
/// <param name="url"></param>
/// <param name="port"></param>
void RemoveUrlForClient (string sessionID, string url, uint port);
}
}
| |
// CodeContracts
//
// 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.
// File System.Activator.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System
{
sealed public partial class Activator : System.Runtime.InteropServices._Activator
{
#region Methods and constructors
internal Activator()
{
}
public static System.Runtime.Remoting.ObjectHandle CreateComInstanceFrom(string assemblyName, string typeName)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static System.Runtime.Remoting.ObjectHandle CreateComInstanceFrom(string assemblyName, string typeName, byte[] hashValue, System.Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstance(AppDomain domain, string assemblyName, string typeName)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstance(AppDomain domain, string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityAttributes)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstance(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityInfo)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstance(string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstance(ActivationContext activationContext, string[] activationCustomData)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static Object CreateInstance(Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture)
{
return default(Object);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstance(AppDomain domain, string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstance(ActivationContext activationContext)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static Object CreateInstance(Type type, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes)
{
return default(Object);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstance(string assemblyName, string typeName, Object[] activationAttributes)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static Object CreateInstance(Type type)
{
return default(Object);
}
public static Object CreateInstance(Type type, Object[] args)
{
return default(Object);
}
public static Object CreateInstance(Type type, Object[] args, Object[] activationAttributes)
{
return default(Object);
}
public static Object CreateInstance(Type type, bool nonPublic)
{
return default(Object);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstance(string assemblyName, string typeName)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static T CreateInstance<T>()
{
Contract.Ensures(Contract.Result<T>() != null);
return default(T);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(AppDomain domain, string assemblyFile, string typeName)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, Object[] activationAttributes)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityInfo)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(AppDomain domain, string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityAttributes)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(AppDomain domain, string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static System.Runtime.Remoting.ObjectHandle CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes)
{
return default(System.Runtime.Remoting.ObjectHandle);
}
public static Object GetObject(Type type, string url, Object state)
{
return default(Object);
}
public static Object GetObject(Type type, string url)
{
return default(Object);
}
void System.Runtime.InteropServices._Activator.GetIDsOfNames(ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
}
void System.Runtime.InteropServices._Activator.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
}
void System.Runtime.InteropServices._Activator.GetTypeInfoCount(out uint pcTInfo)
{
pcTInfo = default(uint);
}
void System.Runtime.InteropServices._Activator.Invoke(uint dispIdMember, ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
}
#endregion
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: SampleFix.SampleFixPublic
File: MainWindow.xaml.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace SampleFix
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Security;
using System.Windows;
using Ecng.Common;
using Ecng.Serialization;
using Ecng.Xaml;
using StockSharp.Messages;
using StockSharp.BusinessEntities;
using StockSharp.Fix;
using StockSharp.Logging;
using StockSharp.Localization;
public partial class MainWindow
{
private bool _isInitialized;
public readonly FixTrader Trader = new FixTrader();
private readonly SecuritiesWindow _securitiesWindow = new SecuritiesWindow();
private readonly TradesWindow _tradesWindow = new TradesWindow();
private readonly MyTradesWindow _myTradesWindow = new MyTradesWindow();
private readonly OrdersWindow _ordersWindow = new OrdersWindow();
private readonly PortfoliosWindow _portfoliosWindow = new PortfoliosWindow();
private readonly StopOrdersWindow _stopOrdersWindow = new StopOrdersWindow();
private readonly NewsWindow _newsWindow = new NewsWindow();
private readonly LogManager _logManager = new LogManager();
private const string _settingsFile = "fix_settings.xml";
public MainWindow()
{
InitializeComponent();
Title = Title.Put("FIX");
_ordersWindow.MakeHideable();
_myTradesWindow.MakeHideable();
_tradesWindow.MakeHideable();
_securitiesWindow.MakeHideable();
_stopOrdersWindow.MakeHideable();
_portfoliosWindow.MakeHideable();
_newsWindow.MakeHideable();
if (File.Exists(_settingsFile))
{
Trader.Load(new XmlSerializer<SettingsStorage>().Deserialize(_settingsFile));
}
MarketDataSessionSettings.SelectedObject = Trader.MarketDataAdapter;
TransactionSessionSettings.SelectedObject = Trader.TransactionAdapter;
MarketDataSupportedMessages.Adapter = Trader.MarketDataAdapter;
TransactionSupportedMessages.Adapter = Trader.TransactionAdapter;
Instance = this;
Trader.LogLevel = LogLevels.Debug;
_logManager.Sources.Add(Trader);
_logManager.Listeners.Add(new FileLogListener { LogDirectory = "StockSharp_Fix" });
}
protected override void OnClosing(CancelEventArgs e)
{
_ordersWindow.DeleteHideable();
_myTradesWindow.DeleteHideable();
_tradesWindow.DeleteHideable();
_securitiesWindow.DeleteHideable();
_stopOrdersWindow.DeleteHideable();
_portfoliosWindow.DeleteHideable();
_newsWindow.DeleteHideable();
_securitiesWindow.Close();
_tradesWindow.Close();
_myTradesWindow.Close();
_stopOrdersWindow.Close();
_ordersWindow.Close();
_portfoliosWindow.Close();
_newsWindow.Close();
if (Trader != null)
Trader.Dispose();
base.OnClosing(e);
}
public static MainWindow Instance { get; private set; }
private void ConnectClick(object sender, RoutedEventArgs e)
{
if (!_isInitialized)
{
_isInitialized = true;
Trader.Restored += () => this.GuiAsync(() =>
{
// update gui labes
ChangeConnectStatus(true);
MessageBox.Show(this, LocalizedStrings.Str2958);
});
// subscribe on connection successfully event
Trader.Connected += () =>
{
this.GuiAsync(() => ChangeConnectStatus(true));
};
Trader.Disconnected += () => this.GuiAsync(() => ChangeConnectStatus(false));
// subscribe on connection error event
Trader.ConnectionError += error => this.GuiAsync(() =>
{
// update gui labes
ChangeConnectStatus(false);
MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2959);
});
// subscribe on error event
Trader.Error += error =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2955));
// subscribe on error of market data subscription event
Trader.MarketDataSubscriptionFailed += (security, msg, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str2956Params.Put(msg.DataType, security)));
Trader.NewSecurities += securities => _securitiesWindow.SecurityPicker.Securities.AddRange(securities);
Trader.NewMyTrades += trades => _myTradesWindow.TradeGrid.Trades.AddRange(trades);
Trader.NewTrades += trades => _tradesWindow.TradeGrid.Trades.AddRange(trades);
Trader.NewOrders += orders => _ordersWindow.OrderGrid.Orders.AddRange(orders);
Trader.NewStopOrders += orders => _stopOrdersWindow.OrderGrid.Orders.AddRange(orders);
Trader.NewPortfolios += portfolios =>
{
// subscribe on portfolio updates
//portfolios.ForEach(Trader.RegisterPortfolio);
_portfoliosWindow.PortfolioGrid.Portfolios.AddRange(portfolios);
};
Trader.NewPositions += positions => _portfoliosWindow.PortfolioGrid.Positions.AddRange(positions);
// subscribe on error of order registration event
Trader.OrdersRegisterFailed += OrdersFailed;
// subscribe on error of order cancelling event
Trader.OrdersCancelFailed += OrdersFailed;
// subscribe on error of stop-order registration event
Trader.StopOrdersRegisterFailed += OrdersFailed;
// subscribe on error of stop-order cancelling event
Trader.StopOrdersCancelFailed += OrdersFailed;
Trader.MassOrderCancelFailed += (transId, error) =>
this.GuiAsync(() => MessageBox.Show(this, error.ToString(), LocalizedStrings.Str716));
Trader.NewNews += news => _newsWindow.NewsPanel.NewsGrid.News.Add(news);
// set market data provider
_securitiesWindow.SecurityPicker.MarketDataProvider = Trader;
// set news provider
_newsWindow.NewsPanel.NewsProvider = Trader;
ShowSecurities.IsEnabled = ShowTrades.IsEnabled = ShowNews.IsEnabled =
ShowMyTrades.IsEnabled = ShowOrders.IsEnabled =
ShowPortfolios.IsEnabled = ShowStopOrders.IsEnabled = true;
}
if (Trader.ConnectionState == ConnectionStates.Failed || Trader.ConnectionState == ConnectionStates.Disconnected)
{
new XmlSerializer<SettingsStorage>().Serialize(Trader.Save(), _settingsFile);
if (!NewPassword.Password.IsEmpty())
Trader.SendInMessage(new ChangePasswordMessage { NewPassword = NewPassword.Password.To<SecureString>() });
else
Trader.Connect();
}
else if (Trader.ConnectionState == ConnectionStates.Connected)
{
Trader.Disconnect();
}
}
private void OrdersFailed(IEnumerable<OrderFail> fails)
{
this.GuiAsync(() =>
{
foreach (var fail in fails)
MessageBox.Show(this, fail.Error.ToString(), LocalizedStrings.Str153);
});
}
private void ChangeConnectStatus(bool isConnected)
{
ConnectBtn.Content = isConnected ? LocalizedStrings.Disconnect : LocalizedStrings.Connect;
}
private void ShowSecuritiesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_securitiesWindow);
}
private void ShowTradesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_tradesWindow);
}
private void ShowMyTradesClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_myTradesWindow);
}
private void ShowOrdersClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_ordersWindow);
}
private void ShowPortfoliosClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_portfoliosWindow);
}
private void ShowStopOrdersClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_stopOrdersWindow);
}
private void ShowNewsClick(object sender, RoutedEventArgs e)
{
ShowOrHide(_newsWindow);
}
private static void ShowOrHide(Window window)
{
if (window == null)
throw new ArgumentNullException(nameof(window));
if (window.Visibility == Visibility.Visible)
window.Hide();
else
window.Show();
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// World.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
#endregion
namespace NetRumble
{
/// <summary>
/// A container for the game-specific logic and code.
/// </summary>
public class World : IDisposable
{
#region Public Constants
/// <summary>
/// The maximum number of players in the game.
/// </summary>
public const int MaximumPlayers = 16;
/// <summary>
/// The different types of packets sent in the game.
/// </summary>
/// <remarks>Frequently used in packets to identify their type.</remarks>
public enum PacketTypes
{
PlayerData,
ShipData,
WorldSetup,
WorldData,
ShipInput,
PowerUpSpawn,
ShipDeath,
ShipSpawn,
GameWon,
};
#endregion
#region Constants
/// <summary>
/// The score required to win the game.
/// </summary>
const int winningScore = 5;
/// <summary>
/// The number of asteroids in the game.
/// </summary>
const int numberOfAsteroids = 15;
/// <summary>
/// The length of time it takes for another power-up to spawn.
/// </summary>
const float maximumPowerUpTimer = 10f;
/// <summary>
/// The size of all of the barriers in the game.
/// </summary>
const int barrierSize = 48;
/// <summary>
/// The number of updates between WorldData packets.
/// </summary>
const int updatesBetweenWorldDataSend = 30;
/// <summary>
/// The number of updates between ship status packets from this machine.
/// </summary>
const int updatesBetweenStatusPackets = MaximumPlayers;
/// <summary>
/// The number of barriers in each dimension.
/// </summary>
static readonly Point barrierCounts = new Point(50, 50);
/// <summary>
/// The dimensions of the game world.
/// </summary>
static readonly Rectangle dimensions = new Rectangle(0, 0,
barrierCounts.X * barrierSize, barrierCounts.Y * barrierSize);
#endregion
#region State Data
/// <summary>
/// If true, the game has been initialized by receiving a WorldSetup packet.
/// </summary>
bool initialized = false;
public bool Initialized
{
get { return initialized; }
}
/// <summary>
/// If true, the game is over, and somebody has won.
/// </summary>
private bool gameWon = false;
public bool GameWon
{
get { return gameWon; }
set { gameWon = value; }
}
/// <summary>
/// The index of the player who won the game.
/// </summary>
private int winnerIndex = -1;
public int WinnerIndex
{
get { return winnerIndex; }
}
/// <summary>
/// If true, the game is over, because the game ended before somebody won.
/// </summary>
/// <remarks></remarks>
private bool gameExited = false;
public bool GameExited
{
get { return gameExited; }
set { gameExited = value; }
}
// presence support
private List<int> highScorers = new List<int>();
public List<int> HighScorers
{
get { return highScorers; }
}
#endregion
#region Gameplay Data
/// <summary>
/// The number of asteroids in the game.
/// </summary>
Asteroid[] asteroids = new Asteroid[numberOfAsteroids];
/// <summary>
/// The current power-up in the game.
/// </summary>
PowerUp powerUp = null;
/// <summary>
/// The amount of time left until the next power-up spawns.
/// </summary>
float powerUpTimer = maximumPowerUpTimer / 2f;
#endregion
#region Graphics Data
/// <summary>
/// The sprite batch used to draw the objects in the world.
/// </summary>
private SpriteBatch spriteBatch;
/// <summary>
/// The corner-barrier texture.
/// </summary>
private Texture2D cornerBarrierTexture;
/// <summary>
/// The vertical-barrier texture.
/// </summary>
private Texture2D verticalBarrierTexture;
/// <summary>
/// The horizontal-barrier texture.
/// </summary>
private Texture2D horizontalBarrierTexture;
/// <summary>
/// The texture signifying that the player can chat.
/// </summary>
private Texture2D chatAbleTexture;
/// <summary>
/// The texture signifying that the player has been muted.
/// </summary>
private Texture2D chatMuteTexture;
/// <summary>
/// The texture signifying that the player is talking right now.
/// </summary>
private Texture2D chatTalkingTexture;
/// <summary>
/// The texture signifying that the player is ready
/// </summary>
private Texture2D readyTexture;
/// <summary>
/// The sprite used to draw the player names.
/// </summary>
private SpriteFont playerFont;
public SpriteFont PlayerFont
{
get { return playerFont; }
}
/// <summary>
/// The list of corner barriers in the game world.
/// </summary>
/// <remarks>This list is not owned by this object.</remarks>
private List<Rectangle> cornerBarriers = new List<Rectangle>();
/// <summary>
/// The list of vertical barriers in the game world.
/// </summary>
/// <remarks>This list is not owned by this object.</remarks>
private List<Rectangle> verticalBarriers = new List<Rectangle>();
/// <summary>
/// The list of horizontal barriers in the game world.
/// </summary>
/// <remarks>This list is not owned by this object.</remarks>
private List<Rectangle> horizontalBarriers = new List<Rectangle>();
/// <summary>
/// The particle-effect manager for the game.
/// </summary>
ParticleEffectManager particleEffectManager;
#endregion
#region Networking Data
/// <summary>
/// The network session for the game.
/// </summary>
private NetworkSession networkSession;
/// <summary>
/// The packet writer for all of the data for the world.
/// </summary>
private PacketWriter packetWriter = new PacketWriter();
/// <summary>
/// The packet reader for all of the data for the world.
/// </summary>
private PacketReader packetReader = new PacketReader();
/// <summary>
/// The number of updates that have passed since the world data was sent.
/// </summary>
private int updatesSinceWorldDataSend = 0;
/// <summary>
/// The number of updates that have passed since a status packet was sent.
/// </summary>
private int updatesSinceStatusPacket = 0;
#endregion
#region Initialization
/// <summary>
/// Construct a new World object.
/// </summary>
/// <param name="graphicsDevice">The graphics device used for this game.</param>
/// <param name="networkSession">The network session for this game.</param>
public World(GraphicsDevice graphicsDevice, ContentManager contentManager,
NetworkSession networkSession)
{
// safety-check the parameters, as they must be valid
if (graphicsDevice == null)
{
throw new ArgumentNullException("graphicsDevice");
}
if (contentManager == null)
{
throw new ArgumentNullException("contentManager");
}
if (networkSession == null)
{
throw new ArgumentNullException("networkSession");
}
// apply the parameter values
this.networkSession = networkSession;
// set up the staggered status packet system
// -- your first update happens based on where you are in the collection
for (int i = 0; i < networkSession.AllGamers.Count; i++)
{
if (networkSession.AllGamers[i].IsLocal)
{
updatesSinceStatusPacket = i;
break;
}
}
// create the spritebatch
spriteBatch = new SpriteBatch(graphicsDevice);
// create and initialize the particle-effect manager
particleEffectManager = new ParticleEffectManager(contentManager);
particleEffectManager.RegisterParticleEffect(
ParticleEffectType.LaserExplosion,
"Particles/laserExplosion.xml", 40);
particleEffectManager.RegisterParticleEffect(
ParticleEffectType.MineExplosion,
"Particles/mineExplosion.xml", 8);
particleEffectManager.RegisterParticleEffect(
ParticleEffectType.RocketExplosion,
"Particles/rocketExplosion.xml", 24);
particleEffectManager.RegisterParticleEffect(
ParticleEffectType.RocketTrail,
"Particles/rocketTrail.xml", 16);
particleEffectManager.RegisterParticleEffect(
ParticleEffectType.ShipExplosion,
"Particles/shipExplosion.xml", 4);
particleEffectManager.RegisterParticleEffect(
ParticleEffectType.ShipSpawn,
"Particles/shipSpawn.xml", 4);
Ship.ParticleEffectManager = particleEffectManager;
RocketProjectile.ParticleEffectManager = particleEffectManager;
MineProjectile.ParticleEffectManager = particleEffectManager;
LaserProjectile.ParticleEffectManager = particleEffectManager;
// load the font
playerFont = contentManager.Load<SpriteFont>("Fonts/NetRumbleFont");
// load the gameplay-object textures
Ship.LoadContent(contentManager);
Asteroid.LoadContent(contentManager);
LaserProjectile.LoadContent(contentManager);
MineProjectile.LoadContent(contentManager);
RocketProjectile.LoadContent(contentManager);
DoubleLaserPowerUp.LoadContent(contentManager);
TripleLaserPowerUp.LoadContent(contentManager);
RocketPowerUp.LoadContent(contentManager);
// load the non-gameplay-object textures
chatAbleTexture = contentManager.Load<Texture2D>("Textures/chatAble");
chatMuteTexture = contentManager.Load<Texture2D>("Textures/chatMute");
chatTalkingTexture = contentManager.Load<Texture2D>("Textures/chatTalking");
readyTexture = contentManager.Load<Texture2D>("Textures/ready");
cornerBarrierTexture =
contentManager.Load<Texture2D>("Textures/barrierEnd");
verticalBarrierTexture =
contentManager.Load<Texture2D>("Textures/barrierPurple");
horizontalBarrierTexture =
contentManager.Load<Texture2D>("Textures/barrierRed");
// clear the collision manager
CollisionManager.Collection.Clear();
// add the collision version of the edge barriers
CollisionManager.Barriers.Clear();
CollisionManager.Barriers.Add(new Rectangle(dimensions.X, dimensions.Y,
dimensions.Width, barrierSize)); // top edge
CollisionManager.Barriers.Add(new Rectangle(
dimensions.X, dimensions.Y + dimensions.Height,
dimensions.Width, barrierSize)); // bottom edge
CollisionManager.Barriers.Add(new Rectangle(dimensions.X, dimensions.Y,
barrierSize, dimensions.Height)); // left edge
CollisionManager.Barriers.Add(new Rectangle(
dimensions.X + dimensions.Width, dimensions.Y,
barrierSize, dimensions.Height)); // right edge
// add the rendering version of the edge barriers
cornerBarriers.Clear();
cornerBarriers.Add(new Rectangle(dimensions.X, dimensions.Y,
barrierSize, barrierSize)); // top-left corner
cornerBarriers.Add(new Rectangle(
dimensions.X + dimensions.Width, dimensions.Y,
barrierSize, barrierSize)); // top-right corner
cornerBarriers.Add(new Rectangle(
dimensions.X, dimensions.Y + dimensions.Height,
barrierSize, barrierSize)); // bottom-left corner
cornerBarriers.Add(new Rectangle(
dimensions.X + dimensions.Width, dimensions.Y + dimensions.Height,
barrierSize, barrierSize)); // bottom-right corner
verticalBarriers.Clear();
for (int i = 1; i < barrierCounts.Y; i++)
{
verticalBarriers.Add(new Rectangle(
dimensions.X, dimensions.Y + barrierSize * i,
barrierSize, barrierSize)); // top edge
verticalBarriers.Add(new Rectangle(
dimensions.X + dimensions.Width, dimensions.Y + barrierSize * i,
barrierSize, barrierSize)); // bottom edge
}
horizontalBarriers.Clear();
for (int i = 1; i < barrierCounts.X; i++)
{
horizontalBarriers.Add(new Rectangle(
dimensions.X + barrierSize * i, dimensions.Y,
barrierSize, barrierSize)); // left edge
horizontalBarriers.Add(new Rectangle(
dimensions.X + barrierSize * i, dimensions.Y + dimensions.Width,
barrierSize, barrierSize)); // right edge
}
}
/// <summary>
/// Generate the initial state of the game, and send it to everyone.
/// </summary>
public void GenerateWorld()
{
if ((networkSession != null) && (networkSession.LocalGamers.Count > 0))
{
// write the identification value
packetWriter.Write((int)PacketTypes.WorldSetup);
// place the ships
// -- we always write the maximum number of players, making the packet
// predictable, in case the player count changes on the client before
// this packet is received
for (int i = 0; i < MaximumPlayers; i++)
{
Vector2 position = Vector2.Zero;
if (i < networkSession.AllGamers.Count)
{
PlayerData playerData = networkSession.AllGamers[i].Tag
as PlayerData;
if ((playerData != null) && (playerData.Ship != null))
{
playerData.Ship.Initialize();
position = playerData.Ship.Position =
CollisionManager.FindSpawnPoint(playerData.Ship,
playerData.Ship.Radius * 5f);
playerData.Ship.Score = 0;
}
}
// write the ship position
packetWriter.Write(position);
}
// place the asteroids
// -- for simplicity, the same number of asteroids is always the same
for (int i = 0; i < asteroids.Length; i++)
{
// choose one of three radii
float radius = 32f;
switch (RandomMath.Random.Next(3))
{
case 0:
radius = 32f;
break;
case 1:
radius = 60f;
break;
case 2:
radius = 96f;
break;
}
// create the asteroid
asteroids[i] = new Asteroid(radius);
// write the radius
packetWriter.Write(asteroids[i].Radius);
// choose a variation
asteroids[i].Variation = i % Asteroid.Variations;
// write the variation
packetWriter.Write(asteroids[i].Variation);
// initialize the asteroid and it's starting position
asteroids[i].Initialize();
asteroids[i].Position =
CollisionManager.FindSpawnPoint(asteroids[i],
asteroids[i].Radius);
// write the starting position and velocity
packetWriter.Write(asteroids[i].Position);
packetWriter.Write(asteroids[i].Velocity);
}
// send the packet to everyone
networkSession.LocalGamers[0].SendData(packetWriter,
SendDataOptions.ReliableInOrder);
}
}
/// <summary>
/// Initialize the world with the data from the WorldSetup packet.
/// </summary>
/// <param name="packetReader">The packet reader with the world data.</param>
public void Initialize()
{
// reset the game status
gameWon = false;
winnerIndex = -1;
gameExited = false;
// initialize the ships with the data from the packet
for (int i = 0; i < MaximumPlayers; i++)
{
// read each of the positions
Vector2 position = packetReader.ReadVector2();
// use the position value if we know of that many players
if (i < networkSession.AllGamers.Count)
{
PlayerData playerData = networkSession.AllGamers[i].Tag
as PlayerData;
if ((playerData != null) && (playerData.Ship != null))
{
// initialize the ship with the provided position
playerData.Ship.Position = position;
playerData.Ship.Score = 0;
playerData.Ship.Initialize();
}
}
}
// initialize the ships with the data from the packet
for (int i = 0; i < asteroids.Length; i++)
{
float radius = packetReader.ReadSingle();
if (asteroids[i] == null)
{
asteroids[i] = new Asteroid(radius);
}
asteroids[i].Variation = packetReader.ReadInt32();
asteroids[i].Position = packetReader.ReadVector2();
asteroids[i].Initialize();
asteroids[i].Velocity = packetReader.ReadVector2();
}
// set the initialized state
initialized = true;
}
#endregion
#region Updating Methods
/// <summary>
/// Update the world.
/// </summary>
/// <param name="elapsedTime">The amount of elapsed time, in seconds.</param>
/// <param name="paused">If true, the game is paused.</param>
public void Update(float elapsedTime, bool paused)
{
if (gameWon)
{
// update the particle-effect manager
particleEffectManager.Update(elapsedTime);
// make sure the collision manager is empty
CollisionManager.Collection.ApplyPendingRemovals();
if (CollisionManager.Collection.Count > 0)
{
CollisionManager.Collection.Clear();
}
}
else
{
// process all incoming packets
ProcessPackets();
// if the game is in progress, update the state of it
if (initialized && (networkSession != null) &&
(networkSession.SessionState == NetworkSessionState.Playing))
{
// presence support
int highScore = int.MinValue;
int highScoreIndex = -1;
for (int i = 0; i < networkSession.AllGamers.Count; i++)
{
NetworkGamer networkGamer = networkSession.AllGamers[i];
PlayerData playerData = networkGamer.Tag as PlayerData;
if ((playerData != null) && (playerData.Ship != null))
{
int playerScore = playerData.Ship.Score;
if (playerScore == highScore)
{
highScorers.Add(i);
}
else if (playerScore > highScore)
{
highScorers.Clear();
highScorers.Add(i);
highScore = playerScore;
highScoreIndex = i;
}
}
}
// the host has singular responsibilities to the game world,
// that need to be done once, by one authority
if (networkSession.IsHost)
{
// get the local player, for frequent re-use
LocalNetworkGamer localGamer = networkSession.Host
as LocalNetworkGamer;
// check for victory
// if victory has been achieved, send a packet to everyone
if (highScore >= winningScore)
{
packetWriter.Write((int)PacketTypes.GameWon);
packetWriter.Write(highScoreIndex);
localGamer.SendData(packetWriter,
SendDataOptions.ReliableInOrder);
}
// respawn each player, if it is time to do so
for (int i = 0; i < networkSession.AllGamers.Count; i++)
{
NetworkGamer networkGamer = networkSession.AllGamers[i];
PlayerData playerData = networkGamer.Tag as PlayerData;
if ((playerData != null) && (playerData.Ship != null) &&
!playerData.Ship.Active &&
(playerData.Ship.RespawnTimer <= 0f))
{
// write the ship-spawn packet
packetWriter.Write((int)PacketTypes.ShipSpawn);
packetWriter.Write(i);
packetWriter.Write(CollisionManager.FindSpawnPoint(
playerData.Ship, playerData.Ship.Radius));
localGamer.SendData(packetWriter,
SendDataOptions.ReliableInOrder);
}
}
// respawn the power-up if it is time to do so
if (powerUp == null)
{
powerUpTimer -= elapsedTime;
if (powerUpTimer < 0)
{
// write the power-up-spawn packet
packetWriter.Write((int)PacketTypes.PowerUpSpawn);
packetWriter.Write(RandomMath.Random.Next(3));
packetWriter.Write(CollisionManager.FindSpawnPoint(null,
PowerUp.PowerUpRadius * 3f));
localGamer.SendData(packetWriter,
SendDataOptions.ReliableInOrder);
}
}
else
{
powerUpTimer = maximumPowerUpTimer;
}
// send everyone an update on the state of the world
if (updatesSinceWorldDataSend >= updatesBetweenWorldDataSend)
{
packetWriter.Write((int)PacketTypes.WorldData);
// write each of the asteroids
for (int i = 0; i < asteroids.Length; i++)
{
packetWriter.Write(asteroids[i].Position);
packetWriter.Write(asteroids[i].Velocity);
}
localGamer.SendData(packetWriter,
SendDataOptions.InOrder);
updatesSinceWorldDataSend = 0;
}
else
{
updatesSinceWorldDataSend++;
}
}
// update each asteroid
foreach (Asteroid asteroid in asteroids)
{
if (asteroid.Active)
{
asteroid.Update(elapsedTime);
}
}
// update the power-up
if (powerUp != null)
{
if (powerUp.Active)
{
powerUp.Update(elapsedTime);
}
else
{
powerUp = null;
}
}
// process the local player's input
if (!paused)
{
ProcessLocalPlayerInput();
}
// update each ship
foreach (NetworkGamer networkGamer in networkSession.AllGamers)
{
PlayerData playerData = networkGamer.Tag as PlayerData;
if ((playerData != null) && (playerData.Ship != null))
{
if (playerData.Ship.Active)
{
playerData.Ship.Update(elapsedTime);
// check for death
// -- only check on local machines - the local player is
// the authority on the death of their own ship
if (networkGamer.IsLocal && (playerData.Ship.Life < 0))
{
SendLocalShipDeath();
}
}
else if (playerData.Ship.RespawnTimer > 0f)
{
playerData.Ship.RespawnTimer -= elapsedTime;
if (playerData.Ship.RespawnTimer < 0f)
{
playerData.Ship.RespawnTimer = 0f;
}
}
}
}
// update the other players with the current state of the local ship
if (updatesSinceStatusPacket >= updatesBetweenStatusPackets)
{
updatesSinceStatusPacket = 0;
SendLocalShipData();
}
else
{
updatesSinceStatusPacket++;
}
// update the collision manager
CollisionManager.Update(elapsedTime);
// update the particle-effect manager
particleEffectManager.Update(elapsedTime);
}
}
}
/// <summary>
/// Process the local player's input.
/// </summary>
private void ProcessLocalPlayerInput()
{
if ((networkSession != null) && (networkSession.LocalGamers.Count > 0))
{
// create the new input structure
ShipInput shipInput = new ShipInput(
GamePad.GetState(
networkSession.LocalGamers[0].SignedInGamer.PlayerIndex),
Keyboard.GetState(
networkSession.LocalGamers[0].SignedInGamer.PlayerIndex));
// send it out
// -- the local machine will receive and apply it from the network just
// like the other clients
shipInput.Serialize(packetWriter);
networkSession.LocalGamers[0].SendData(packetWriter,
SendDataOptions.InOrder);
}
}
/// <summary>
/// Send the current state of the ship to the other players.
/// </summary>
private void SendLocalShipData()
{
if ((networkSession != null) && (networkSession.LocalGamers.Count > 0))
{
PlayerData playerData = networkSession.LocalGamers[0].Tag as PlayerData;
if ((playerData != null) && (playerData.Ship != null))
{
packetWriter.Write((int)World.PacketTypes.ShipData);
packetWriter.Write(playerData.Ship.Position);
packetWriter.Write(playerData.Ship.Velocity);
packetWriter.Write(playerData.Ship.Rotation);
packetWriter.Write(playerData.Ship.Life);
packetWriter.Write(playerData.Ship.Shield);
packetWriter.Write(playerData.Ship.Score);
networkSession.LocalGamers[0].SendData(packetWriter,
SendDataOptions.InOrder);
}
}
}
/// <summary>
/// Send a notification of the death of the local ship to the other players.
/// </summary>
private void SendLocalShipDeath()
{
if ((networkSession != null) && (networkSession.LocalGamers.Count > 0))
{
LocalNetworkGamer localNetworkGamer = networkSession.LocalGamers[0]
as LocalNetworkGamer;
PlayerData playerData = localNetworkGamer.Tag as PlayerData;
if ((playerData != null) && (playerData.Ship != null))
{
// send a ship-death notification
packetWriter.Write((int)PacketTypes.ShipDeath);
// determine the player behind the last damage taken
int lastDamagedByPlayer = -1;
Ship lastDamagedByShip = playerData.Ship.LastDamagedBy as Ship;
if ((lastDamagedByShip != null) &&
(lastDamagedByShip != playerData.Ship))
{
for (int i = 0; i < networkSession.AllGamers.Count; i++)
{
PlayerData sourcePlayerData =
networkSession.AllGamers[i].Tag as PlayerData;
if ((sourcePlayerData != null) &&
(sourcePlayerData.Ship != null) &&
(sourcePlayerData.Ship == lastDamagedByShip))
{
lastDamagedByPlayer = i;
break;
}
}
}
packetWriter.Write(lastDamagedByPlayer);
localNetworkGamer.SendData(packetWriter,
SendDataOptions.ReliableInOrder);
}
}
}
#endregion
#region Packet Handling Methods
/// <summary>
/// Process incoming packets on the local gamer.
/// </summary>
private void ProcessPackets()
{
if ((networkSession != null) && (networkSession.LocalGamers.Count > 0))
{
// process all packets found, every frame
while (networkSession.LocalGamers[0].IsDataAvailable)
{
NetworkGamer sender;
networkSession.LocalGamers[0].ReceiveData(packetReader, out sender);
// read the type of packet...
PacketTypes packetType = (PacketTypes)packetReader.ReadInt32();
// ... and dispatch appropriately
switch (packetType)
{
case PacketTypes.PlayerData:
UpdatePlayerData(sender);
break;
case PacketTypes.WorldSetup:
// apply the world setup data, but only once
if (!Initialized)
{
Initialize();
}
break;
case PacketTypes.ShipData:
if ((sender != null) && !sender.IsLocal)
{
UpdateShipData(sender);
}
break;
case PacketTypes.WorldData:
if (!networkSession.IsHost && Initialized)
{
UpdateWorldData();
}
break;
case PacketTypes.ShipInput:
if (sender != null)
{
PlayerData playerData = sender.Tag as PlayerData;
if ((playerData != null) && (playerData.Ship != null))
{
playerData.Ship.ShipInput =
new ShipInput(packetReader);
}
}
break;
case PacketTypes.ShipSpawn:
SpawnShip();
break;
case PacketTypes.PowerUpSpawn:
SpawnPowerup();
break;
case PacketTypes.ShipDeath:
KillShip(sender);
break;
case PacketTypes.GameWon:
gameWon = true;
winnerIndex = packetReader.ReadInt32();
if (networkSession.IsHost && (networkSession.SessionState ==
NetworkSessionState.Playing))
{
networkSession.EndGame();
}
break;
}
}
}
}
/// <summary>
/// Spawn a ship based on the data in the packet.
/// </summary>
private void SpawnShip()
{
int whichGamer = packetReader.ReadInt32();
if (whichGamer < networkSession.AllGamers.Count)
{
NetworkGamer networkGamer = networkSession.AllGamers[whichGamer];
PlayerData playerData = networkGamer.Tag as PlayerData;
if ((playerData != null) && (playerData.Ship != null))
{
playerData.Ship.Position = packetReader.ReadVector2();
playerData.Ship.Initialize();
}
}
}
/// <summary>
/// Spawn a power-up based on the data in the packet.
/// </summary>
private void SpawnPowerup()
{
int whichPowerUp = packetReader.ReadInt32();
if (powerUp == null)
{
switch (whichPowerUp)
{
case 0:
powerUp = new DoubleLaserPowerUp();
break;
case 1:
powerUp = new TripleLaserPowerUp();
break;
case 2:
powerUp = new RocketPowerUp();
break;
}
}
if (powerUp != null)
{
powerUp.Position = packetReader.ReadVector2();
powerUp.Initialize();
}
}
/// <summary>
/// Kill the sender's ship based on data in the packet.
/// </summary>
/// <param name="sender">The sender of the packet.</param>
private void KillShip(NetworkGamer sender)
{
if (sender != null)
{
PlayerData playerData = sender.Tag as PlayerData;
if ((playerData != null) && (playerData.Ship != null) &&
playerData.Ship.Active)
{
GameplayObject source = null;
// read the index of the source of the last damage taken
int sourcePlayerIndex = packetReader.ReadInt32();
if ((sourcePlayerIndex >= 0) &&
(sourcePlayerIndex < networkSession.AllGamers.Count))
{
PlayerData sourcePlayerData =
networkSession.AllGamers[sourcePlayerIndex].Tag
as PlayerData;
source = sourcePlayerData != null ? sourcePlayerData.Ship :
null;
}
// kill the ship
playerData.Ship.Die(source, false);
}
}
}
/// <summary>
/// Update the player data for the sender based on the data in the packet.
/// </summary>
/// <param name="sender">The sender of the packet.</param>
private void UpdatePlayerData(NetworkGamer sender)
{
if ((networkSession != null) && (networkSession.LocalGamers.Count > 0) &&
(sender != null))
{
PlayerData playerData = sender.Tag as PlayerData;
if (playerData != null)
{
playerData.Deserialize(packetReader);
// see if we're still unique
// -- this can happen legitimately as we receive introductory data
foreach (LocalNetworkGamer localNetworkGamer in
networkSession.LocalGamers)
{
PlayerData localPlayerData =
localNetworkGamer.Tag as PlayerData;
if ((localPlayerData != null) &&
!Ship.HasUniqueColorIndex(localNetworkGamer,
networkSession))
{
localPlayerData.ShipColor = Ship.GetNextUniqueColorIndex(
localPlayerData.ShipColor, networkSession);
packetWriter.Write((int)World.PacketTypes.PlayerData);
localPlayerData.Serialize(packetWriter);
networkSession.LocalGamers[0].SendData(packetWriter,
SendDataOptions.ReliableInOrder);
}
}
}
}
}
/// <summary>
/// Update ship state based on the data in the packet.
/// </summary>
/// <param name="sender">The sender of the packet.</param>
private void UpdateShipData(NetworkGamer sender)
{
if (sender != null)
{
PlayerData playerData = sender.Tag as PlayerData;
if ((playerData != null) && (playerData.Ship != null))
{
playerData.Ship.Position = packetReader.ReadVector2();
playerData.Ship.Velocity = packetReader.ReadVector2();
playerData.Ship.Rotation = packetReader.ReadSingle();
playerData.Ship.Life = packetReader.ReadSingle();
playerData.Ship.Shield = packetReader.ReadSingle();
playerData.Ship.Score = packetReader.ReadInt32();
}
}
}
/// <summary>
/// Update the world data based on the data in the packet.
/// </summary>
private void UpdateWorldData()
{
// safety-check the parameters, as they must be valid
if (packetReader == null)
{
throw new ArgumentNullException("packetReader");
}
for (int i = 0; i < asteroids.Length; i++)
{
asteroids[i].Position = packetReader.ReadVector2();
asteroids[i].Velocity = packetReader.ReadVector2();
}
}
#endregion
#region Drawing Methods
/// <summary>
/// Draws the objects in the world.
/// </summary>
/// <param name="elapsedTime">The amount of elapsed time, in seconds.</param>
/// <param name="center">The center of the current view.</param>
public void Draw(float elapsedTime, Vector2 center)
{
Matrix transform = Matrix.CreateTranslation(
new Vector3(-center.X, -center.Y, 0f));
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied,
null, null, null, null, transform);
// draw the barriers
foreach (Rectangle rectangle in cornerBarriers)
{
spriteBatch.Draw(cornerBarrierTexture, rectangle, Color.White);
}
foreach (Rectangle rectangle in verticalBarriers)
{
spriteBatch.Draw(verticalBarrierTexture, rectangle, Color.White);
}
foreach (Rectangle rectangle in horizontalBarriers)
{
spriteBatch.Draw(horizontalBarrierTexture, rectangle, Color.White);
}
// draw the asteroids
foreach (Asteroid asteroid in asteroids)
{
if (asteroid.Active)
{
asteroid.Draw(elapsedTime, spriteBatch);
}
}
// draw the powerup
if ((powerUp != null) && powerUp.Active)
{
powerUp.Draw(elapsedTime, spriteBatch);
}
// draw the ships
foreach (NetworkGamer networkGamer in networkSession.AllGamers)
{
PlayerData playerData = networkGamer.Tag as PlayerData;
if ((playerData != null) && (playerData.Ship != null) &&
playerData.Ship.Active)
{
playerData.Ship.Draw(elapsedTime, spriteBatch);
}
}
// draw the alpha-blended particles
particleEffectManager.Draw(spriteBatch, SpriteBlendMode.AlphaBlend);
spriteBatch.End();
// draw the additive particles
spriteBatch.Begin(SpriteSortMode.Texture, BlendState.Additive,
null, null, null, null, transform);
particleEffectManager.Draw(spriteBatch, SpriteBlendMode.Additive);
spriteBatch.End();
}
/// <summary>
/// Draw the specified player's data in the screen - gamertag, etc.
/// </summary>
/// <param name="totalTime">The total time spent in the game.</param>
/// <param name="networkGamer">The player to be drawn.</param>
/// <param name="position">The center of the desired location.</param>
/// <param name="spriteBatch">The SpriteBatch object used to draw.</param>
/// <param name="lobby">If true, drawn "lobby style"</param>
public void DrawPlayerData(float totalTime, NetworkGamer networkGamer,
Vector2 position, SpriteBatch spriteBatch, bool lobby)
{
// safety-check the parameters, as they must be valid
if (networkGamer == null)
{
throw new ArgumentNullException("networkGamer");
}
if (spriteBatch == null)
{
throw new ArgumentNullException("spriteBatch");
}
// get the player data
PlayerData playerData = networkGamer.Tag as PlayerData;
if (playerData == null)
{
return;
}
// draw the gamertag
float playerStringScale = 1.0f;
if (networkGamer.IsLocal)
{
// pulse the scale of local gamers
playerStringScale = 1f + 0.08f * (1f + (float)Math.Sin(totalTime * 4f));
}
string playerString = networkGamer.Gamertag;
Color playerColor = playerData.Ship == null ?
Ship.ShipColors[playerData.ShipColor] : playerData.Ship.Color;
Vector2 playerStringSize = playerFont.MeasureString(playerString);
Vector2 playerStringPosition = position;
spriteBatch.DrawString(playerFont, playerString, playerStringPosition,
playerColor, 0f,
new Vector2(playerStringSize.X / 2f, playerStringSize.Y / 2f),
playerStringScale, SpriteEffects.None, 0f);
// draw the chat texture
Texture2D chatTexture = null;
if (networkGamer.IsMutedByLocalUser)
{
chatTexture = chatMuteTexture;
}
else if (networkGamer.IsTalking)
{
chatTexture = chatTalkingTexture;
}
else if (networkGamer.HasVoice)
{
chatTexture = chatAbleTexture;
}
if (chatTexture != null)
{
float chatTextureScale = 0.9f * playerStringSize.Y /
(float)chatTexture.Height;
Vector2 chatTexturePosition = new Vector2(playerStringPosition.X -
1.2f * playerStringSize.X / 2f -
1.1f * chatTextureScale * (float)chatTexture.Width / 2f,
playerStringPosition.Y);
spriteBatch.Draw(chatTexture, chatTexturePosition, null,
Color.White, 0f, new Vector2((float)chatTexture.Width / 2f,
(float)chatTexture.Height / 2f), chatTextureScale,
SpriteEffects.None, 0f);
}
// if we're in "lobby mode", draw a sample version of the ship,
// and the ready texture
if (lobby)
{
// draw the ship
if (playerData.Ship != null)
{
float oldShipShield = playerData.Ship.Shield;
float oldShipRadius = playerData.Ship.Radius;
Vector2 oldShipPosition = playerData.Ship.Position;
float oldShipRotation = playerData.Ship.Rotation;
playerData.Ship.Shield = 0f;
playerData.Ship.Radius = 0.6f * (float)playerStringSize.Y;
playerData.Ship.Position = new Vector2(playerStringPosition.X +
1.2f * playerStringSize.X / 2f + 1.1f * playerData.Ship.Radius,
playerStringPosition.Y);
playerData.Ship.Rotation = 0f;
playerData.Ship.Draw(0f, spriteBatch);
playerData.Ship.Rotation = oldShipRotation;
playerData.Ship.Position = oldShipPosition;
playerData.Ship.Shield = oldShipShield;
playerData.Ship.Radius = oldShipRadius;
}
// draw the ready texture
if ((readyTexture != null) && networkGamer.IsReady)
{
float readyTextureScale = 0.9f * playerStringSize.Y /
(float)readyTexture.Height;
Vector2 readyTexturePosition = new Vector2(playerStringPosition.X +
1.2f * playerStringSize.X / 2f +
2.2f * playerData.Ship.Radius +
1.1f * readyTextureScale * (float)readyTexture.Width / 2f,
playerStringPosition.Y);
spriteBatch.Draw(readyTexture, readyTexturePosition, null,
Color.White, 0f, new Vector2((float)readyTexture.Width / 2f,
(float)readyTexture.Height / 2f), readyTextureScale,
SpriteEffects.None, 0f);
}
}
else
{
// if we're not in "lobby mode", draw the score
if (playerData.Ship != null)
{
string scoreString = String.Empty;
if (playerData.Ship.Active)
{
scoreString = playerData.Ship.Score.ToString();
}
else
{
int respawnTimer =
(int)Math.Ceiling(playerData.Ship.RespawnTimer);
scoreString = "Respawning in: " + respawnTimer.ToString();
}
Vector2 scoreStringSize = playerFont.MeasureString(scoreString);
Vector2 scoreStringPosition = new Vector2(position.X,
position.Y + 0.9f * playerStringSize.Y);
spriteBatch.DrawString(playerFont, scoreString, scoreStringPosition,
playerColor, 0f, new Vector2(scoreStringSize.X / 2f,
scoreStringSize.Y / 2f), 1f, SpriteEffects.None, 0f);
}
}
}
#endregion
#region IDisposable Implementation
/// <summary>
/// Finalizes the World object, calls Dispose(false)
/// </summary>
~World()
{
Dispose(false);
}
/// <summary>
/// Disposes the World object.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes this object.
/// </summary>
/// <param name="disposing">
/// True if this method was called as part of the Dispose method.
/// </param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
lock (this)
{
if (packetReader != null)
{
packetReader.Close();
packetReader = null;
}
if (packetWriter != null)
{
packetWriter.Close();
packetWriter = null;
}
if (spriteBatch != null)
{
spriteBatch.Dispose();
spriteBatch = null;
}
cornerBarrierTexture = null;
verticalBarrierTexture = null;
horizontalBarrierTexture = null;
Ship.UnloadContent();
Asteroid.UnloadContent();
LaserProjectile.UnloadContent();
MineProjectile.UnloadContent();
RocketProjectile.UnloadContent();
DoubleLaserPowerUp.UnloadContent();
TripleLaserPowerUp.UnloadContent();
Ship.ParticleEffectManager = null;
RocketProjectile.ParticleEffectManager = null;
MineProjectile.ParticleEffectManager = null;
LaserProjectile.ParticleEffectManager = null;
particleEffectManager.UnregisterParticleEffect(
ParticleEffectType.MineExplosion);
particleEffectManager.UnregisterParticleEffect(
ParticleEffectType.RocketExplosion);
particleEffectManager.UnregisterParticleEffect(
ParticleEffectType.RocketTrail);
particleEffectManager.UnregisterParticleEffect(
ParticleEffectType.ShipExplosion);
particleEffectManager.UnregisterParticleEffect(
ParticleEffectType.ShipSpawn);
}
}
}
#endregion
}
}
| |
//
// PlayerEngineService.cs
//
// Author:
// Aaron Bockover <[email protected]>
//
// Copyright (C) 2006-2008 Novell, 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.IO;
using System.Collections.Generic;
using System.Reflection;
using Mono.Unix;
using Mono.Addins;
using Hyena;
using Banshee.Base;
using Banshee.Streaming;
using Banshee.ServiceStack;
using Banshee.Sources;
using Banshee.Query;
using Banshee.Metadata;
using Banshee.Configuration;
using Banshee.Collection;
using Banshee.Equalizer;
using Banshee.Collection.Database;
namespace Banshee.MediaEngine
{
public delegate bool TrackInterceptHandler (TrackInfo track);
public class PlayerEngineService : IInitializeService, IDelayedInitializeService,
IRequiredService, IPlayerEngineService, IDisposable
{
private List<PlayerEngine> engines = new List<PlayerEngine> ();
private PlayerEngine active_engine;
private PlayerEngine default_engine;
private PlayerEngine pending_engine;
private object pending_playback_for_not_ready;
private bool pending_playback_for_not_ready_play;
private TrackInfo synthesized_contacting_track;
private string preferred_engine_id = null;
public event EventHandler PlayWhenIdleRequest;
public event TrackInterceptHandler TrackIntercept;
public event Action<PlayerEngine> EngineBeforeInitialize;
public event Action<PlayerEngine> EngineAfterInitialize;
private event DBusPlayerEventHandler dbus_event_changed;
event DBusPlayerEventHandler IPlayerEngineService.EventChanged {
add { dbus_event_changed += value; }
remove { dbus_event_changed -= value; }
}
private event DBusPlayerStateHandler dbus_state_changed;
event DBusPlayerStateHandler IPlayerEngineService.StateChanged {
add { dbus_state_changed += value; }
remove { dbus_state_changed -= value; }
}
public PlayerEngineService ()
{
}
void IInitializeService.Initialize ()
{
preferred_engine_id = EngineSchema.Get();
if (default_engine == null && engines.Count > 0) {
default_engine = engines[0];
}
foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/MediaEngine/PlayerEngine")) {
LoadEngine (node);
}
if (default_engine != null) {
active_engine = default_engine;
Log.Debug (Catalog.GetString ("Default player engine"), active_engine.Name);
} else {
default_engine = active_engine;
}
if (default_engine == null || active_engine == null || engines == null || engines.Count == 0) {
Log.Warning (Catalog.GetString (
"No player engines were found. Please ensure Banshee has been cleanly installed."),
"Using the featureless NullPlayerEngine.");
PlayerEngine null_engine = new NullPlayerEngine ();
LoadEngine (null_engine);
active_engine = null_engine;
default_engine = null_engine;
}
MetadataService.Instance.HaveResult += OnMetadataServiceHaveResult;
TrackInfo.IsPlayingMethod = track => IsPlaying (track) &&
track.CacheModelId == CurrentTrack.CacheModelId &&
(track.CacheEntryId == null || track.CacheEntryId.Equals (CurrentTrack.CacheEntryId));
}
private void InitializeEngine (PlayerEngine engine)
{
var handler = EngineBeforeInitialize;
if (handler != null) {
handler (engine);
}
engine.Initialize ();
engine.IsInitialized = true;
handler = EngineAfterInitialize;
if (handler != null) {
handler (engine);
}
}
void IDelayedInitializeService.DelayedInitialize ()
{
foreach (var engine in Engines) {
if (engine.DelayedInitialize) {
InitializeEngine (engine);
}
}
}
private void LoadEngine (TypeExtensionNode node)
{
LoadEngine ((PlayerEngine) node.CreateInstance (typeof (PlayerEngine)));
}
private void LoadEngine (PlayerEngine engine)
{
if (!engine.DelayedInitialize) {
InitializeEngine (engine);
}
engine.EventChanged += OnEngineEventChanged;
if (engine.Id == preferred_engine_id) {
DefaultEngine = engine;
} else {
if (active_engine == null) {
active_engine = engine;
}
engines.Add (engine);
}
}
public void Dispose ()
{
MetadataService.Instance.HaveResult -= OnMetadataServiceHaveResult;
foreach (PlayerEngine engine in engines) {
engine.Dispose ();
}
active_engine = null;
default_engine = null;
pending_engine = null;
preferred_engine_id = null;
engines.Clear ();
}
private void OnMetadataServiceHaveResult (object o, MetadataLookupResultArgs args)
{
if (CurrentTrack != null && CurrentTrack.TrackEqual (args.Track as TrackInfo)) {
foreach (StreamTag tag in args.ResultTags) {
StreamTagger.TrackInfoMerge (CurrentTrack, tag);
}
OnEngineEventChanged (new PlayerEventArgs (PlayerEvent.TrackInfoUpdated));
}
}
private void HandleStateChange (PlayerEventStateChangeArgs args)
{
if (args.Current == PlayerState.Loaded && CurrentTrack != null) {
MetadataService.Instance.Lookup (CurrentTrack);
} else if (args.Current == PlayerState.Ready) {
// Enable our preferred equalizer if it exists and was enabled last time.
if (SupportsEqualizer) {
EqualizerManager.Instance.Select ();
}
if (pending_playback_for_not_ready != null) {
OpenCheck (pending_playback_for_not_ready, pending_playback_for_not_ready_play);
pending_playback_for_not_ready = null;
pending_playback_for_not_ready_play = false;
}
}
DBusPlayerStateHandler dbus_handler = dbus_state_changed;
if (dbus_handler != null) {
dbus_handler (args.Current.ToString ().ToLower ());
}
}
private void OnEngineEventChanged (PlayerEventArgs args)
{
if (CurrentTrack != null) {
if (args.Event == PlayerEvent.Error
&& CurrentTrack.PlaybackError == StreamPlaybackError.None) {
CurrentTrack.SavePlaybackError (StreamPlaybackError.Unknown);
} else if (args.Event == PlayerEvent.Iterate
&& CurrentTrack.PlaybackError != StreamPlaybackError.None) {
CurrentTrack.SavePlaybackError (StreamPlaybackError.None);
}
}
if (args.Event == PlayerEvent.StartOfStream) {
incremented_last_played = false;
} else if (args.Event == PlayerEvent.EndOfStream) {
IncrementLastPlayed ();
}
RaiseEvent (args);
// Do not raise iterate across DBus to avoid so many calls;
// DBus clients should do their own iterating and
// event/state checking locally
if (args.Event == PlayerEvent.Iterate) {
return;
}
DBusPlayerEventHandler dbus_handler = dbus_event_changed;
if (dbus_handler != null) {
dbus_handler (args.Event.ToString ().ToLower (),
args is PlayerEventErrorArgs ? ((PlayerEventErrorArgs)args).Message : String.Empty,
args is PlayerEventBufferingArgs ? ((PlayerEventBufferingArgs)args).Progress : 0
);
}
}
private void OnPlayWhenIdleRequest ()
{
EventHandler handler = PlayWhenIdleRequest;
if (handler != null) {
handler (this, EventArgs.Empty);
}
}
private bool OnTrackIntercept (TrackInfo track)
{
TrackInterceptHandler handler = TrackIntercept;
if (handler == null) {
return false;
}
bool handled = false;
foreach (TrackInterceptHandler single_handler in handler.GetInvocationList ()) {
handled |= single_handler (track);
}
return handled;
}
public void Open (TrackInfo track)
{
OpenPlay (track, false);
}
public void Open (SafeUri uri)
{
// Check if the uri exists
if (uri == null || !File.Exists (uri.AbsolutePath)) {
return;
}
bool found = false;
if (ServiceManager.DbConnection != null) {
// Try to find uri in the library
long track_id = DatabaseTrackInfo.GetTrackIdForUri (uri);
if (track_id > 0) {
DatabaseTrackInfo track_db = DatabaseTrackInfo.Provider.FetchSingle (track_id);
found = true;
Open (track_db);
}
}
if (!found) {
// Not in the library, get info from the file
TrackInfo track = new TrackInfo ();
using (var file = StreamTagger.ProcessUri (uri)) {
StreamTagger.TrackInfoMerge (track, file, false);
}
Open (track);
}
}
void IPlayerEngineService.Open (string uri)
{
Open (new SafeUri (uri));
}
public void SetNextTrack (TrackInfo track)
{
if (track != null && EnsureActiveEngineCanPlay (track.Uri)) {
active_engine.SetNextTrack (track);
} else {
active_engine.SetNextTrack ((TrackInfo) null);
}
}
public void SetNextTrack (SafeUri uri)
{
if (EnsureActiveEngineCanPlay (uri)) {
active_engine.SetNextTrack (uri);
} else {
active_engine.SetNextTrack ((SafeUri) null);
}
}
private bool EnsureActiveEngineCanPlay (SafeUri uri)
{
if (uri == null) {
// No engine can play the null URI.
return false;
}
if (active_engine != FindSupportingEngine (uri)) {
if (active_engine.CurrentState == PlayerState.Playing) {
// If we're currently playing then we can't switch engines now.
// We can't ensure the active engine can play this URI.
return false;
} else {
// If we're not playing, we can switch the active engine to
// something that will play this URI.
SwitchToEngine (FindSupportingEngine (uri));
CheckPending ();
return true;
}
}
return true;
}
public void OpenPlay (TrackInfo track)
{
OpenPlay (track, true);
}
private void OpenPlay (TrackInfo track, bool play)
{
if (track == null || !track.CanPlay || OnTrackIntercept (track)) {
return;
}
try {
OpenCheck (track, play);
} catch (Exception e) {
Log.Error (e);
Log.Error (Catalog.GetString ("Problem with Player Engine"), e.Message, true);
Close ();
ActiveEngine = default_engine;
}
}
private void OpenCheck (object o, bool play)
{
if (CurrentState == PlayerState.NotReady) {
pending_playback_for_not_ready = o;
pending_playback_for_not_ready_play = play;
return;
}
SafeUri uri = null;
TrackInfo track = null;
if (o is SafeUri) {
uri = (SafeUri)o;
} else if (o is TrackInfo) {
track = (TrackInfo)o;
uri = track.Uri;
} else {
return;
}
if (track != null && (track.MediaAttributes & TrackMediaAttributes.ExternalResource) != 0) {
RaiseEvent (new PlayerEventArgs (PlayerEvent.EndOfStream));
return;
}
PlayerEngine supportingEngine = FindSupportingEngine (uri);
SwitchToEngine (supportingEngine);
CheckPending ();
if (track != null) {
active_engine.Open (track);
} else if (uri != null) {
active_engine.Open (uri);
}
if (play) {
active_engine.Play ();
}
}
public void IncrementLastPlayed ()
{
// If Length <= 0 assume 100% completion.
IncrementLastPlayed (active_engine.Length <= 0
? 1.0
: (double)active_engine.Position / active_engine.Length);
}
private bool incremented_last_played = true;
public void IncrementLastPlayed (double completed)
{
if (!incremented_last_played && CurrentTrack != null && CurrentTrack.PlaybackError == StreamPlaybackError.None) {
CurrentTrack.OnPlaybackFinished (completed);
incremented_last_played = true;
}
}
private PlayerEngine FindSupportingEngine (SafeUri uri)
{
foreach (PlayerEngine engine in engines) {
foreach (string extension in engine.ExplicitDecoderCapabilities) {
if (!uri.AbsoluteUri.EndsWith (extension)) {
continue;
}
return engine;
}
}
foreach (PlayerEngine engine in engines) {
foreach (string scheme in engine.SourceCapabilities) {
bool supported = scheme == uri.Scheme;
if (supported) {
return engine;
}
}
}
// If none of our engines support this URI, return the currently active one.
// There doesn't seem to be anything better to do.
return active_engine;
}
private bool SwitchToEngine (PlayerEngine switchTo)
{
if (active_engine != switchTo) {
Close ();
pending_engine = switchTo;
Log.DebugFormat ("Switching engine to: {0}", switchTo.GetType ());
return true;
}
return false;
}
public void Close ()
{
Close (false);
}
public void Close (bool fullShutdown)
{
IncrementLastPlayed ();
active_engine.Close (fullShutdown);
}
public void Play ()
{
if (CurrentState == PlayerState.Idle) {
OnPlayWhenIdleRequest ();
} else {
active_engine.Play ();
}
}
public void Pause ()
{
if (!CanPause) {
Close ();
} else {
active_engine.Pause ();
}
}
public void RestartCurrentTrack ()
{
var track = CurrentTrack;
if (track != null) {
// Don't process the track as played through IncrementLastPlayed, just play it again
active_engine.Close (false);
OpenPlay (track);
}
}
// For use by RadioTrackInfo
// TODO remove this method once RadioTrackInfo playlist downloading/parsing logic moved here?
internal void StartSynthesizeContacting (TrackInfo track)
{
//OnStateChanged (PlayerState.Contacting);
RaiseEvent (new PlayerEventStateChangeArgs (CurrentState, PlayerState.Contacting));
synthesized_contacting_track = track;
}
internal void EndSynthesizeContacting (TrackInfo track, bool idle)
{
if (track == synthesized_contacting_track) {
synthesized_contacting_track = null;
if (idle) {
RaiseEvent (new PlayerEventStateChangeArgs (PlayerState.Contacting, PlayerState.Idle));
}
}
}
public void TogglePlaying ()
{
if (IsPlaying () && CurrentState != PlayerState.Paused) {
Pause ();
} else if (CurrentState != PlayerState.NotReady) {
Play ();
}
}
public void Seek (uint position, bool accurate_seek)
{
active_engine.Seek (position, accurate_seek);
}
public void Seek (uint position)
{
Seek (position, false);
}
public void TrackInfoUpdated ()
{
active_engine.TrackInfoUpdated ();
}
public bool IsPlaying (TrackInfo track)
{
return IsPlaying () && track != null && track.TrackEqual (CurrentTrack);
}
public bool IsPlaying ()
{
return CurrentState == PlayerState.Playing ||
CurrentState == PlayerState.Paused ||
CurrentState == PlayerState.Loaded ||
CurrentState == PlayerState.Loading ||
CurrentState == PlayerState.Contacting;
}
private void CheckPending ()
{
if (pending_engine != null && pending_engine != active_engine) {
if (active_engine.CurrentState == PlayerState.Idle) {
Close ();
}
active_engine = pending_engine;
pending_engine = null;
}
}
public TrackInfo CurrentTrack {
get {
return active_engine == null ? null : active_engine.CurrentTrack ?? synthesized_contacting_track;
}
}
private Dictionary<string, object> dbus_sucks;
IDictionary<string, object> IPlayerEngineService.CurrentTrack {
get {
// FIXME: Managed DBus sucks - it explodes if you transport null
// or even an empty dictionary (a{sv} in our case). Piece of shit.
if (dbus_sucks == null) {
dbus_sucks = new Dictionary<string, object> ();
dbus_sucks.Add (String.Empty, String.Empty);
}
return CurrentTrack == null ? dbus_sucks : CurrentTrack.GenerateExportable ();
}
}
public SafeUri CurrentSafeUri {
get { return active_engine.CurrentUri; }
}
string IPlayerEngineService.CurrentUri {
get { return CurrentSafeUri == null ? String.Empty : CurrentSafeUri.AbsoluteUri; }
}
public PlayerState CurrentState {
get {
if (active_engine == null) {
return PlayerState.NotReady;
}
return synthesized_contacting_track != null ? PlayerState.Contacting : active_engine.CurrentState;
}
}
string IPlayerEngineService.CurrentState {
get { return CurrentState.ToString ().ToLower (); }
}
public PlayerState LastState {
get { return active_engine.LastState; }
}
string IPlayerEngineService.LastState {
get { return LastState.ToString ().ToLower (); }
}
public ushort Volume {
get { return active_engine.Volume; }
set {
foreach (PlayerEngine engine in engines) {
engine.Volume = value;
}
}
}
public uint Position {
get { return active_engine.Position; }
set { active_engine.Position = value; }
}
public byte Rating {
get { return (byte)(CurrentTrack == null ? 0 : CurrentTrack.Rating); }
set {
if (CurrentTrack != null) {
CurrentTrack.Rating = (int)Math.Min (5u, value);
CurrentTrack.Save ();
foreach (var source in ServiceManager.SourceManager.Sources) {
var psource = source as PrimarySource;
if (psource != null) {
psource.NotifyTracksChanged (BansheeQuery.RatingField);
}
}
}
}
}
public bool CanSeek {
get { return active_engine.CanSeek; }
}
public bool CanPause {
get { return CurrentTrack != null && !CurrentTrack.IsLive; }
}
public bool SupportsEqualizer {
get { return ((active_engine is IEqualizer) && active_engine.SupportsEqualizer); }
}
public uint Length {
get {
uint length = active_engine.Length;
if (length > 0) {
return length;
} else if (CurrentTrack == null) {
return 0;
}
return (uint) CurrentTrack.Duration.TotalSeconds;
}
}
public PlayerEngine ActiveEngine {
get { return active_engine; }
set { pending_engine = value; }
}
public PlayerEngine DefaultEngine {
get { return default_engine; }
set {
if (engines.Contains (value)) {
engines.Remove (value);
}
engines.Insert (0, value);
default_engine = value;
EngineSchema.Set (value.Id);
}
}
public IEnumerable<PlayerEngine> Engines {
get { return engines; }
}
#region Player Event System
private LinkedList<PlayerEventHandlerSlot> event_handlers = new LinkedList<PlayerEventHandlerSlot> ();
private struct PlayerEventHandlerSlot
{
public PlayerEvent EventMask;
public PlayerEventHandler Handler;
public PlayerEventHandlerSlot (PlayerEvent mask, PlayerEventHandler handler)
{
EventMask = mask;
Handler = handler;
}
}
private const PlayerEvent event_all_mask = PlayerEvent.Iterate
| PlayerEvent.StateChange
| PlayerEvent.StartOfStream
| PlayerEvent.EndOfStream
| PlayerEvent.Buffering
| PlayerEvent.Seek
| PlayerEvent.Error
| PlayerEvent.Volume
| PlayerEvent.Metadata
| PlayerEvent.TrackInfoUpdated
| PlayerEvent.RequestNextTrack
| PlayerEvent.PrepareVideoWindow;
private const PlayerEvent event_default_mask = event_all_mask & ~PlayerEvent.Iterate;
private static void VerifyEventMask (PlayerEvent eventMask)
{
if (eventMask <= PlayerEvent.None || eventMask > event_all_mask) {
throw new ArgumentOutOfRangeException ("eventMask", "A valid event mask must be provided");
}
}
public void ConnectEvent (PlayerEventHandler handler)
{
ConnectEvent (handler, event_default_mask, false);
}
public void ConnectEvent (PlayerEventHandler handler, PlayerEvent eventMask)
{
ConnectEvent (handler, eventMask, false);
}
public void ConnectEvent (PlayerEventHandler handler, bool connectAfter)
{
ConnectEvent (handler, event_default_mask, connectAfter);
}
public void ConnectEvent (PlayerEventHandler handler, PlayerEvent eventMask, bool connectAfter)
{
lock (event_handlers) {
VerifyEventMask (eventMask);
PlayerEventHandlerSlot slot = new PlayerEventHandlerSlot (eventMask, handler);
if (connectAfter) {
event_handlers.AddLast (slot);
} else {
event_handlers.AddFirst (slot);
}
}
}
private LinkedListNode<PlayerEventHandlerSlot> FindEventNode (PlayerEventHandler handler)
{
LinkedListNode<PlayerEventHandlerSlot> node = event_handlers.First;
while (node != null) {
if (node.Value.Handler == handler) {
return node;
}
node = node.Next;
}
return null;
}
public void DisconnectEvent (PlayerEventHandler handler)
{
lock (event_handlers) {
LinkedListNode<PlayerEventHandlerSlot> node = FindEventNode (handler);
if (node != null) {
event_handlers.Remove (node);
}
}
}
public void ModifyEvent (PlayerEvent eventMask, PlayerEventHandler handler)
{
lock (event_handlers) {
VerifyEventMask (eventMask);
LinkedListNode<PlayerEventHandlerSlot> node = FindEventNode (handler);
if (node != null) {
PlayerEventHandlerSlot slot = node.Value;
slot.EventMask = eventMask;
node.Value = slot;
}
}
}
private void RaiseEvent (PlayerEventArgs args)
{
lock (event_handlers) {
if (args.Event == PlayerEvent.StateChange && args is PlayerEventStateChangeArgs) {
HandleStateChange ((PlayerEventStateChangeArgs)args);
}
LinkedListNode<PlayerEventHandlerSlot> node = event_handlers.First;
while (node != null) {
if ((node.Value.EventMask & args.Event) == args.Event) {
try {
node.Value.Handler (args);
} catch (Exception e) {
Log.Error (String.Format ("Error running PlayerEngine handler for {0}", args.Event), e);
}
}
node = node.Next;
}
}
}
#endregion
string IService.ServiceName {
get { return "PlayerEngine"; }
}
IDBusExportable IDBusExportable.Parent {
get { return null; }
}
public static readonly SchemaEntry<int> VolumeSchema = new SchemaEntry<int> (
"player_engine", "volume",
80,
"Volume",
"Volume of playback relative to mixer output"
);
public static readonly SchemaEntry<string> EngineSchema = new SchemaEntry<string> (
"player_engine", "backend",
"helix-remote",
"Backend",
"Name of media playback engine backend"
);
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.1.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace ApplicationGateway
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// NetworkSecurityGroupsOperations operations.
/// </summary>
public partial interface INetworkSecurityGroupsOperations
{
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkSecurityGroup>> GetWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a network security group in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkSecurityGroup>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a network security group in the specified
/// resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NetworkSecurityGroup>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NetworkSecurityGroup>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using EasyNetQ.Events;
using EasyNetQ.Internals;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using RabbitMQ.Client.Exceptions;
namespace EasyNetQ.Persistent;
/// <inheritdoc />
public class PersistentChannel : IPersistentChannel
{
private const string RequestPipeliningForbiddenMessage = "Pipelining of requests forbidden";
private const int MinRetryTimeoutMs = 50;
private const int MaxRetryTimeoutMs = 5000;
private readonly IPersistentConnection connection;
private readonly CancellationTokenSource disposeCts = new();
private readonly IEventBus eventBus;
private readonly AsyncLock mutex = new();
private readonly PersistentChannelOptions options;
private volatile IModel initializedChannel;
private volatile bool disposed;
/// <summary>
/// Creates PersistentChannel
/// </summary>
/// <param name="options">The channel options</param>
/// <param name="connection">The connection</param>
/// <param name="eventBus">The event bus</param>
public PersistentChannel(in PersistentChannelOptions options, IPersistentConnection connection, IEventBus eventBus)
{
Preconditions.CheckNotNull(connection, nameof(connection));
Preconditions.CheckNotNull(eventBus, nameof(eventBus));
this.connection = connection;
this.eventBus = eventBus;
this.options = options;
}
/// <inheritdoc />
public async Task<T> InvokeChannelActionAsync<T>(
Func<IModel, T> channelAction, CancellationToken cancellationToken
)
{
Preconditions.CheckNotNull(channelAction, nameof(channelAction));
if (disposed)
throw new ObjectDisposedException(nameof(PersistentChannel));
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, disposeCts.Token);
using var _ = await mutex.AcquireAsync(cts.Token).ConfigureAwait(false);
var retryTimeoutMs = MinRetryTimeoutMs;
while (true)
{
cts.Token.ThrowIfCancellationRequested();
try
{
var channel = initializedChannel ??= CreateChannel();
return channelAction(channel);
}
catch (Exception exception)
{
var exceptionVerdict = GetExceptionVerdict(exception);
if (exceptionVerdict.CloseChannel)
CloseChannel();
if (exceptionVerdict.Rethrow)
throw;
}
await Task.Delay(retryTimeoutMs, cts.Token).ConfigureAwait(false);
retryTimeoutMs = Math.Min(retryTimeoutMs * 2, MaxRetryTimeoutMs);
}
}
/// <inheritdoc />
public void Dispose()
{
if (disposed)
return;
disposed = true;
disposeCts.Cancel();
mutex.Dispose();
CloseChannel();
disposeCts.Dispose();
}
private IModel CreateChannel()
{
var channel = connection.CreateModel();
AttachChannelEvents(channel);
return channel;
}
private void CloseChannel()
{
var channel = Interlocked.Exchange(ref initializedChannel, null);
if (channel == null)
return;
channel.Close();
DetachChannelEvents(channel);
channel.Dispose();
}
private void AttachChannelEvents(IModel channel)
{
if (options.PublisherConfirms)
{
channel.ConfirmSelect();
channel.BasicAcks += OnAck;
channel.BasicNacks += OnNack;
}
channel.BasicReturn += OnReturn;
channel.ModelShutdown += OnChannelShutdown;
if (channel is IRecoverable recoverable)
recoverable.Recovery += OnChannelRecovered;
else
throw new NotSupportedException("Non-recoverable channel is not supported");
}
private void DetachChannelEvents(IModel channel)
{
if (channel is IRecoverable recoverable)
recoverable.Recovery -= OnChannelRecovered;
channel.ModelShutdown -= OnChannelShutdown;
channel.BasicReturn -= OnReturn;
if (!options.PublisherConfirms)
return;
channel.BasicNacks -= OnNack;
channel.BasicAcks -= OnAck;
}
private void OnChannelRecovered(object sender, EventArgs e)
{
eventBus.Publish(new ChannelRecoveredEvent((IModel)sender));
}
private void OnChannelShutdown(object sender, ShutdownEventArgs e)
{
eventBus.Publish(new ChannelShutdownEvent((IModel)sender));
}
private void OnReturn(object sender, BasicReturnEventArgs args)
{
var messageProperties = new MessageProperties();
messageProperties.CopyFrom(args.BasicProperties);
var messageReturnedInfo = new MessageReturnedInfo(args.Exchange, args.RoutingKey, args.ReplyText);
var @event = new ReturnedMessageEvent(
(IModel)sender,
args.Body,
messageProperties,
messageReturnedInfo
);
eventBus.Publish(@event);
}
private void OnAck(object sender, BasicAckEventArgs args)
{
eventBus.Publish(MessageConfirmationEvent.Ack((IModel)sender, args.DeliveryTag, args.Multiple));
}
private void OnNack(object sender, BasicNackEventArgs args)
{
eventBus.Publish(MessageConfirmationEvent.Nack((IModel)sender, args.DeliveryTag, args.Multiple));
}
private static ExceptionVerdict GetExceptionVerdict(Exception exception)
{
switch (exception)
{
case OperationInterruptedException e:
return e.ShutdownReason?.ReplyCode switch
{
AmqpErrorCodes.ConnectionClosed => ExceptionVerdict.Suppress,
AmqpErrorCodes.AccessRefused => ExceptionVerdict.ThrowAndCloseChannel,
AmqpErrorCodes.NotFound => ExceptionVerdict.ThrowAndCloseChannel,
AmqpErrorCodes.ResourceLocked => ExceptionVerdict.ThrowAndCloseChannel,
AmqpErrorCodes.PreconditionFailed => ExceptionVerdict.ThrowAndCloseChannel,
AmqpErrorCodes.InternalErrors => ExceptionVerdict.SuppressAndCloseChannel,
_ => ExceptionVerdict.Throw
};
case NotSupportedException e:
var isRequestPipeliningForbiddenException = e.Message.Contains(RequestPipeliningForbiddenMessage);
return isRequestPipeliningForbiddenException
? ExceptionVerdict.SuppressAndCloseChannel
: ExceptionVerdict.Throw;
case EasyNetQException:
return ExceptionVerdict.Suppress;
default:
return ExceptionVerdict.Throw;
}
}
private readonly struct ExceptionVerdict
{
public static ExceptionVerdict Suppress { get; } = new(false, false);
public static ExceptionVerdict SuppressAndCloseChannel { get; } = new(false, true);
public static ExceptionVerdict Throw { get; } = new(true, false);
public static ExceptionVerdict ThrowAndCloseChannel { get; } = new(true, true);
private ExceptionVerdict(bool rethrow, bool closeChannel)
{
Rethrow = rethrow;
CloseChannel = closeChannel;
}
public bool Rethrow { get; }
public bool CloseChannel { get; }
}
}
| |
/*
* Copyright 2014 Amazon.com,
* Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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.Collections.Generic;
using System.Diagnostics;
using com.amazon.device.iap.cpt.json;
namespace com.amazon.device.iap.cpt
{
public abstract partial class AmazonIapV2Impl
{
private abstract class AmazonIapV2Base : AmazonIapV2Impl
{
static readonly System.Object startLock = new System.Object();
static volatile bool startCalled = false;
protected void Start ()
{
if(startCalled)
{
return;
}
lock(startLock)
{
if(startCalled == false)
{
Init();
RegisterCallback();
RegisterEventListener();
RegisterCrossPlatformTool();
startCalled = true;
}
}
}
protected abstract void Init();
protected abstract void RegisterCallback();
protected abstract void RegisterEventListener();
protected abstract void RegisterCrossPlatformTool();
public AmazonIapV2Base()
{
logger = new AmazonLogger(this.GetType().Name);
}
public override void UnityFireEvent(string jsonMessage)
{
AmazonIapV2Impl.FireEvent(jsonMessage);
}
public override RequestOutput GetUserData()
{
Start();
return RequestOutput.CreateFromJson(GetUserDataJson("{}"));
}
private string GetUserDataJson(string jsonMessage)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string result = NativeGetUserDataJson(jsonMessage);
stopwatch.Stop();
logger.Debug(string.Format("Successfully called native code in {0} ms", stopwatch.ElapsedMilliseconds));
return result;
}
protected abstract string NativeGetUserDataJson(string jsonMessage);
public override RequestOutput Purchase(SkuInput skuInput)
{
Start();
return RequestOutput.CreateFromJson(PurchaseJson(skuInput.ToJson()));
}
private string PurchaseJson(string jsonMessage)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string result = NativePurchaseJson(jsonMessage);
stopwatch.Stop();
logger.Debug(string.Format("Successfully called native code in {0} ms", stopwatch.ElapsedMilliseconds));
return result;
}
protected abstract string NativePurchaseJson(string jsonMessage);
public override RequestOutput GetProductData(SkusInput skusInput)
{
Start();
return RequestOutput.CreateFromJson(GetProductDataJson(skusInput.ToJson()));
}
private string GetProductDataJson(string jsonMessage)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string result = NativeGetProductDataJson(jsonMessage);
stopwatch.Stop();
logger.Debug(string.Format("Successfully called native code in {0} ms", stopwatch.ElapsedMilliseconds));
return result;
}
protected abstract string NativeGetProductDataJson(string jsonMessage);
public override RequestOutput GetPurchaseUpdates(ResetInput resetInput)
{
Start();
return RequestOutput.CreateFromJson(GetPurchaseUpdatesJson(resetInput.ToJson()));
}
private string GetPurchaseUpdatesJson(string jsonMessage)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string result = NativeGetPurchaseUpdatesJson(jsonMessage);
stopwatch.Stop();
logger.Debug(string.Format("Successfully called native code in {0} ms", stopwatch.ElapsedMilliseconds));
return result;
}
protected abstract string NativeGetPurchaseUpdatesJson(string jsonMessage);
public override void NotifyFulfillment(NotifyFulfillmentInput notifyFulfillmentInput)
{
Start();
Jsonable.CheckForErrors(Json.Deserialize(NotifyFulfillmentJson(notifyFulfillmentInput.ToJson())) as Dictionary<string, object>);
}
private string NotifyFulfillmentJson(string jsonMessage)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
string result = NativeNotifyFulfillmentJson(jsonMessage);
stopwatch.Stop();
logger.Debug(string.Format("Successfully called native code in {0} ms", stopwatch.ElapsedMilliseconds));
return result;
}
protected abstract string NativeNotifyFulfillmentJson(string jsonMessage);
public override void AddGetUserDataResponseListener(GetUserDataResponseDelegate responseDelegate)
{
Start();
string eventId = "getUserDataResponse";
lock(eventLock)
{
if (eventListeners.ContainsKey(eventId))
{
eventListeners[eventId].Add(new GetUserDataResponseDelegator (responseDelegate));
}
else
{
var list = new List<IDelegator>();
list.Add(new GetUserDataResponseDelegator(responseDelegate));
eventListeners.Add(eventId, list);
}
}
}
public override void RemoveGetUserDataResponseListener(GetUserDataResponseDelegate responseDelegate)
{
Start();
string eventId = "getUserDataResponse";
lock(eventLock)
{
if (eventListeners.ContainsKey(eventId))
{
foreach(GetUserDataResponseDelegator delegator in eventListeners[eventId])
{
if(delegator.responseDelegate == responseDelegate)
{
eventListeners[eventId].Remove(delegator);
return;
}
}
}
}
}
public override void AddPurchaseResponseListener(PurchaseResponseDelegate responseDelegate)
{
Start();
string eventId = "purchaseResponse";
lock(eventLock)
{
if (eventListeners.ContainsKey(eventId))
{
eventListeners[eventId].Add(new PurchaseResponseDelegator (responseDelegate));
}
else
{
var list = new List<IDelegator>();
list.Add(new PurchaseResponseDelegator(responseDelegate));
eventListeners.Add(eventId, list);
}
}
}
public override void RemovePurchaseResponseListener(PurchaseResponseDelegate responseDelegate)
{
Start();
string eventId = "purchaseResponse";
lock(eventLock)
{
if (eventListeners.ContainsKey(eventId))
{
foreach(PurchaseResponseDelegator delegator in eventListeners[eventId])
{
if(delegator.responseDelegate == responseDelegate)
{
eventListeners[eventId].Remove(delegator);
return;
}
}
}
}
}
public override void AddGetProductDataResponseListener(GetProductDataResponseDelegate responseDelegate)
{
Start();
string eventId = "getProductDataResponse";
lock(eventLock)
{
if (eventListeners.ContainsKey(eventId))
{
eventListeners[eventId].Add(new GetProductDataResponseDelegator (responseDelegate));
}
else
{
var list = new List<IDelegator>();
list.Add(new GetProductDataResponseDelegator(responseDelegate));
eventListeners.Add(eventId, list);
}
}
}
public override void RemoveGetProductDataResponseListener(GetProductDataResponseDelegate responseDelegate)
{
Start();
string eventId = "getProductDataResponse";
lock(eventLock)
{
if (eventListeners.ContainsKey(eventId))
{
foreach(GetProductDataResponseDelegator delegator in eventListeners[eventId])
{
if(delegator.responseDelegate == responseDelegate)
{
eventListeners[eventId].Remove(delegator);
return;
}
}
}
}
}
public override void AddGetPurchaseUpdatesResponseListener(GetPurchaseUpdatesResponseDelegate responseDelegate)
{
Start();
string eventId = "getPurchaseUpdatesResponse";
lock(eventLock)
{
if (eventListeners.ContainsKey(eventId))
{
eventListeners[eventId].Add(new GetPurchaseUpdatesResponseDelegator (responseDelegate));
}
else
{
var list = new List<IDelegator>();
list.Add(new GetPurchaseUpdatesResponseDelegator(responseDelegate));
eventListeners.Add(eventId, list);
}
}
}
public override void RemoveGetPurchaseUpdatesResponseListener(GetPurchaseUpdatesResponseDelegate responseDelegate)
{
Start();
string eventId = "getPurchaseUpdatesResponse";
lock(eventLock)
{
if (eventListeners.ContainsKey(eventId))
{
foreach(GetPurchaseUpdatesResponseDelegator delegator in eventListeners[eventId])
{
if(delegator.responseDelegate == responseDelegate)
{
eventListeners[eventId].Remove(delegator);
return;
}
}
}
}
}
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System;
using System.IO;
using System.Runtime;
using System.Threading.Tasks;
using System.Xml;
sealed class XmlByteStreamWriter : XmlDictionaryWriter
{
bool ownsStream;
ByteStreamWriterState state;
Stream stream;
public XmlByteStreamWriter(Stream stream, bool ownsStream)
{
Fx.Assert(stream != null, "stream is null");
this.stream = stream;
this.ownsStream = ownsStream;
this.state = ByteStreamWriterState.Start;
}
public override WriteState WriteState
{
get { return ByteStreamWriterStateToWriteState(this.state); }
}
public override void Close()
{
if (this.state != ByteStreamWriterState.Closed)
{
try
{
if (ownsStream)
{
this.stream.Close();
}
this.stream = null;
}
finally
{
this.state = ByteStreamWriterState.Closed;
}
}
}
void EnsureWriteBase64State(byte[] buffer, int index, int count)
{
ThrowIfClosed();
ByteStreamMessageUtility.EnsureByteBoundaries(buffer, index, count, false);
if (this.state != ByteStreamWriterState.Content && this.state != ByteStreamWriterState.StartElement)
{
throw FxTrace.Exception.AsError(
new InvalidOperationException(SR.XmlWriterMustBeInElement(ByteStreamWriterStateToWriteState(this.state))));
}
}
public override void Flush()
{
ThrowIfClosed();
this.stream.Flush();
}
void InternalWriteEndElement()
{
ThrowIfClosed();
if (this.state != ByteStreamWriterState.StartElement && this.state != ByteStreamWriterState.Content)
{
throw FxTrace.Exception.AsError(
new InvalidOperationException(SR.XmlUnexpectedEndElement));
}
this.state = ByteStreamWriterState.EndElement;
}
public override string LookupPrefix(string ns)
{
if (ns == string.Empty)
{
return string.Empty;
}
else if (ns == ByteStreamMessageUtility.XmlNamespace)
{
return "xml";
}
else if (ns == ByteStreamMessageUtility.XmlNamespaceNamespace)
{
return "xmlns";
}
else
{
return null;
}
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
EnsureWriteBase64State(buffer, index, count);
this.stream.Write(buffer, index, count);
this.state = ByteStreamWriterState.Content;
}
public override Task WriteBase64Async(byte[] buffer, int index, int count)
{
return Task.Factory.FromAsync(this.BeginWriteBase64, this.EndWriteBase64, buffer, index, count, null);
}
internal IAsyncResult BeginWriteBase64(byte[] buffer, int index, int count, AsyncCallback callback, object state)
{
EnsureWriteBase64State(buffer, index, count);
return new WriteBase64AsyncResult(buffer, index, count, this, callback, state);
}
internal void EndWriteBase64(IAsyncResult result)
{
WriteBase64AsyncResult.End(result);
}
class WriteBase64AsyncResult : AsyncResult
{
XmlByteStreamWriter writer;
public WriteBase64AsyncResult(byte[] buffer, int index, int count, XmlByteStreamWriter writer, AsyncCallback callback, object state)
: base(callback, state)
{
this.writer = writer;
IAsyncResult result = writer.stream.BeginWrite(buffer, index, count, PrepareAsyncCompletion(HandleWriteBase64), this);
bool completeSelf = SyncContinue(result);
if (completeSelf)
{
this.Complete(true);
}
}
static bool HandleWriteBase64(IAsyncResult result)
{
WriteBase64AsyncResult thisPtr = (WriteBase64AsyncResult)result.AsyncState;
thisPtr.writer.stream.EndWrite(result);
thisPtr.writer.state = ByteStreamWriterState.Content;
return true;
}
public static void End(IAsyncResult result)
{
AsyncResult.End<WriteBase64AsyncResult>(result);
}
}
public override void WriteCData(string text)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteCharEntity(char ch)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteChars(char[] buffer, int index, int count)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteComment(string text)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteEndAttribute()
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteEndDocument()
{
return;
}
public override void WriteEndElement()
{
this.InternalWriteEndElement();
}
public override void WriteEntityRef(string name)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteFullEndElement()
{
this.InternalWriteEndElement();
}
public override void WriteProcessingInstruction(string name, string text)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteRaw(string data)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteRaw(char[] buffer, int index, int count)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteStartDocument(bool standalone)
{
ThrowIfClosed();
}
public override void WriteStartDocument()
{
ThrowIfClosed();
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
ThrowIfClosed();
if (this.state != ByteStreamWriterState.Start)
{
throw FxTrace.Exception.AsError(
new InvalidOperationException(SR.ByteStreamWriteStartElementAlreadyCalled));
}
if (!string.IsNullOrEmpty(prefix) || !string.IsNullOrEmpty(ns) || localName != ByteStreamMessageUtility.StreamElementName)
{
throw FxTrace.Exception.AsError(
new XmlException(SR.XmlStartElementNameExpected(ByteStreamMessageUtility.StreamElementName, localName)));
}
this.state = ByteStreamWriterState.StartElement;
}
public override void WriteString(string text)
{
// no state checks here - WriteBase64 will take care of this.
byte[] buffer = Convert.FromBase64String(text);
WriteBase64(buffer, 0, buffer.Length);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
public override void WriteWhitespace(string ws)
{
throw FxTrace.Exception.AsError(new NotSupportedException());
}
void ThrowIfClosed()
{
if (this.state == ByteStreamWriterState.Closed)
{
throw FxTrace.Exception.AsError(
new InvalidOperationException(SR.XmlWriterClosed));
}
}
static WriteState ByteStreamWriterStateToWriteState(ByteStreamWriterState byteStreamWriterState)
{
// Converts the internal ByteStreamWriterState to an Xml WriteState
switch (byteStreamWriterState)
{
case ByteStreamWriterState.Start:
return WriteState.Start;
case ByteStreamWriterState.StartElement:
return WriteState.Element;
case ByteStreamWriterState.Content:
return WriteState.Content;
case ByteStreamWriterState.EndElement:
return WriteState.Element;
case ByteStreamWriterState.Closed:
return WriteState.Closed;
default:
return WriteState.Error;
}
}
enum ByteStreamWriterState
{
Start,
StartElement,
Content,
EndElement,
Closed
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Test.Common;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
public class HttpClientTest
{
[Fact]
public void Dispose_MultipleTimes_Success()
{
var client = new HttpClient();
client.Dispose();
client.Dispose();
}
[Fact]
public void DefaultRequestHeaders_Idempotent()
{
using (var client = new HttpClient())
{
Assert.NotNull(client.DefaultRequestHeaders);
Assert.Same(client.DefaultRequestHeaders, client.DefaultRequestHeaders);
}
}
[Fact]
public void BaseAddress_Roundtrip_Equal()
{
using (var client = new HttpClient())
{
Assert.Null(client.BaseAddress);
Uri uri = new Uri(CreateFakeUri());
client.BaseAddress = uri;
Assert.Equal(uri, client.BaseAddress);
client.BaseAddress = null;
Assert.Null(client.BaseAddress);
}
}
[Fact]
public void BaseAddress_InvalidUri_Throws()
{
using (var client = new HttpClient())
{
Assert.Throws<ArgumentException>("value", () => client.BaseAddress = new Uri("ftp://onlyhttpsupported"));
Assert.Throws<ArgumentException>("value", () => client.BaseAddress = new Uri("/onlyabsolutesupported", UriKind.Relative));
}
}
[Fact]
public void Timeout_Roundtrip_Equal()
{
using (var client = new HttpClient())
{
client.Timeout = Timeout.InfiniteTimeSpan;
Assert.Equal(Timeout.InfiniteTimeSpan, client.Timeout);
client.Timeout = TimeSpan.FromSeconds(1);
Assert.Equal(TimeSpan.FromSeconds(1), client.Timeout);
}
}
[Fact]
public void Timeout_OutOfRange_Throws()
{
using (var client = new HttpClient())
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(-2));
Assert.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(0));
Assert.Throws<ArgumentOutOfRangeException>("value", () => client.Timeout = TimeSpan.FromSeconds(int.MaxValue));
}
}
[Fact]
public void MaxResponseContentBufferSize_Roundtrip_Equal()
{
using (var client = new HttpClient())
{
client.MaxResponseContentBufferSize = 1;
Assert.Equal(1, client.MaxResponseContentBufferSize);
client.MaxResponseContentBufferSize = int.MaxValue;
Assert.Equal(int.MaxValue, client.MaxResponseContentBufferSize);
}
}
[Fact]
public void MaxResponseContentBufferSize_OutOfRange_Throws()
{
using (var client = new HttpClient())
{
Assert.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = -1);
Assert.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = 0);
Assert.Throws<ArgumentOutOfRangeException>("value", () => client.MaxResponseContentBufferSize = 1 + (long)int.MaxValue);
}
}
[Fact]
public async Task MaxResponseContentBufferSize_TooSmallForContent_Throws()
{
using (var client = new HttpClient())
{
client.MaxResponseContentBufferSize = 1;
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(HttpTestServers.RemoteEchoServer));
}
}
[Fact]
public async Task Properties_CantChangeAfterOperation_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage()))))
{
(await client.GetAsync(CreateFakeUri())).Dispose();
Assert.Throws<InvalidOperationException>(() => client.BaseAddress = null);
Assert.Throws<InvalidOperationException>(() => client.Timeout = TimeSpan.FromSeconds(1));
Assert.Throws<InvalidOperationException>(() => client.MaxResponseContentBufferSize = 1);
}
}
[Theory]
[InlineData(null)]
[InlineData("/something.html")]
public void GetAsync_NoBaseAddress_InvalidUri_ThrowsException(string uri)
{
using (var client = new HttpClient())
{
Assert.Throws<InvalidOperationException>(() => { client.GetAsync(uri == null ? null : new Uri(uri, UriKind.RelativeOrAbsolute)); });
}
}
[Theory]
[InlineData(null)]
[InlineData("/")]
public async Task GetAsync_BaseAddress_ValidUri_Success(string uri)
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage()))))
{
client.BaseAddress = new Uri(CreateFakeUri());
using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task GetContentAsync_ErrorStatusCode_ExpectedExceptionThrown(bool withResponseContent)
{
using (var client = new HttpClient(new CustomResponseHandler(
(r,c) => Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = withResponseContent ? new ByteArrayContent(new byte[1]) : null
}))))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetByteArrayAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStreamAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_NullResponse_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult<HttpResponseMessage>(null))))
{
await Assert.ThrowsAnyAsync<InvalidOperationException>(() => client.GetStringAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_NullResponseContent_ReturnsDefaultValue()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult(new HttpResponseMessage() { Content = null }))))
{
Assert.Same(string.Empty, await client.GetStringAsync(CreateFakeUri()));
Assert.Same(Array.Empty<byte>(), await client.GetByteArrayAsync(CreateFakeUri()));
Assert.Same(Stream.Null, await client.GetStreamAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetContentAsync_SerializingContentThrows_Synchronous_Throws()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler(
(r, c) => Task.FromResult(new HttpResponseMessage() { Content = new CustomContent(stream => { throw e; }) }))))
{
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStringAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetByteArrayAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStreamAsync(CreateFakeUri())));
}
}
[Fact]
public async Task GetContentAsync_SerializingContentThrows_Asynchronous_Throws()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler(
(r, c) => Task.FromResult(new HttpResponseMessage() { Content = new CustomContent(stream => Task.FromException(e)) }))))
{
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStringAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetByteArrayAsync(CreateFakeUri())));
Assert.Same(e, await Assert.ThrowsAsync<FormatException>(() => client.GetStreamAsync(CreateFakeUri())));
}
}
[Fact]
public async Task GetAsync_InvalidUrl_ExpectedExceptionThrown()
{
using (var client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(CreateFakeUri()));
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetStringAsync(CreateFakeUri()));
}
}
[Fact]
public async Task GetPutPostDeleteAsync_Canceled_Throws()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
var content = new ByteArrayContent(new byte[1]);
var cts = new CancellationTokenSource();
Task t1 = client.GetAsync(CreateFakeUri(), cts.Token);
Task t2 = client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead, cts.Token);
Task t3 = client.PostAsync(CreateFakeUri(), content, cts.Token);
Task t4 = client.PutAsync(CreateFakeUri(), content, cts.Token);
Task t5 = client.DeleteAsync(CreateFakeUri(), cts.Token);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t1);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t2);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t3);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t4);
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t5);
}
}
[Fact]
public async Task GetPutPostDeleteAsync_Success()
{
Action<HttpResponseMessage> verify = message => { using (message) Assert.Equal(HttpStatusCode.OK, message.StatusCode); };
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
verify(await client.GetAsync(CreateFakeUri()));
verify(await client.GetAsync(CreateFakeUri(), CancellationToken.None));
verify(await client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead));
verify(await client.GetAsync(CreateFakeUri(), HttpCompletionOption.ResponseContentRead, CancellationToken.None));
verify(await client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])));
verify(await client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1]), CancellationToken.None));
verify(await client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])));
verify(await client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1]), CancellationToken.None));
verify(await client.DeleteAsync(CreateFakeUri()));
verify(await client.DeleteAsync(CreateFakeUri(), CancellationToken.None));
}
}
[Fact]
public void GetAsync_CustomException_Synchronous_ThrowsException()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler((r, c) => { throw e; })))
{
FormatException thrown = Assert.Throws<FormatException>(() => { client.GetAsync(CreateFakeUri()); });
Assert.Same(e, thrown);
}
}
[Fact]
public async Task GetAsync_CustomException_Asynchronous_ThrowsException()
{
var e = new FormatException();
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromException<HttpResponseMessage>(e))))
{
FormatException thrown = await Assert.ThrowsAsync<FormatException>(() => client.GetAsync(CreateFakeUri()));
Assert.Same(e, thrown);
}
}
[Fact]
public void SendAsync_NullRequest_ThrowsException()
{
using (var client = new HttpClient(new CustomResponseHandler((r,c) => Task.FromResult<HttpResponseMessage>(null))))
{
Assert.Throws<ArgumentNullException>("request", () => { client.SendAsync(null); });
}
}
[Fact]
public async Task SendAsync_DuplicateRequest_ThrowsException()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
using (var request = new HttpRequestMessage(HttpMethod.Get, CreateFakeUri()))
{
(await client.SendAsync(request)).Dispose();
Assert.Throws<InvalidOperationException>(() => { client.SendAsync(request); });
}
}
[Fact]
public async Task SendAsync_RequestContentDisposed()
{
var content = new ByteArrayContent(new byte[1]);
using (var request = new HttpRequestMessage(HttpMethod.Get, CreateFakeUri()) { Content = content })
using (var client = new HttpClient(new CustomResponseHandler((r, c) => Task.FromResult(new HttpResponseMessage()))))
{
await client.SendAsync(request);
Assert.Throws<ObjectDisposedException>(() => { content.ReadAsStringAsync(); });
}
}
[Fact]
public void Dispose_UseAfterDispose_Throws()
{
var client = new HttpClient();
client.Dispose();
Assert.Throws<ObjectDisposedException>(() => client.BaseAddress = null);
Assert.Throws<ObjectDisposedException>(() => client.CancelPendingRequests());
Assert.Throws<ObjectDisposedException>(() => { client.DeleteAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetByteArrayAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetStreamAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.GetStringAsync(CreateFakeUri()); });
Assert.Throws<ObjectDisposedException>(() => { client.PostAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])); });
Assert.Throws<ObjectDisposedException>(() => { client.PutAsync(CreateFakeUri(), new ByteArrayContent(new byte[1])); });
Assert.Throws<ObjectDisposedException>(() => { client.SendAsync(new HttpRequestMessage(HttpMethod.Get, CreateFakeUri())); });
Assert.Throws<ObjectDisposedException>(() => { client.Timeout = TimeSpan.FromSeconds(1); });
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void CancelAllPending_AllPendingOperationsCanceled(bool withInfiniteTimeout)
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
if (withInfiniteTimeout)
{
client.Timeout = Timeout.InfiniteTimeSpan;
}
Task<HttpResponseMessage>[] tasks = Enumerable.Range(0, 3).Select(_ => client.GetAsync(CreateFakeUri())).ToArray();
client.CancelPendingRequests();
Assert.All(tasks, task => Assert.ThrowsAny<OperationCanceledException>(() => task.GetAwaiter().GetResult()));
}
}
[Fact]
public void Timeout_TooShort_AllPendingOperationsCanceled()
{
using (var client = new HttpClient(new CustomResponseHandler((r, c) => WhenCanceled<HttpResponseMessage>(c))))
{
client.Timeout = TimeSpan.FromMilliseconds(1);
Task<HttpResponseMessage>[] tasks = Enumerable.Range(0, 3).Select(_ => client.GetAsync(CreateFakeUri())).ToArray();
Assert.All(tasks, task => Assert.ThrowsAny<OperationCanceledException>(() => task.GetAwaiter().GetResult()));
}
}
[Fact]
[OuterLoop]
public void Timeout_SetTo60AndGetResponseFromServerWhichTakes40_Success()
{
// TODO: This is a placeholder until GitHub Issue #2383 gets resolved.
const string SlowServer = "http://httpbin.org/drip?numbytes=1&duration=1&delay=40&code=200";
using (var client = new HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(60);
var response = client.GetAsync(SlowServer).GetAwaiter().GetResult();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
/// <remarks>
/// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler
/// DiagnosticSources, since the global logging mechanism makes them conflict inherently.
/// </remarks>
[Fact]
public void SendAsync_ExpectedDiagnosticSourceLogging()
{
bool requestLogged = false;
Guid requestGuid = Guid.Empty;
bool responseLogged = false;
Guid responseGuid = Guid.Empty;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(
kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request");
requestGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId");
requestLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Response"))
{
Assert.NotNull(kvp.Value);
GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response");
responseGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId");
responseLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
diagnosticListenerObserver.Enable();
using (var client = new HttpClient())
{
var response = client.GetAsync(HttpTestServers.RemoteEchoServer).Result;
}
Assert.True(requestLogged, "Request was not logged.");
// Poll with a timeout since logging response is not synchronized with returning a response.
WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1), "Response was not logged within 1 second timeout.");
Assert.Equal(requestGuid, responseGuid);
diagnosticListenerObserver.Disable();
}
}
/// <remarks>
/// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler
/// DiagnosticSources, since the global logging mechanism makes them conflict inherently.
/// </remarks>
[Fact]
public void SendAsync_ExpectedDiagnosticSourceNoLogging()
{
bool requestLogged = false;
bool responseLogged = false;
var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(
kvp =>
{
if (kvp.Key.Equals("System.Net.Http.Request"))
{
requestLogged = true;
}
else if (kvp.Key.Equals("System.Net.Http.Response"))
{
responseLogged = true;
}
});
using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver))
{
using (var client = new HttpClient())
{
var response = client.GetAsync(HttpTestServers.RemoteEchoServer).Result;
}
Assert.False(requestLogged, "Request was logged while logging disabled.");
WaitForFalse(() => responseLogged, TimeSpan.FromSeconds(1), "Response was logged while logging disabled.");
}
}
private void WaitForTrue(Func<bool> p, TimeSpan timeout, string message)
{
// Assert that spin doesn't time out.
Assert.True(System.Threading.SpinWait.SpinUntil(p, timeout), message);
}
private void WaitForFalse(Func<bool> p, TimeSpan timeout, string message)
{
// Assert that spin times out.
Assert.False(System.Threading.SpinWait.SpinUntil(p, timeout), message);
}
private T GetPropertyValueFromAnonymousTypeInstance<T>(object obj, string propertyName)
{
Type t = obj.GetType();
PropertyInfo p = t.GetRuntimeProperty(propertyName);
object propertyValue = p.GetValue(obj);
Assert.NotNull(propertyValue);
Assert.IsAssignableFrom<T>(propertyValue);
return (T)propertyValue;
}
private static string CreateFakeUri() => $"http://{Guid.NewGuid().ToString("N")}";
private static async Task<T> WhenCanceled<T>(CancellationToken cancellationToken)
{
await Task.Delay(-1, cancellationToken);
return default(T);
}
private sealed class CustomResponseHandler : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _func;
public CustomResponseHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> func) { _func = func; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return _func(request, cancellationToken);
}
}
private sealed class CustomContent : HttpContent
{
private readonly Func<Stream, Task> _func;
public CustomContent(Func<Stream, Task> func) { _func = func; }
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
return _func(stream);
}
protected override bool TryComputeLength(out long length)
{
length = 0;
return false;
}
}
}
}
| |
// ReSharper disable once CheckNamespace
namespace Fluent
{
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using Fluent.Internal;
/// <summary>
/// Represent panel with ribbon group.
/// It is automatically adjusting size of controls
/// </summary>
public class RibbonGroupsContainer : Panel, IScrollInfo
{
#region Reduce Order
/// <summary>
/// Gets or sets reduce order of group in the ribbon panel.
/// It must be enumerated with comma from the first to reduce to
/// the last to reduce (use Control.Name as group name in the enum).
/// Enclose in parentheses as (Control.Name) to reduce/enlarge
/// scalable elements in the given group
/// </summary>
public string ReduceOrder
{
get { return (string)this.GetValue(ReduceOrderProperty); }
set { this.SetValue(ReduceOrderProperty, value); }
}
/// <summary>
/// Using a DependencyProperty as the backing store for ReduceOrder.
/// This enables animation, styling, binding, etc...
/// </summary>
public static readonly DependencyProperty ReduceOrderProperty =
DependencyProperty.Register(nameof(ReduceOrder), typeof(string), typeof(RibbonGroupsContainer), new PropertyMetadata(ReduceOrderPropertyChanged));
// handles ReduseOrder property changed
private static void ReduceOrderPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ribbonPanel = (RibbonGroupsContainer)d;
for (var i = ribbonPanel.reduceOrderIndex; i < ribbonPanel.reduceOrder.Length - 1; i++)
{
ribbonPanel.IncreaseGroupBoxSize(ribbonPanel.reduceOrder[i]);
}
ribbonPanel.reduceOrder = ((string)e.NewValue).Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
var newReduceOrderIndex = ribbonPanel.reduceOrder.Length - 1;
ribbonPanel.reduceOrderIndex = newReduceOrderIndex;
ribbonPanel.InvalidateMeasure();
ribbonPanel.InvalidateArrange();
}
#endregion
#region Fields
private string[] reduceOrder = new string[0];
private int reduceOrderIndex;
#endregion
#region Initialization
/// <summary>
/// Default constructor
/// </summary>
public RibbonGroupsContainer()
{
this.Focusable = false;
}
#endregion
#region Layout Overridings
/// <summary>
/// Returns a collection of the panel's UIElements.
/// </summary>
/// <param name="logicalParent">The logical parent of the collection to be created.</param>
/// <returns>Returns an ordered collection of elements that have the specified logical parent.</returns>
protected override UIElementCollection CreateUIElementCollection(FrameworkElement logicalParent)
{
return new UIElementCollection(this, /*Parent as FrameworkElement*/this);
}
/// <summary>
/// Measures all of the RibbonGroupBox, and resize them appropriately
/// to fit within the available room
/// </summary>
/// <param name="availableSize">The available size that this element can give to child elements.</param>
/// <returns>The size that the groups container determines it needs during
/// layout, based on its calculations of child element sizes.
/// </returns>
protected override Size MeasureOverride(Size availableSize)
{
var desiredSize = this.GetChildrenDesiredSizeIntermediate();
if (this.reduceOrder.Length == 0)
{
this.VerifyScrollData(availableSize.Width, desiredSize.Width);
return desiredSize;
}
// If we have more available space - try to expand groups
while (desiredSize.Width <= availableSize.Width)
{
var hasMoreVariants = this.reduceOrderIndex < this.reduceOrder.Length - 1;
if (hasMoreVariants == false)
{
break;
}
// Increase size of another item
this.reduceOrderIndex++;
this.IncreaseGroupBoxSize(this.reduceOrder[this.reduceOrderIndex]);
desiredSize = this.GetChildrenDesiredSizeIntermediate();
}
// If not enough space - go to next variant
while (desiredSize.Width > availableSize.Width)
{
var hasMoreVariants = this.reduceOrderIndex >= 0;
if (hasMoreVariants == false)
{
break;
}
// Decrease size of another item
this.DecreaseGroupBoxSize(this.reduceOrder[this.reduceOrderIndex]);
this.reduceOrderIndex--;
desiredSize = this.GetChildrenDesiredSizeIntermediate();
}
// Set find values
foreach (var item in this.InternalChildren)
{
var groupBox = item as RibbonGroupBox;
if (groupBox == null)
{
continue;
}
if (groupBox.State != groupBox.StateIntermediate
|| groupBox.Scale != groupBox.ScaleIntermediate)
{
groupBox.SuppressCacheReseting = true;
groupBox.State = groupBox.StateIntermediate;
groupBox.Scale = groupBox.ScaleIntermediate;
groupBox.InvalidateLayout();
groupBox.Measure(new Size(double.PositiveInfinity, availableSize.Height));
groupBox.SuppressCacheReseting = false;
}
// Something wrong with cache?
if (groupBox.DesiredSizeIntermediate != groupBox.DesiredSize)
{
// Reset cache and reinvoke masure
groupBox.ClearCache();
return this.MeasureOverride(availableSize);
}
}
this.VerifyScrollData(availableSize.Width, desiredSize.Width);
return desiredSize;
}
private Size GetChildrenDesiredSizeIntermediate()
{
double width = 0;
double height = 0;
foreach (UIElement child in this.InternalChildren)
{
var groupBox = child as RibbonGroupBox;
if (groupBox == null)
{
continue;
}
var desiredSize = groupBox.DesiredSizeIntermediate;
width += desiredSize.Width;
height = Math.Max(height, desiredSize.Height);
}
return new Size(width, height);
}
// Increase size of the item
private void IncreaseGroupBoxSize(string name)
{
var groupBox = this.FindGroup(name);
var scale = name.StartsWith("(", StringComparison.OrdinalIgnoreCase);
if (groupBox == null)
{
return;
}
if (scale)
{
groupBox.ScaleIntermediate++;
}
else
{
groupBox.StateIntermediate = groupBox.StateIntermediate != RibbonGroupBoxState.Large
? groupBox.StateIntermediate - 1
: RibbonGroupBoxState.Large;
}
}
// Decrease size of the item
private void DecreaseGroupBoxSize(string name)
{
var groupBox = this.FindGroup(name);
var scale = name.StartsWith("(", StringComparison.OrdinalIgnoreCase);
if (groupBox == null)
{
return;
}
if (scale)
{
groupBox.ScaleIntermediate--;
}
else
{
groupBox.StateIntermediate = groupBox.StateIntermediate != RibbonGroupBoxState.Collapsed
? groupBox.StateIntermediate + 1
: groupBox.StateIntermediate;
}
}
private RibbonGroupBox FindGroup(string name)
{
if (name.StartsWith("(", StringComparison.OrdinalIgnoreCase))
{
name = name.Substring(1, name.Length - 2);
}
foreach (FrameworkElement child in this.InternalChildren)
{
if (child.Name == name)
{
return child as RibbonGroupBox;
}
}
return null;
}
/// <summary>
/// When overridden in a derived class, positions child elements and determines
/// a size for a System.Windows.FrameworkElement derived class.
/// </summary>
/// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param>
/// <returns>The actual size used.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
var finalRect = new Rect(finalSize)
{
X = -this.HorizontalOffset
};
foreach (UIElement item in this.InternalChildren)
{
finalRect.Width = item.DesiredSize.Width;
finalRect.Height = Math.Max(finalSize.Height, item.DesiredSize.Height);
item.Arrange(finalRect);
finalRect.X += item.DesiredSize.Width;
}
return finalSize;
}
#endregion
#region IScrollInfo Members
/// <summary>
/// Gets or sets a System.Windows.Controls.ScrollViewer element that controls scrolling behavior.
/// </summary>
public ScrollViewer ScrollOwner
{
get { return this.ScrollData.ScrollOwner; }
set { this.ScrollData.ScrollOwner = value; }
}
/// <summary>
/// Sets the amount of horizontal offset.
/// </summary>
/// <param name="offset">The degree to which content is horizontally offset from the containing viewport.</param>
public void SetHorizontalOffset(double offset)
{
var newValue = CoerceOffset(ValidateInputOffset(offset, "HorizontalOffset"), this.scrollData.ExtentWidth, this.scrollData.ViewportWidth);
if (DoubleUtil.AreClose(this.ScrollData.OffsetX, newValue) == false)
{
this.scrollData.OffsetX = newValue;
this.InvalidateArrange();
}
}
/// <summary>
/// Gets the horizontal size of the extent.
/// </summary>
public double ExtentWidth
{
get { return this.ScrollData.ExtentWidth; }
}
/// <summary>
/// Gets the horizontal offset of the scrolled content.
/// </summary>
public double HorizontalOffset
{
get { return this.ScrollData.OffsetX; }
}
/// <summary>
/// Gets the horizontal size of the viewport for this content.
/// </summary>
public double ViewportWidth
{
get { return this.ScrollData.ViewportWidth; }
}
/// <summary>
/// Scrolls left within content by one logical unit.
/// </summary>
public void LineLeft()
{
this.SetHorizontalOffset(this.HorizontalOffset - 16.0);
}
/// <summary>
/// Scrolls right within content by one logical unit.
/// </summary>
public void LineRight()
{
this.SetHorizontalOffset(this.HorizontalOffset + 16.0);
}
/// <summary>
/// Forces content to scroll until the coordinate space of a System.Windows.Media.Visual object is visible.
/// This is optimized for horizontal scrolling only
/// </summary>
/// <param name="visual">A System.Windows.Media.Visual that becomes visible.</param>
/// <param name="rectangle">A bounding rectangle that identifies the coordinate space to make visible.</param>
/// <returns>A System.Windows.Rect that is visible.</returns>
public Rect MakeVisible(Visual visual, Rect rectangle)
{
// We can only work on visuals that are us or children.
// An empty rect has no size or position. We can't meaningfully use it.
if (rectangle.IsEmpty
|| visual == null
|| ReferenceEquals(visual, this)
|| !this.IsAncestorOf(visual))
{
return Rect.Empty;
}
// Compute the child's rect relative to (0,0) in our coordinate space.
var childTransform = visual.TransformToAncestor(this);
rectangle = childTransform.TransformBounds(rectangle);
// Initialize the viewport
var viewport = new Rect(this.HorizontalOffset, rectangle.Top, this.ViewportWidth, rectangle.Height);
rectangle.X += viewport.X;
// Compute the offsets required to minimally scroll the child maximally into view.
var minX = ComputeScrollOffsetWithMinimalScroll(viewport.Left, viewport.Right, rectangle.Left, rectangle.Right);
// We have computed the scrolling offsets; scroll to them.
this.SetHorizontalOffset(minX);
// Compute the visible rectangle of the child relative to the viewport.
viewport.X = minX;
rectangle.Intersect(viewport);
rectangle.X -= viewport.X;
// Return the rectangle
return rectangle;
}
private static double ComputeScrollOffsetWithMinimalScroll(
double topView,
double bottomView,
double topChild,
double bottomChild)
{
// # CHILD POSITION CHILD SIZE SCROLL REMEDY
// 1 Above viewport <= viewport Down Align top edge of child & viewport
// 2 Above viewport > viewport Down Align bottom edge of child & viewport
// 3 Below viewport <= viewport Up Align bottom edge of child & viewport
// 4 Below viewport > viewport Up Align top edge of child & viewport
// 5 Entirely within viewport NA No scroll.
// 6 Spanning viewport NA No scroll.
//
// Note: "Above viewport" = childTop above viewportTop, childBottom above viewportBottom
// "Below viewport" = childTop below viewportTop, childBottom below viewportBottom
// These child thus may overlap with the viewport, but will scroll the same direction
/*bool fAbove = DoubleUtil.LessThan(topChild, topView) && DoubleUtil.LessThan(bottomChild, bottomView);
bool fBelow = DoubleUtil.GreaterThan(bottomChild, bottomView) && DoubleUtil.GreaterThan(topChild, topView);*/
var fAbove = (topChild < topView) && (bottomChild < bottomView);
var fBelow = (bottomChild > bottomView) && (topChild > topView);
var fLarger = bottomChild - topChild > bottomView - topView;
// Handle Cases: 1 & 4 above
if ((fAbove && !fLarger)
|| (fBelow && fLarger))
{
return topChild;
}
// Handle Cases: 2 & 3 above
if (fAbove || fBelow)
{
return bottomChild - (bottomView - topView);
}
// Handle cases: 5 & 6 above.
return topView;
}
/// <summary>
/// Not implemented
/// </summary>
public void MouseWheelDown()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void MouseWheelLeft()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void MouseWheelRight()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void MouseWheelUp()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void LineDown()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void LineUp()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void PageDown()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void PageLeft()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void PageRight()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void PageUp()
{
}
/// <summary>
/// Not implemented
/// </summary>
public void SetVerticalOffset(double offset)
{
}
/// <summary>
/// Gets or sets a value that indicates whether scrolling on the vertical axis is possible.
/// </summary>
public bool CanVerticallyScroll
{
get { return false; }
set { }
}
/// <summary>
/// Gets or sets a value that indicates whether scrolling on the horizontal axis is possible.
/// </summary>
public bool CanHorizontallyScroll
{
get { return true; }
set { }
}
/// <summary>
/// Not implemented
/// </summary>
public double ExtentHeight
{
get { return 0.0; }
}
/// <summary>
/// Not implemented
/// </summary>
public double VerticalOffset
{
get { return 0.0; }
}
/// <summary>
/// Not implemented
/// </summary>
public double ViewportHeight
{
get { return 0.0; }
}
// Gets scroll data info
private ScrollData ScrollData
{
get
{
return this.scrollData ?? (this.scrollData = new ScrollData());
}
}
// Scroll data info
private ScrollData scrollData;
// Validates input offset
private static double ValidateInputOffset(double offset, string parameterName)
{
if (double.IsNaN(offset))
{
throw new ArgumentOutOfRangeException(parameterName);
}
return Math.Max(0.0, offset);
}
// Verifies scrolling data using the passed viewport and extent as newly computed values.
// Checks the X/Y offset and coerces them into the range [0, Extent - ViewportSize]
// If extent, viewport, or the newly coerced offsets are different than the existing offset,
// cachces are updated and InvalidateScrollInfo() is called.
private void VerifyScrollData(double viewportWidth, double extentWidth)
{
var isValid = true;
if (double.IsInfinity(viewportWidth))
{
viewportWidth = extentWidth;
}
var offsetX = CoerceOffset(this.ScrollData.OffsetX, extentWidth, viewportWidth);
isValid &= DoubleUtil.AreClose(viewportWidth, this.ScrollData.ViewportWidth);
isValid &= DoubleUtil.AreClose(extentWidth, this.ScrollData.ExtentWidth);
isValid &= DoubleUtil.AreClose(this.ScrollData.OffsetX, offsetX);
this.ScrollData.ViewportWidth = viewportWidth;
this.ScrollData.ExtentWidth = extentWidth;
this.ScrollData.OffsetX = offsetX;
if (isValid == false)
{
this.ScrollOwner?.InvalidateScrollInfo();
}
}
// Returns an offset coerced into the [0, Extent - Viewport] range.
private static double CoerceOffset(double offset, double extent, double viewport)
{
if (offset > extent - viewport)
{
offset = extent - viewport;
}
if (offset < 0)
{
offset = 0;
}
return offset;
}
#endregion
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
namespace System.Reflection.Internal
{
internal static class MemoryMapLightUp
{
private static Type s_lazyMemoryMappedFileType;
private static Type s_lazyMemoryMappedViewAccessorType;
private static Type s_lazyMemoryMappedFileAccessType;
private static Type s_lazyMemoryMappedFileSecurityType;
private static Type s_lazyHandleInheritabilityType;
private static MethodInfo s_lazyCreateFromFile;
private static MethodInfo s_lazyCreateFromFileClassic;
private static MethodInfo s_lazyCreateViewAccessor;
private static PropertyInfo s_lazySafeMemoryMappedViewHandle;
private static PropertyInfo s_lazyPointerOffset;
private static FieldInfo s_lazyInternalViewField;
private static PropertyInfo s_lazyInternalPointerOffset;
private static readonly object s_MemoryMappedFileAccess_Read = 1;
private static readonly object s_HandleInheritability_None = 0;
private static readonly object s_LongZero = (long)0;
private static readonly object s_True = true;
private static bool? s_lazyIsAvailable;
internal static bool IsAvailable
{
get
{
if (!s_lazyIsAvailable.HasValue)
{
s_lazyIsAvailable = TryLoadTypes();
}
return s_lazyIsAvailable.Value;
}
}
private static bool TryLoadType(string typeName, string modernAssembly, string classicAssembly, out Type type)
{
type = LightUpHelper.GetType(typeName, modernAssembly, classicAssembly);
return type != null;
}
private static bool TryLoadTypes()
{
const string systemIOMemoryMappedFiles = "System.IO.MemoryMappedFiles, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
const string systemRuntimeHandles = "System.Runtime.Handles, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
const string systemCore = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
TryLoadType("System.IO.MemoryMappedFiles.MemoryMappedFileSecurity", systemIOMemoryMappedFiles, systemCore, out s_lazyMemoryMappedFileSecurityType);
return FileStreamReadLightUp.FileStreamType.Value != null
&& TryLoadType("System.IO.MemoryMappedFiles.MemoryMappedFile", systemIOMemoryMappedFiles, systemCore, out s_lazyMemoryMappedFileType)
&& TryLoadType("System.IO.MemoryMappedFiles.MemoryMappedViewAccessor", systemIOMemoryMappedFiles, systemCore, out s_lazyMemoryMappedViewAccessorType)
&& TryLoadType("System.IO.MemoryMappedFiles.MemoryMappedFileAccess", systemIOMemoryMappedFiles, systemCore, out s_lazyMemoryMappedFileAccessType)
&& TryLoadType("System.IO.HandleInheritability", systemRuntimeHandles, systemCore, out s_lazyHandleInheritabilityType)
&& TryLoadMembers();
}
private static bool TryLoadMembers()
{
// .NET Core, .NET 4.6+
s_lazyCreateFromFile = LightUpHelper.GetMethod(
s_lazyMemoryMappedFileType,
"CreateFromFile",
FileStreamReadLightUp.FileStreamType.Value,
typeof(string),
typeof(long),
s_lazyMemoryMappedFileAccessType,
s_lazyHandleInheritabilityType,
typeof(bool)
);
// .NET < 4.6
if (s_lazyCreateFromFile == null)
{
if (s_lazyMemoryMappedFileSecurityType != null)
{
s_lazyCreateFromFileClassic = LightUpHelper.GetMethod(
s_lazyMemoryMappedFileType,
"CreateFromFile",
FileStreamReadLightUp.FileStreamType.Value,
typeof(string),
typeof(long),
s_lazyMemoryMappedFileAccessType,
s_lazyMemoryMappedFileSecurityType,
s_lazyHandleInheritabilityType,
typeof(bool));
}
if (s_lazyCreateFromFileClassic == null)
{
return false;
}
}
s_lazyCreateViewAccessor = LightUpHelper.GetMethod(
s_lazyMemoryMappedFileType,
"CreateViewAccessor",
typeof(long),
typeof(long),
s_lazyMemoryMappedFileAccessType);
if (s_lazyCreateViewAccessor == null)
{
return false;
}
s_lazySafeMemoryMappedViewHandle = s_lazyMemoryMappedViewAccessorType.GetTypeInfo().GetDeclaredProperty("SafeMemoryMappedViewHandle");
if (s_lazySafeMemoryMappedViewHandle == null)
{
return false;
}
// .NET Core, .NET 4.5.1+
s_lazyPointerOffset = s_lazyMemoryMappedViewAccessorType.GetTypeInfo().GetDeclaredProperty("PointerOffset");
// .NET < 4.5.1
if (s_lazyPointerOffset == null)
{
s_lazyInternalViewField = s_lazyMemoryMappedViewAccessorType.GetTypeInfo().GetDeclaredField("m_view");
if (s_lazyInternalViewField == null)
{
return false;
}
s_lazyInternalPointerOffset = s_lazyInternalViewField.FieldType.GetTypeInfo().GetDeclaredProperty("PointerOffset");
if (s_lazyInternalPointerOffset == null)
{
return false;
}
}
return true;
}
internal static IDisposable CreateMemoryMap(Stream stream)
{
Debug.Assert(s_lazyIsAvailable.GetValueOrDefault());
try
{
if (s_lazyCreateFromFile != null)
{
return (IDisposable)s_lazyCreateFromFile.Invoke(null, new object[6]
{
stream, // fileStream
null, // mapName
s_LongZero, // capacity
s_MemoryMappedFileAccess_Read, // access
s_HandleInheritability_None, // inheritability
s_True, // leaveOpen
});
}
else
{
Debug.Assert(s_lazyCreateFromFileClassic != null);
return (IDisposable)s_lazyCreateFromFileClassic.Invoke(null, new object[7]
{
stream, // fileStream
null, // mapName
s_LongZero, // capacity
s_MemoryMappedFileAccess_Read, // access
null, // memoryMappedFileSecurity
s_HandleInheritability_None, // inheritability
s_True, // leaveOpen
});
}
}
catch (MemberAccessException)
{
s_lazyIsAvailable = false;
return null;
}
catch (InvalidOperationException)
{
// thrown when accessing unapproved API in a Windows Store app
s_lazyIsAvailable = false;
return null;
}
catch (TargetInvocationException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
throw;
}
}
internal static IDisposable CreateViewAccessor(object memoryMap, long start, int size)
{
Debug.Assert(s_lazyIsAvailable.GetValueOrDefault());
try
{
return (IDisposable)s_lazyCreateViewAccessor.Invoke(memoryMap, new object[3]
{
start, // start
(long)size, // size
s_MemoryMappedFileAccess_Read, // access
});
}
catch (MemberAccessException)
{
s_lazyIsAvailable = false;
return null;
}
catch (InvalidOperationException)
{
s_lazyIsAvailable = false;
return null;
}
catch (TargetInvocationException ex) when (ex.InnerException is UnauthorizedAccessException)
{
throw new IOException(ex.InnerException.Message, ex.InnerException);
}
catch (TargetInvocationException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
throw;
}
}
internal static unsafe byte* AcquirePointer(object accessor, out SafeBuffer safeBuffer)
{
Debug.Assert(s_lazyIsAvailable.GetValueOrDefault());
safeBuffer = (SafeBuffer)s_lazySafeMemoryMappedViewHandle.GetValue(accessor);
byte* ptr = null;
safeBuffer.AcquirePointer(ref ptr);
try
{
long offset;
if (s_lazyPointerOffset != null)
{
offset = (long)s_lazyPointerOffset.GetValue(accessor);
}
else
{
object internalView = s_lazyInternalViewField.GetValue(accessor);
offset = (long)s_lazyInternalPointerOffset.GetValue(internalView);
}
return ptr + offset;
}
catch (MemberAccessException)
{
s_lazyIsAvailable = false;
return null;
}
catch (InvalidOperationException)
{
// thrown when accessing unapproved API in a Windows Store app
s_lazyIsAvailable = false;
return null;
}
catch (TargetInvocationException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
throw;
}
}
}
}
| |
// 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 Microsoft.CodeAnalysis.CSharp.UnitTests;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests
{
public class ActiveStatementTests_Methods : RudeEditTestBase
{
#region Methods
[WorkItem(740443, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740443")]
[Fact]
public void Method_Delete_Leaf1()
{
string src1 = @"
class C
{
static void Main(string[] args)
{
<AS:1>Foo(1);</AS:1>
}
static void Foo(int a)
{
<AS:0>Console.WriteLine(a);</AS:0>
}
}";
string src2 = @"
<AS:0>class C</AS:0>
{
static void Main(string[] args)
{
<AS:1>Foo(1);</AS:1>
}
}
";
// TODO (bug 755959): better deleted active statement span
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.Delete, "class C", FeaturesResources.method));
}
[Fact]
public void Method_Body_Delete1()
{
var src1 = "class C { int M() { <AS:0>return 1;</AS:0> } }";
var src2 = "class C { <AS:0>int M();</AS:0> }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.MethodBodyDelete, "int M()", FeaturesResources.method));
}
[Fact]
public void Method_ExpressionBody_Delete1()
{
var src1 = "class C { int M() => <AS:0>1</AS:0>; }";
var src2 = "class C { <AS:0>int M();</AS:0> }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.MethodBodyDelete, "int M()", FeaturesResources.method));
}
[Fact]
public void Method_ExpressionBodyToBlockBody1()
{
var src1 = "class C { int M() => <AS:0>1</AS:0>; }";
var src2 = "class C { int M() <AS:0>{</AS:0> return 1; } }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void Method_BlockBodyToExpressionBody1()
{
var src1 = "class C { int M() { <AS:0>return 1;</AS:0> } }";
var src2 = "class C { int M() => <AS:0>1</AS:0>; }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
// Generics
[Fact]
public void Update_Inner_GenericMethod()
{
string src1 = @"
class C
{
static void Main(string[] args)
{
C c = new C();
int a = 5;
int b = 10;
<AS:1>c.Swap(ref a, ref b);</AS:1>
}
void Swap<T>(ref T lhs, ref T rhs) where T : System.IComparable<T>
{
<AS:0>Console.WriteLine(""hello"");</AS:0>
}
}";
string src2 = @"
class C
{
static void Main(string[] args)
{
while (true)
{
C c = new C();
int a = 5;
int b = 10;
<AS:1>c.Swap(ref b, ref a);</AS:1>
}
}
void Swap<T>(ref T lhs, ref T rhs) where T : System.IComparable<T>
{
<AS:0>Console.WriteLine(""hello"");</AS:0>
}
}
";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.ActiveStatementUpdate, "c.Swap(ref b, ref a);"));
}
[Fact]
public void Update_Inner_ParameterType_GenericMethod()
{
string src1 = @"
class C
{
static void Main(string[] args)
{
<AS:1>Swap(5,6);</AS:1>
}
static void Swap<T>(T lhs, T rhs) where T : System.IComparable<T>
{
<AS:0>Console.WriteLine(""hello"");</AS:0>
}
}";
string src2 = @"
class C
{
static void Main(string[] args)
{
while (true)
{
<AS:1>Swap(null, null);</AS:1>
}
}
static void Swap<T>(T lhs, T rhs) where T : System.IComparable<T>
{
<AS:0>Console.WriteLine(""hello"");</AS:0>
}
}
";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.ActiveStatementUpdate, "Swap(null, null);"));
}
[Fact]
public void Update_Leaf_GenericMethod()
{
string src1 = @"
class C
{
static void Main(string[] args)
{
<AS:1>Swap(5,6);</AS:1>
}
static void Swap<T>(T lhs, T rhs) where T : System.IComparable<T>
{
<AS:0>Console.WriteLine(""hello"");</AS:0>
}
}";
string src2 = @"
class C
{
static void Main(string[] args)
{
while (true)
{
<AS:1>Swap(5,6);</AS:1>
}
}
static void Swap<T>(T lhs, T rhs) where T : System.IComparable<T>
{
<AS:0>Console.WriteLine(""hello world!"");</AS:0>
}
}
";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.GenericMethodUpdate, "static void Swap<T>(T lhs, T rhs)", FeaturesResources.method));
}
// Async
[WorkItem(749458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749458")]
[Fact]
public void Update_Leaf_AsyncMethod()
{
string src1 = @"
class Test
{
static void Main(string[] args)
{
Test f = new Test();
<AS:1>string result = f.WaitAsync().Result;</AS:1>
}
public async Task<string> WaitAsync()
{
<AS:0>await Task.Delay(1000);</AS:0>
return ""Done"";
}
}";
string src2 = @"
class Test
{
static void Main(string[] args)
{
Test f = new Test();
<AS:1>string result = f.WaitAsync().Result;</AS:1>
}
public async Task<string> WaitAsync()
{
<AS:0>await Task.Delay(100);</AS:0>
return ""Done"";
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[WorkItem(749440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749440")]
[Fact]
public void Update_Inner_AsyncMethod()
{
string src1 = @"
class Test
{
static void Main(string[] args)
{
Test f = new Test();
<AS:1>string result = f.WaitAsync(5).Result;</AS:1>
}
public async Task<string> WaitAsync(int millis)
{
<AS:0>await Task.Delay(millis);</AS:0>
return ""Done"";
}
}";
string src2 = @"
class Test
{
static void Main(string[] args)
{
Test f = new Test();
<AS:1>string result = f.WaitAsync(6).Result;</AS:1>
}
public async Task<string> WaitAsync(int millis)
{
<AS:0>await Task.Delay(millis);</AS:0>
return ""Done"";
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.ActiveStatementUpdate, "string result = f.WaitAsync(6).Result;"));
}
[WorkItem(749440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749440")]
[Fact]
public void Update_Initializer_MultipleVariables1()
{
string src1 = @"
class Test
{
static void Main(string[] args)
{
<AS:1>int a = F()</AS:1>, b = G();
}
public int F()
{
<AS:0>return 1;</AS:0>
}
public int G()
{
return 2;
}
}";
string src2 = @"
class Test
{
static void Main(string[] args)
{
<AS:1>int a = G()</AS:1>, b = F();
}
public int F()
{
<AS:0>return 1;</AS:0>
}
public int G()
{
return 2;
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.ActiveStatementUpdate, "int a = G()"));
}
[WorkItem(749440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/749440")]
[Fact]
public void Update_Initializer_MultipleVariables2()
{
string src1 = @"
class Test
{
static void Main(string[] args)
{
int a = F(), <AS:1>b = G()</AS:1>;
}
public int F()
{
<AS:0>return 1;</AS:0>
}
public int G()
{
return 2;
}
}";
string src2 = @"
class Test
{
static void Main(string[] args)
{
int a = G(), <AS:1>b = F()</AS:1>;
}
public int F()
{
<AS:0>return 1;</AS:0>
}
public int G()
{
return 2;
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.ActiveStatementUpdate, "b = F()"));
}
[Fact]
public void MethodUpdateWithLocalVariables()
{
string src1 = @"
class C
{
static void Main(string[] args)
{
int <N:0.0>a = 1</N:0.0>;
int <N:0.1>b = 2</N:0.1>;
<AS:0>System.Console.WriteLine(a + b);</AS:0>
}
}
";
string src2 = @"
class C
{
static void Main(string[] args)
{
int <N:0.1>b = 2</N:0.1>;
int <N:0.0>a = 1</N:0.0>;
<AS:0>System.Console.WriteLine(a + b);</AS:0>
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
var syntaxMap = GetSyntaxMap(src1, src2);
edits.VerifySemantics(
active,
new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), syntaxMap[0]) });
}
#endregion
#region Properties
[Fact]
public void Property_ExpressionBodyToBlockBody1()
{
var src1 = "class C { int P => <AS:0>1</AS:0>; }";
var src2 = "class C { int P { get <AS:0>{</AS:0> return 1; } } }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void Property_ExpressionBodyToBlockBody2()
{
var src1 = "class C { int P => <AS:0>1</AS:0>; }";
var src2 = "class C { int P { get <AS:0>{</AS:0> return 1; } set { } } }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void Property_ExpressionBodyToBlockBody3()
{
var src1 = "class C { int P => <AS:0>1</AS:0>; }";
var src2 = "class C { int P { set { } get <AS:0>{</AS:0> return 1; } } }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void Property_ExpressionBodyToBlockBody_Internal()
{
var src1 = @"
class C
{
int P => <AS:1>M()</AS:1>;
int M() { <AS:0>return 1;</AS:0> }
}
";
var src2 = @"
class C
{
int P { get <AS:1>{</AS:1> return M(); } }
int M() { <AS:0>return 1;</AS:0> }
}
";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.DeleteActiveStatement, "get"));
}
[Fact]
public void Property_BlockBodyToExpressionBody1()
{
var src1 = "class C { int P { get { <AS:0>return 1;</AS:0> } } }";
var src2 = "class C { int P => <AS:0>1</AS:0>; }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void Property_BlockBodyToExpressionBody2()
{
var src1 = "class C { int P { set { } get { <AS:0>return 1;</AS:0> } } }";
var src2 = "class C { int P => <AS:0>1</AS:0>; }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.Delete, "int P", CSharpFeaturesResources.property_setter));
}
[Fact]
public void Property_BlockBodyToExpressionBody_Internal()
{
var src1 = @"
class C
{
int P { get { <AS:1>return M();</AS:1> } }
int M() { <AS:0>return 1;</AS:0> }
}
";
var src2 = @"
class C
{
int P => <AS:1>M()</AS:1>;
int M() { <AS:0>return 1;</AS:0> }
}
";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.DeleteActiveStatement, "=> M()"));
}
#endregion
#region Indexers
[Fact]
public void Indexer_ExpressionBodyToBlockBody1()
{
var src1 = "class C { int this[int a] => <AS:0>1</AS:0>; }";
var src2 = "class C { int this[int a] { get <AS:0>{</AS:0> return 1; } } }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void Indexer_ExpressionBodyToBlockBody2()
{
var src1 = "class C { int this[int a] => <AS:0>1</AS:0>; }";
var src2 = "class C { int this[int a] { get <AS:0>{</AS:0> return 1; } set { } } }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void Indexer_BlockBodyToExpressionBody1()
{
var src1 = "class C { int this[int a] { get { <AS:0>return 1;</AS:0> } } }";
var src2 = "class C { int this[int a] => <AS:0>1</AS:0>; }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void Indexer_BlockBodyToExpressionBody2()
{
var src1 = "class C { int this[int a] { get { <AS:0>return 1;</AS:0> } set { } } }";
var src2 = "class C { int this[int a] => <AS:0>1</AS:0>; }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.Delete, "int this[int a]", CSharpFeaturesResources.indexer_setter));
}
[Fact]
public void Update_Leaf_Indexers1()
{
string src1 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
<AS:1>stringCollection[0] = ""hello"";</AS:1>
Console.WriteLine(stringCollection[0]);
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { return arr[i]; }
set { <AS:0>arr[i] = value;</AS:0> }
}
}";
string src2 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
<AS:1>stringCollection[0] = ""hello"";</AS:1>
Console.WriteLine(stringCollection[0]);
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { return arr[i]; }
set { <AS:0>arr[i+1] = value;</AS:0> }
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.GenericTypeUpdate, "set", CSharpFeaturesResources.indexer_setter));
}
[WorkItem(750244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750244")]
[Fact]
public void Update_Inner_Indexers1()
{
string src1 = @"
using System;
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
<AS:1>stringCollection[0] = ""hello"";</AS:1>
Console.WriteLine(stringCollection[0]);
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { return arr[i]; }
set { <AS:0>arr[i] = value;</AS:0> }
}
}";
string src2 = @"
using System;
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
<AS:1>stringCollection[1] = ""hello"";</AS:1>
Console.WriteLine(stringCollection[0]);
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { return arr[i]; }
set { <AS:0>arr[i+1] = value;</AS:0> }
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.ActiveStatementUpdate, @"stringCollection[1] = ""hello"";"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "set", CSharpFeaturesResources.indexer_setter));
}
[Fact]
public void Update_Leaf_Indexers2()
{
string src1 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = ""hello"";
<AS:1>Console.WriteLine(stringCollection[0]);</AS:1>
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { <AS:0>return arr[i];</AS:0> }
set { arr[i] = value; }
}
}";
string src2 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = ""hello"";
<AS:1>Console.WriteLine(stringCollection[0]);</AS:1>
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { <AS:0>return arr[0];</AS:0> }
set { arr[i] = value; }
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.GenericTypeUpdate, "get", CSharpFeaturesResources.indexer_getter));
}
[WorkItem(750244, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750244")]
[Fact]
public void Update_Inner_Indexers2()
{
string src1 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = ""hello"";
<AS:1>Console.WriteLine(stringCollection[0]);</AS:1>
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { <AS:0>return arr[i];</AS:0> }
set { arr[i] = value; }
}
}";
string src2 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = ""hello"";
<AS:1>Console.WriteLine(stringCollection[1]);</AS:1>
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { <AS:0>return arr[0];</AS:0> }
set { arr[i] = value; }
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(stringCollection[1]);"),
Diagnostic(RudeEditKind.GenericTypeUpdate, "get", CSharpFeaturesResources.indexer_getter));
}
[Fact]
public void Deleted_Leaf_Indexers1()
{
string src1 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
<AS:1>stringCollection[0] = ""hello"";</AS:1>
Console.WriteLine(stringCollection[0]);
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { return arr[i]; }
set { <AS:0>arr[i] = value;</AS:0> }
}
}";
string src2 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
<AS:1>stringCollection[0] = ""hello"";</AS:1>
Console.WriteLine(stringCollection[0]);
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { return arr[i]; }
set { <AS:0>}</AS:0>
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.GenericTypeUpdate, "set", CSharpFeaturesResources.indexer_setter));
}
[Fact]
public void Deleted_Inner_Indexers1()
{
string src1 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
<AS:1>stringCollection[0] = ""hello"";</AS:1>
Console.WriteLine(stringCollection[0]);
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { return arr[i]; }
set { <AS:0>arr[i] = value;</AS:0> }
}
}";
string src2 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
<AS:1>Console.WriteLine(stringCollection[0]);</AS:1>
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { return arr[i]; }
set { <AS:0>arr[i] = value;</AS:0> }
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.DeleteActiveStatement, "{"));
}
[Fact]
public void Deleted_Leaf_Indexers2()
{
string src1 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = ""hello"";
<AS:1>Console.WriteLine(stringCollection[0]);</AS:1>
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { <AS:0>return arr[i];</AS:0> }
set { arr[i] = value; }
}
}";
string src2 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = ""hello"";
<AS:1>Console.WriteLine(stringCollection[0]);</AS:1>
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { <AS:0>}</AS:0>
set { arr[i] = value; }
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.GenericTypeUpdate, "get", CSharpFeaturesResources.indexer_getter));
}
[Fact]
public void Deleted_Inner_Indexers2()
{
string src1 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = ""hello"";
<AS:1>Console.WriteLine(stringCollection[0]);</AS:1>
}
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { <AS:0>return arr[i];</AS:0> }
set { arr[i] = value; }
}
}";
string src2 = @"
class Test
{
static void Main(string[] args)
{
SampleCollection<string> stringCollection = new SampleCollection<string>();
stringCollection[0] = ""hello"";
<AS:1>}</AS:1>
}
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get { <AS:0>return arr[i];</AS:0> }
set { arr[i] = value; }
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.DeleteActiveStatement, "{"));
}
#endregion
#region Operators
[Fact]
public void Operator_ExpressionBodyToBlockBody1()
{
var src1 = "class C { public static C operator +(C t1, C t2) => <AS:0>null</AS:0>; }";
var src2 = "class C { public static C operator +(C t1, C t2) <AS:0>{</AS:0> return null; } }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void Operator_ExpressionBodyToBlockBody2()
{
var src1 = "class C { public static explicit operator D(C t) => <AS:0>null</AS:0>; }";
var src2 = "class C { public static explicit operator D(C t) <AS:0>{</AS:0> return null; } }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void Operator_BlockBodyToExpressionBody1()
{
var src1 = "class C { public static C operator +(C t1, C t2) { <AS:0>return null;</AS:0> } }";
var src2 = "class C { public static C operator +(C t1, C t2) => <AS:0>null</AS:0>; }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[Fact]
public void Operator_BlockBodyToExpressionBody2()
{
var src1 = "class C { public static explicit operator D(C t) { <AS:0>return null;</AS:0> } }";
var src2 = "class C { public static explicit operator D(C t) => <AS:0>null</AS:0>; }";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[WorkItem(754274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754274")]
[Fact]
public void Update_Leaf_OverloadedOperator()
{
string src1 = @"
class Test
{
static void Main(string[] args)
{
Test t1 = new Test(5);
Test t2 = new Test(5);
<AS:1>Test t3 = t1 + t2;</AS:1>
}
public static Test operator +(Test t1, Test t2)
{
<AS:0>return new Test(t1.a + t2.a);</AS:0>
}
}";
string src2 = @"
class Test
{
static void Main(string[] args)
{
Test t1 = new Test(5);
Test t2 = new Test(5);
<AS:1>Test t3 = t1 + t2;</AS:1>
}
public static Test operator +(Test t1, Test t2)
{
<AS:0>return new Test(t1.a + 2 * t2.a);</AS:0>
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active);
}
[WorkItem(754274, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754274")]
[Fact]
public void Update_Inner_OverloadedOperator()
{
string src1 = @"
class Test
{
static void Main(string[] args)
{
Test t1 = new Test(5);
Test t2 = new Test(5);
<AS:1>Test t3 = t1 + t2;</AS:1>
}
public static Test operator +(Test t1, Test t2)
{
<AS:0>return new Test(t1.a + t2.a);</AS:0>
}
public static Test operator *(Test t1, Test t2)
{
return new Test(t1.a * t2.a);
}
}";
string src2 = @"
class Test
{
static void Main(string[] args)
{
Test t1 = new Test(5);
Test t2 = new Test(5);
<AS:1>Test t3 = t1 * t2;</AS:1>
}
public static Test operator +(Test t1, Test t2)
{
<AS:0>return new Test(t1.a + t2.a);</AS:0>
}
public static Test operator *(Test t1, Test t2)
{
return new Test(t1.a * t2.a);
}
}";
var edits = GetTopEdits(src1, src2);
var active = GetActiveStatements(src1, src2);
edits.VerifyRudeDiagnostics(active,
Diagnostic(RudeEditKind.ActiveStatementUpdate, "Test t3 = t1 * t2;"));
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Net;
using System.Text;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Protocols.TestTools.StackSdk.Security.Sspi;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Rsvd
{
/// <summary>
/// RsvdClient is the exposed interface for testing Rsvd server.
/// </summary>
public sealed class RsvdClient : IDisposable
{
#region Fields
private Smb2ClientTransport transport;
private bool disposed;
private TimeSpan timeout;
#endregion
#region Constructor & Dispose
/// <summary>
/// Constructor
/// </summary>
public RsvdClient(TimeSpan timeout)
{
this.timeout = timeout;
}
/// <summary>
/// Release the managed and unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
// Take this object out of the finalization queue of the GC:
GC.SuppressFinalize(this);
}
/// <summary>
/// Release resources.
/// </summary>
/// <param name="disposing">If disposing equals true, Managed and unmanaged resources are disposed.
/// if false, Only unmanaged resources can be disposed.</param>
private void Dispose(bool disposing)
{
if (!this.disposed)
{
// If disposing equals true, dispose all managed and unmanaged resources.
if (disposing)
{
// Free managed resources & other reference types:
if (this.transport != null)
{
this.transport.Dispose();
this.transport = null;
}
}
this.disposed = true;
}
}
/// <summary>
/// finalizer
/// </summary>
~RsvdClient()
{
Dispose(false);
}
#endregion
/// <summary>
/// Set up connection with server.
/// Including 4 steps: 1. Tcp connection 2. Negotiation 3. SessionSetup 4. TreeConnect
/// </summary>
/// <param name="serverName">server name</param>
/// <param name="serverIP">server IP address</param>
/// <param name="domain">user's domain</param>
/// <param name="userName">user's name</param>
/// <param name="password">user's password</param>
/// <param name="securityPackage">The security package</param>
/// <param name="useServerToken">Whether to use token from server</param>
/// <param name="shareName">Name of the share when TreeConnect</param>
public void Connect(
string serverName,
IPAddress serverIP,
string domain,
string userName,
string password,
SecurityPackageType securityPackage,
bool useServerToken,
string shareName)
{
transport = new Smb2ClientTransport();
transport.ConnectShare(serverName, serverIP, domain, userName, password, shareName, securityPackage, useServerToken);
}
/// <summary>
/// Disconnect from server.
/// </summary>
public void Disconnect()
{
if (transport != null)
{
this.transport.Disconnect(timeout);
}
}
/// <summary>
/// Open the shared virtual disk file
/// Send smb2 create request to server
/// </summary>
/// <param name="vhdxName">Name of the shared virtual disk file</param>
/// <param name="createOption">CreateOption in create request</param>
/// <param name="contexts">Create Contexts to be sent together with Create Request</param>
/// <param name="status">Status of create response</param>
/// <param name="serverContexts">Create contexts returned in create response</param>
/// <param name="response">Create Response returned by server</param>
/// <returns>Create Response returned by server</returns>
public uint OpenSharedVirtualDisk(
string vhdxName,
FsCreateOption createOption,
Smb2CreateContextRequest[] contexts,
out Smb2CreateContextResponse[] serverContexts,
out CREATE_Response response)
{
uint status;
transport.Create(
vhdxName,
// The desired access is set the same as Windows client's behavior
FsFileDesiredAccess.FILE_READ_DATA | FsFileDesiredAccess.FILE_WRITE_DATA | FsFileDesiredAccess.FILE_READ_ATTRIBUTES | FsFileDesiredAccess.READ_CONTROL,
ShareAccess_Values.FILE_SHARE_DELETE | ShareAccess_Values.FILE_SHARE_READ | ShareAccess_Values.FILE_SHARE_WRITE,
FsImpersonationLevel.Impersonation,
FsFileAttribute.NONE,
FsCreateDisposition.FILE_OPEN,
createOption,
contexts,
out status,
out serverContexts,
out response);
return status;
}
/// <summary>
/// Close the shared virtual disk file
/// </summary>
public void CloseSharedVirtualDisk()
{
transport.Close();
}
/// <summary>
/// Read content from the shared virtual disk file
/// </summary>
/// <param name="offset">In bytes, from the beginning of the virtual disk where data should be read</param>
/// <param name="length">The number of bytes to read</param>
/// <param name="data">The buffer to receive the data.</param>
/// <returns>Status of response packet</returns>
public uint Read(ulong offset, uint length, out byte[] data)
{
return transport.Read(timeout, offset, length, out data);
}
/// <summary>
/// Write content to the shared virtual disk file
/// </summary>
/// <param name="offset">In bytes, from the beginning of the virtual disk where data should be written</param>
/// <param name="data">A buffer containing the bytes to be written.</param>
/// <returns>Status of response packet</returns>
public uint Write(ulong offset, byte[] data)
{
return transport.Write(timeout, offset, data);
}
/// <summary>
/// Tunnel operations to the shared virtual disk file
/// </summary>
/// <typeparam name="ResponseT">Type of the operation response</typeparam>
/// <param name="isAsyncOperation">Indicate whether the tunnel operation is async or not</param>
/// <param name="code">Operation code</param>
/// <param name="requestId">A value that uniquely identifies an operation request and response for all requests sent by this client</param>
/// <param name="requestStructure">The marshalled tunnel structure of the request</param>
/// <param name="responseHeader">Tunnel operation header of the response packet</param>
/// <param name="response">Tunnel operation response of the smb2 response packet</param>
/// <returns>Status of the smb2 response packet</returns>
public uint TunnelOperation<ResponseT>(
bool isAsyncOperation,
RSVD_TUNNEL_OPERATION_CODE code,
ulong requestId,
byte[] requestStructure,
out SVHDX_TUNNEL_OPERATION_HEADER? responseHeader,
out ResponseT? response) where ResponseT : struct
{
SVHDX_TUNNEL_OPERATION_HEADER header = new SVHDX_TUNNEL_OPERATION_HEADER();
header.OperationCode = code;
header.RequestId = requestId;
byte[] payload = TypeMarshal.ToBytes(header);
if (null != requestStructure)
payload = payload.Concat(requestStructure).ToArray();
CtlCode_Values ctlCode = isAsyncOperation ? CtlCode_Values.FSCTL_SVHDX_ASYNC_TUNNEL_REQUEST : CtlCode_Values.FSCTL_SVHDX_SYNC_TUNNEL_REQUEST;
transport.SendIoctlPayload(ctlCode, payload);
uint smb2Status;
transport.ExpectIoctlPayload(out smb2Status, out payload);
response = null;
responseHeader = null;
if (smb2Status != Smb2Status.STATUS_SUCCESS)
{
return smb2Status;
}
responseHeader = TypeMarshal.ToStruct<SVHDX_TUNNEL_OPERATION_HEADER>(payload);
// If the response does not contain Header only, parse the resonse body.
if (responseHeader.Value.Status == 0 && typeof(ResponseT) != typeof(SVHDX_TUNNEL_OPERATION_HEADER))
{
response = TypeMarshal.ToStruct<ResponseT>(payload.Skip(Marshal.SizeOf(responseHeader)).ToArray());
}
else
{
// The operation failed, so no response body.
// Or the response only contains header, no response body.
}
return smb2Status;
}
/// <summary>
/// Create an SVHDX_TUNNEL_FILE_INFO_REQUEST structure and marshal it to a byte array
/// </summary>
/// <returns>The marshalled byte array</returns>
public byte[] CreateTunnelFileInfoRequest()
{
// The SVHDX_TUNNEL_FILE_INFO_REQUEST packet is sent by the client to get the shared virtual disk file information.
// The request MUST contain only SVHDX_TUNNEL_OPERATION_HEADER, and MUST NOT contain any payload.
return null;
}
/// <summary>
/// Create an SVHDX_TUNNEL_CHECK_CONNECTION_REQUEST structure and marshal it to a byte array
/// </summary>
/// <returns>The marshalled byte array</returns>
public byte[] CreateTunnelCheckConnectionStatusRequest()
{
///The SVHDX_TUNNEL_CHECK_CONNECTION_REQUEST packet is sent by the client to check the connection status to the shared virtual disk.
///The request MUST contain only SVHDX_TUNNEL_OPERATION_HEADER, and MUST NOT contain any payload.
return null;
}
/// <summary>
/// Create an SVHDX_TUNNEL_SRB_STATUS_REQUEST structure and marshal it to a byte array
/// </summary>
/// <param name="statusKey">The client MUST set this field to the least significant bytes of the status code value given by the server for the failed request.</param>
/// <returns>The marshalled byte array</returns>
public byte[] CreateTunnelSrbStatusRequest(byte statusKey)
{
SVHDX_TUNNEL_SRB_STATUS_REQUEST srbStatusRequest = new SVHDX_TUNNEL_SRB_STATUS_REQUEST();
srbStatusRequest.StatusKey = statusKey;
srbStatusRequest.Reserved = new byte[27];
return TypeMarshal.ToBytes(srbStatusRequest);
}
/// <summary>
/// Create an SVHDX_TUNNEL_DISK_INFO_REQUEST structure and marshal it to a byte array
/// </summary>
/// <param name="blockSize">The client MUST set this field to zero, and the server MUST ignore it on receipt.</param>
/// <param name="linkageID">The client MUST set this field to zero, and the server MUST ignore it on receipt.</param>
/// <param name="isMounted">The client MUST set this field to zero, and the server MUST ignore it on receipt.</param>
/// <param name="is4kAligned">The client MUST set this field to zero, and the server MUST ignore it on receipt.</param>
/// <param name="fileSize">The client MUST set this field to zero, and the server MUST ignore it on receipt.</param>
/// <param name="virtualDiskId">This field MUST NOT be used and MUST be reserved. The client MUST set this field to zero, and the server MUST ignore it on receipt.</param>
/// <returns>The marshalled byte array</returns>
public byte[] CreateTunnelDiskInfoRequest(uint blockSize = 0, Guid linkageID = default(Guid), bool isMounted = false, bool is4kAligned = false, ulong fileSize = 0, Guid virtualDiskId = default(Guid))
{
SVHDX_TUNNEL_DISK_INFO_REQUEST diskInfoRequest = new SVHDX_TUNNEL_DISK_INFO_REQUEST();
diskInfoRequest.BlockSize = blockSize;
diskInfoRequest.LinkageID = linkageID;
diskInfoRequest.IsMounted = isMounted;
diskInfoRequest.Is4kAligned = is4kAligned;
diskInfoRequest.FileSize = fileSize;
diskInfoRequest.VirtualDiskId = virtualDiskId;
return TypeMarshal.ToBytes(diskInfoRequest);
}
/// <summary>
/// Create an SVHDX_TUNNEL_SCSI_REQUEST structure and marshal it to a byte array
/// </summary>
/// <param name="length">Specifies the size, in bytes, of the SVHDX_TUNNEL_SCSI_REQUEST structure.</param>
/// <param name="cdbLength">The length, in bytes, of the SCSI command descriptor block. This value MUST be less than or equal to RSVD_CDB_GENERIC_LENGTH.</param>
/// <param name="senseInfoExLength">The length, in bytes, of the request sense data buffer. This value MUST be less than or equal to RSVD_SCSI_SENSE_BUFFER_SIZE.</param>
/// <param name="dataIn">A Boolean, indicating the SCSI command descriptor block transfer type.
/// The value TRUE (0x01) indicates that the operation is to store the data onto the disk.
/// The value FALSE (0x00) indicates that the operation is to retrieve the data from the disk.</param>
/// <param name="srbFlags">An optional, application-provided flag to indicate the options of the SCSI request.</param>
/// <param name="dataTransferLength">The length, in bytes, of the additional data placed in the DataBuffer field.</param>
/// <param name="cdbBuffer">A buffer that contains the SCSI command descriptor block.</param>
/// <param name="dataBuffer">A variable-length buffer that contains the additional buffer, as described by the DataTransferLength field.</param>
/// <returns>The marshalled byte array</returns>
public byte[] CreateTunnelScsiRequest(
ushort length,
byte cdbLength,
byte senseInfoExLength,
bool dataIn,
SRB_FLAGS srbFlags,
uint dataTransferLength,
byte[] cdbBuffer,
byte[] dataBuffer)
{
SVHDX_TUNNEL_SCSI_REQUEST scsiRequest = new SVHDX_TUNNEL_SCSI_REQUEST();
scsiRequest.Length = length;
scsiRequest.CdbLength = cdbLength;
scsiRequest.SenseInfoExLength = senseInfoExLength;
scsiRequest.DataIn = dataIn;
scsiRequest.SrbFlags = srbFlags;
scsiRequest.DataTransferLength = dataTransferLength;
scsiRequest.CDBBuffer = cdbBuffer;
scsiRequest.DataBuffer = dataBuffer;
return TypeMarshal.ToBytes(scsiRequest);
}
/// <summary>
/// Create an SVHDX_TUNNEL_VALIDATE_DISK_REQUEST structure and marshal it to a byte array
/// </summary>
/// <returns>The marshalled byte array</returns>
public byte[] CreateTunnelValidateDiskRequest()
{
///The SVHDX_TUNNEL_VALIDATE_DISK_REQUEST packet is sent by the client to validate the shared virtual disk.
SVHDX_TUNNEL_VALIDATE_DISK_REQUEST validDiskRequest = new SVHDX_TUNNEL_VALIDATE_DISK_REQUEST();
validDiskRequest.Reserved = new byte[56];
return TypeMarshal.ToBytes(validDiskRequest);
}
/// <summary>
/// Create an SVHDX_TUNNEL_VHDSET_FILE_QUERY_INFORMATION_REQUEST structure and marshal it to a byte array
/// </summary>
/// <param name="setFileInformationType">The set file information type requested</param>
/// <param name="snapshotType">The snapshot type queried by this operation</param>
/// <param name="snapshotId">The snapshot ID relevant to the particular request</param>
/// <returns>The marshalled byte array</returns>
public byte[] CreateTunnelGetVHDSetFileInfoRequest(
SetFile_InformationType setFileInformationType,
Snapshot_Type snapshotType,
Guid snapshotId)
{
SVHDX_TUNNEL_VHDSET_FILE_QUERY_INFORMATION_REQUEST getVHDSetFileInfoRequest = new SVHDX_TUNNEL_VHDSET_FILE_QUERY_INFORMATION_REQUEST();
getVHDSetFileInfoRequest.SetFileInformationType = setFileInformationType;
getVHDSetFileInfoRequest.SetFileInformationSnapshotType = snapshotType;
getVHDSetFileInfoRequest.SnapshotId = snapshotId;
return TypeMarshal.ToBytes(getVHDSetFileInfoRequest);
}
/// <summary>
/// Create an SVHDX_META_OPERATION_START_CREATE_SNAPSHOT_REQUEST structure and marshal it to a byte array
/// </summary>
/// <param name="startRequest">Type SVHDX_META_OPERATION_START_REQUEST includes TransactionId and OperationType</param>
/// <param name="createSnapshot">Type of SVHDX_META_OPERATION_CREATE_SNAPSHOT structure</param>
/// <returns>The marshalled byte array</returns>
public byte[] CreateTunnelMetaOperationStartCreateSnapshotRequest(
SVHDX_META_OPERATION_START_REQUEST startRequest,
SVHDX_META_OPERATION_CREATE_SNAPSHOT createSnapshot)
{
SVHDX_META_OPERATION_START_CREATE_SNAPSHOT_REQUEST createSnapshotRequest = new SVHDX_META_OPERATION_START_CREATE_SNAPSHOT_REQUEST();
createSnapshotRequest.startRequest = startRequest;
createSnapshotRequest.createSnapshot = createSnapshot;
return TypeMarshal.ToBytes(createSnapshotRequest);
}
/// <summary>
/// Create an SVHDX_META_OPERATION_OPTIMIZE_REQUEST structure and marshal it to a byte array
/// </summary>
/// <param name="startRequest">Type SVHDX_META_OPERATION_START_REQUEST includes TransactionId and OperationType</param>
/// <param name="optimize">Type of SVHDX_META_OPERATION_OPTIMIZE structure</param>
/// <returns>The marshalled byte array</returns>
public byte[] CreateTunnelMetaOperationStartOptimizeRequest(
SVHDX_META_OPERATION_START_REQUEST startRequest,
SVHDX_META_OPERATION_OPTIMIZE optimize)
{
SVHDX_META_OPERATION_START_OPTIMIZE_REQUEST optimizeRequest = new SVHDX_META_OPERATION_START_OPTIMIZE_REQUEST();
optimizeRequest.startRequest = startRequest;
optimizeRequest.optimize = optimize;
return TypeMarshal.ToBytes(optimizeRequest);
}
/// <summary>
/// Create an SVHDX_TUNNEL_DELETE_SNAPSHOT_REQUEST structure and marshal it to a byte array
/// </summary>
/// <param name="request">A SVHDX_TUNNEL_DELETE_SNAPSHOT_REQUEST request</param>
/// <returns>The marshalled byte array</returns>
public byte[] CreateTunnelMetaOperationDeleteSnapshotRequest(
SVHDX_TUNNEL_DELETE_SNAPSHOT_REQUEST request)
{
return TypeMarshal.ToBytes(request);
}
/// <summary>
/// Create an SVHDX_META_OPERATION_START_EXTRACT_REQUEST structure and marshal it to a byte array
/// </summary>
/// <param name="startRequest">Struct SVHDX_META_OPERATION_START_REQUEST includes TransactionId and OperationType</param>
/// <param name="extract">Struct SVHDX_META_OPERATION_EXTRACT</param>
/// <returns>The marshalled byte array</returns>
public byte[] CreateTunnelMetaOperationStartExtractRequest(
SVHDX_META_OPERATION_START_REQUEST startRequest,
SVHDX_META_OPERATION_EXTRACT extract)
{
SVHDX_META_OPERATION_START_EXTRACT_REQUEST extractRequest = new SVHDX_META_OPERATION_START_EXTRACT_REQUEST();
extractRequest.startRequest = startRequest;
extractRequest.extract = extract;
return TypeMarshal.ToBytes(extractRequest);
}
/// <summary>
/// Create an SVHDX_META_OPERATION_START_CONVERT_TO_VHDSET_REQUEST structure and marshal it to a byte array
/// </summary>
/// <param name="startRequest">Struct SVHDX_META_OPERATION_START_REQUEST includes TransactionId and OperationType</param>
/// <param name="convert">Struct SVHDX_META_OPERATION_CONVERT_TO_VHDSET</param>
/// <returns>The marshalled byte array</returns>
public byte[] CreateTunnelMetaOperationStartConvertToVHDSetRequest(
SVHDX_META_OPERATION_START_REQUEST startRequest,
SVHDX_META_OPERATION_CONVERT_TO_VHDSET convert)
{
SVHDX_META_OPERATION_START_CONVERT_TO_VHDSET_REQUEST convertRequest = new SVHDX_META_OPERATION_START_CONVERT_TO_VHDSET_REQUEST();
convertRequest.startRequest = startRequest;
convertRequest.convert = convert;
return TypeMarshal.ToBytes(convertRequest);
}
/// <summary>
/// Create an SVHDX_META_OPERATION_START_ONLINE_RESIZE_REQUEST structure and marshal it to a byte array
/// </summary>
/// <param name="startRequest">Struct SVHDX_META_OPERATION_START_REQUEST includes TransactionId and OperationType</param>
/// <param name="resize">Struct SVHDX_META_OPERATION_RESIZE_VIRTUAL_DISK</param>
/// <returns>The marshalled byte array</returns>
public byte[] CreateTunnelMetaOperationStartOnlineResizeRequest(
SVHDX_META_OPERATION_START_REQUEST startRequest,
SVHDX_META_OPERATION_RESIZE_VIRTUAL_DISK resize)
{
SVHDX_META_OPERATION_START_ONLINE_RESIZE_REQUEST resizeVHDSetRequest = new SVHDX_META_OPERATION_START_ONLINE_RESIZE_REQUEST();
resizeVHDSetRequest.startRequest = startRequest;
resizeVHDSetRequest.resizeRequest = resize;
return TypeMarshal.ToBytes(resizeVHDSetRequest);
}
/// <summary>
/// Query shared virtual disk support
/// </summary>
/// <param name="response">Shared virtual disk support response to receive from RSVD server</param>
/// <param name="requestPayload">Payload of the ioctl request, default value is null</param>
/// <returns>Status of response packet</returns>
public uint QuerySharedVirtualDiskSupport(out SVHDX_SHARED_VIRTUAL_DISK_SUPPORT_RESPONSE? response, byte[] requestPayload = null)
{
byte[] output;
uint status;
// FSCTL_QUERY_SHARED_VIRTUAL_DISK_SUPPORT is a fsctl code.
// So cast the type from CtlCode_Values to FsCtlCode is to use the correct overloaded function
// IoControl(TimeSpan timeout, FsCtlCode controlCode, byte[] input, out byte[] output)
status = transport.IoControl(this.timeout, (FsCtlCode)CtlCode_Values.FSCTL_QUERY_SHARED_VIRTUAL_DISK_SUPPORT, requestPayload, out output);
if (status != Smb2Status.STATUS_SUCCESS)
{
response = null;
return status;
}
response = TypeMarshal.ToStruct<SVHDX_SHARED_VIRTUAL_DISK_SUPPORT_RESPONSE>(output);
return status;
}
}
}
| |
using System.Collections;
using System.Runtime.InteropServices;
namespace GraphQLParser.Tests;
public class ParserTests
{
[Fact]
public void GraphQLDocument_Source_ShouldBe_Original_String()
{
string text = "scalar JSON";
var doc = text.Parse();
(doc.Source == text).ShouldBeTrue();
// just to demonstrate how TryGetString works
MemoryMarshal.TryGetString(doc.Source, out var str1, out var start1, out var length1).ShouldBeTrue();
ReferenceEquals(text, str1).ShouldBeTrue();
start1.ShouldBe(0);
length1.ShouldBe(11);
var text2 = text.AsMemory().Slice(1);
MemoryMarshal.TryGetString(text2, out var str2, out var start2, out var length2).ShouldBeTrue();
ReferenceEquals(text, str2).ShouldBeTrue();
start2.ShouldBe(1);
length2.ShouldBe(10);
var text3 = text.AsMemory().Slice(2, 4);
MemoryMarshal.TryGetString(text3, out var str3, out var start3, out var length3).ShouldBeTrue();
ReferenceEquals(text, str3).ShouldBeTrue();
start3.ShouldBe(2);
length3.ShouldBe(4);
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Extra_Comments_Should_Read_Correctly(IgnoreOptions options)
{
string query = "ExtraComments".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
// query
var def = document.Definitions.First() as GraphQLOperationDefinition;
def.SelectionSet.Selections.Count.ShouldBe(2);
// person
var field = def.SelectionSet.Selections.First() as GraphQLField;
field.SelectionSet.Selections.Count.ShouldBe(1);
// name
var subField = field.SelectionSet.Selections.First() as GraphQLField;
subField.Comment.ShouldBeNull();
// test
field = def.SelectionSet.Selections.Last() as GraphQLField;
field.SelectionSet.Selections.Count.ShouldBe(1);
field.Comment.ShouldNotBeNull().Value.ShouldBe("comment2");
// alt
subField = field.SelectionSet.Selections.First() as GraphQLField;
subField.Comment.ShouldBeNull();
// extra document comments
document.UnattachedComments.Count.ShouldBe(3);
document.UnattachedComments[0][0].Value.ShouldBe("comment1");
document.UnattachedComments[1][0].Value.ShouldBe("comment3");
document.UnattachedComments[2][0].Value.ShouldBe("comment4");
}
[Theory]
//[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
//[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Comments_Can_Be_Ignored(IgnoreOptions options)
{
const string query = @"
{
#comment
person
# comment2
}";
var document = query.Parse(new ParserOptions { Ignore = options });
document.UnattachedComments.ShouldBeNull();
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions.First() as GraphQLOperationDefinition;
def.SelectionSet.Selections.Count.ShouldBe(1);
def.Comment.ShouldBeNull();
var field = def.SelectionSet.Selections.First() as GraphQLField;
field.Comment.ShouldBeNull();
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_FragmentSpread_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnFragmentSpread".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(2);
var def = document.Definitions.First() as GraphQLOperationDefinition;
def.SelectionSet.Selections.Count.ShouldBe(1);
var field = def.SelectionSet.Selections.First() as GraphQLField;
field.SelectionSet.Selections.Count.ShouldBe(1);
var spread = field.SelectionSet.Selections.First() as GraphQLFragmentSpread;
spread.Comment.ShouldNotBeNull().Value.ShouldBe("comment");
spread.FragmentName.Comment.Value.ShouldBe("comment on fragment name 1");
var frag = document.Definitions.Last() as GraphQLFragmentDefinition;
frag.Comment.ShouldBeNull();
frag.FragmentName.Comment.Value.ShouldBe("comment on fragment name 2");
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_Values_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnValues".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions.First() as GraphQLOperationDefinition;
def.SelectionSet.Selections.Count.ShouldBe(1);
var field = def.SelectionSet.Selections.First() as GraphQLField;
field.SelectionSet.Selections.Count.ShouldBe(1);
field.Arguments.Count.ShouldBe(9);
var boolValue = field.Arguments[0].Value.ShouldBeAssignableTo<GraphQLBooleanValue>();
boolValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for bool");
var nullValue = field.Arguments[1].Value.ShouldBeAssignableTo<GraphQLNullValue>();
nullValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for null");
var enumValue = field.Arguments[2].Value.ShouldBeAssignableTo<GraphQLEnumValue>();
enumValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for enum");
var listValue = field.Arguments[3].Value.ShouldBeAssignableTo<GraphQLListValue>();
listValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for list");
var objValue = field.Arguments[4].Value.ShouldBeAssignableTo<GraphQLObjectValue>();
objValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for object");
var intValue = field.Arguments[5].Value.ShouldBeAssignableTo<GraphQLIntValue>();
intValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for int");
var floatValue = field.Arguments[6].Value.ShouldBeAssignableTo<GraphQLFloatValue>();
floatValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for float");
var stringValue = field.Arguments[7].Value.ShouldBeAssignableTo<GraphQLStringValue>();
stringValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for string");
var varValue = field.Arguments[8].Value.ShouldBeAssignableTo<GraphQLVariable>();
varValue.Comment.ShouldNotBeNull().Value.ShouldBe("comment for variable");
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_FragmentInline_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnInlineFragment".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions.First() as GraphQLOperationDefinition;
def.SelectionSet.Selections.Count.ShouldBe(1);
var field = def.SelectionSet.Selections.First() as GraphQLField;
field.SelectionSet.Selections.Count.ShouldBe(1);
var fragment = field.SelectionSet.Selections.First() as GraphQLInlineFragment;
fragment.Comment.ShouldNotBeNull().Value.ShouldBe("comment");
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_Arguments_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnArguments".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions[0] as GraphQLOperationDefinition;
def.SelectionSet.Selections.Count.ShouldBe(1);
var field = def.SelectionSet.Selections.First() as GraphQLField;
field.Arguments.Count.ShouldBe(2);
field.Arguments.Comment.ShouldNotBeNull().Value.ShouldBe("arguments comment");
var obj = field.Arguments[1].Value.ShouldBeAssignableTo<GraphQLObjectValue>();
obj.Fields.Count.ShouldBe(1);
obj.Fields[0].Name.Value.ShouldBe("z");
obj.Fields[0].Comment.Value.ShouldBe("comment on object field");
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_NamedTypes_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnNamedType".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(5);
var def1 = document.Definitions[0] as GraphQLOperationDefinition;
var field = def1.SelectionSet.Selections[0] as GraphQLField;
var frag = field.SelectionSet.Selections[0] as GraphQLInlineFragment;
frag.TypeCondition.Type.Comment.Value.ShouldBe("comment for named type from TypeCondition");
var def2 = document.Definitions[1] as GraphQLObjectTypeDefinition;
def2.Interfaces[0].Comment.Value.ShouldBe("comment for named type from ImplementsInterfaces");
var def3 = document.Definitions[2] as GraphQLSchemaDefinition;
def3.OperationTypes[0].Type.Comment.Value.ShouldBe("comment for named type from RootOperationTypeDefinition");
var def4 = document.Definitions[3] as GraphQLObjectTypeDefinition;
def4.Fields[0].Type.Comment.Value.ShouldBe("comment for named type from Type");
var def5 = document.Definitions[4] as GraphQLUnionTypeDefinition;
def5.Types[1].Comment.Value.ShouldBe("comment for named type from UnionMemberTypes");
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_SelectionSet_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnSelectionSet".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions[0] as GraphQLOperationDefinition;
def.SelectionSet.Comment.Value.ShouldBe("comment on selection set");
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_RootOperationType_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnRootOperationType".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions[0] as GraphQLSchemaDefinition;
def.OperationTypes[0].Comment.Value.ShouldBe("comment for root operation type");
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_Directive_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnDirective".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions[0] as GraphQLScalarTypeDefinition;
def.Directives[0].Comment.Value.ShouldBe("comment for directive");
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_Type_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnType".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(3);
var def = document.Definitions[0] as GraphQLObjectTypeDefinition;
def.Comment.Value.ShouldBe("very good type");
def.Interfaces.Comment.Value.ShouldBe("comment for implemented interfaces");
def.Fields.Comment.Value.ShouldBe("comment for fields definition");
def.Fields[0].Type.Comment.Value.ShouldBe("comment for named type");
def.Fields[0].Arguments.Comment.Value.ShouldBe("comment for arguments definition");
def.Fields[1].Type.Comment.Value.ShouldBe("comment for nonnull type");
def.Fields[2].Type.Comment.Value.ShouldBe("comment for list type");
(def.Fields[2].Type as GraphQLListType).Type.Comment.Value.ShouldBe("comment for item type");
var ext1 = document.Definitions[1] as GraphQLObjectTypeExtension;
ext1.Comment.Value.ShouldBe("forgot about address!");
var ext2 = document.Definitions[2] as GraphQLInterfaceTypeExtension;
ext2.Comment.Value.ShouldBe("forgot about vip!");
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_Input_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnInput".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(2);
var def = document.Definitions[0] as GraphQLInputObjectTypeDefinition;
def.Comment.Value.ShouldBe("very good input");
def.Fields.Comment.Value.ShouldBe("comment for input fields definition");
def.Fields[0].Type.Comment.Value.ShouldBe("comment for named type");
def.Fields[1].Type.Comment.Value.ShouldBe("comment for nonnull type");
def.Fields[2].Type.Comment.Value.ShouldBe("comment for list type");
(def.Fields[2].Type as GraphQLListType).Type.Comment.Value.ShouldBe("comment for item type");
var ext = document.Definitions[1] as GraphQLInputObjectTypeExtension;
ext.Comment.Value.ShouldBe("forgot about address!");
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_Alias_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnAlias".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions[0] as GraphQLOperationDefinition;
def.SelectionSet.Selections.Count.ShouldBe(1);
var field = def.SelectionSet.Selections[0].ShouldBeAssignableTo<GraphQLField>();
field.Comment.Value.ShouldBe("field comment! not alias!");
field.Alias.Name.Value.ShouldBe("a");
field.Alias.Comment.ShouldBeNull();
field.Name.Value.ShouldBe("name");
field.Name.Comment.Value.ShouldBe("field name (GraphQLName) comment");
document.UnattachedComments.Count.ShouldBe(1);
document.UnattachedComments[0][0].Value.ShouldBe("colon comment");
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_DirectiveDefinition_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnDirectiveDefinition".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions[0] as GraphQLDirectiveDefinition;
def.Comment.Value.ShouldBe("very good directive");
def.Locations.Comment.Value.ShouldBe("comment for directive locations");
document.UnattachedComments.ShouldBeNull();
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_Enum_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnEnum".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(2);
document.OperationWithName("qwerty").ShouldBeNull();
document.OperationWithName("").ShouldBeNull();
var def = document.Definitions[0] as GraphQLEnumTypeDefinition;
def.Comment.Value.ShouldBe("very good colors");
def.Values.Comment.Value.ShouldBe("values");
def.Values[0].Comment.Value.ShouldBe("not green");
def.Values[1].Comment.Value.ShouldBe("not red");
var ext = document.Definitions[1] as GraphQLEnumTypeExtension;
ext.Comment.Value.ShouldBe("forgot about orange!");
document.UnattachedComments.ShouldBeNull();
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_Schema_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnSchema".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(2);
var def = document.Definitions[0] as GraphQLSchemaDefinition;
def.Comment.Value.ShouldBe("very good schema");
var ext = document.Definitions[1] as GraphQLSchemaExtension;
ext.Comment.Value.ShouldBe("forgot about mutation!");
document.UnattachedComments.ShouldBeNull();
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_Scalar_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnScalar".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(2);
var def = document.Definitions[0] as GraphQLScalarTypeDefinition;
def.Comment.Value.ShouldBe("very good scalar");
var ext = document.Definitions[1] as GraphQLScalarTypeExtension;
ext.Comment.Value.ShouldBe("forgot about external!");
document.UnattachedComments.ShouldBeNull();
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_Union_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnUnion".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(2);
var def = document.Definitions[0] as GraphQLUnionTypeDefinition;
def.Comment.Value.ShouldBe("very good union");
def.Types.Comment.Value.ShouldBe("comment for union members");
var ext = document.Definitions[1] as GraphQLUnionTypeExtension;
ext.Comment.Value.ShouldBe("forgot about C!");
document.UnattachedComments.ShouldBeNull();
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_on_Variable_Should_Read_Correctly(IgnoreOptions options)
{
string query = "CommentsOnVariables".ReadGraphQLFile();
var document = query.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions.First() as GraphQLOperationDefinition;
def.Variables.Count.ShouldBe(3);
def.Variables.Comment.Value.ShouldBe("very good variables definition");
def.Variables[0].Comment.ShouldNotBeNull().Value.ShouldBe("comment1");
def.Variables.Skip(1).First().Comment.ShouldBeNull();
def.Variables.Skip(2).First().Comment.ShouldNotBeNull().Value.ShouldBe("comment3");
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_On_SelectionSet_Should_Read_Correctly(IgnoreOptions options)
{
var document = @"
query {
# a comment below query
field1
field2
#second comment
field3
}
".Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions.First() as GraphQLOperationDefinition;
def.SelectionSet.Selections.Count.ShouldBe(3);
def.SelectionSet.Selections.First().Comment.ShouldNotBeNull().Value.ShouldBe(" a comment below query");
def.SelectionSet.Selections.Skip(1).First().Comment.ShouldBe(null);
def.SelectionSet.Selections.Skip(2).First().Comment.ShouldNotBeNull().Value.ShouldBe("second comment");
}
[Theory]
[InlineData(IgnoreOptions.None)]
//[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Comments_On_Enum_Definitions_Should_Read_Correctly(IgnoreOptions options)
{
var document = @"
# different animals
enum Animal {
#a cat
Cat
#a dog
Dog
Octopus
#bird is the word
Bird
}
input Parameter {
#any value
Value: String
}
scalar JSON
".Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(3);
var d1 = document.Definitions.First() as GraphQLEnumTypeDefinition;
d1.Name.Value.ShouldBe("Animal");
d1.Comment.ShouldNotBeNull().Value.ShouldBe(" different animals");
d1.Values[0].Name.Value.ShouldBe("Cat");
d1.Values[0].Comment.ShouldNotBeNull();
d1.Values[0].Comment.Value.ShouldBe("a cat");
d1.Values.Skip(2).First().Name.Value.ShouldBe("Octopus");
d1.Values.Skip(2).First().Comment.ShouldBeNull();
var d2 = document.Definitions.Skip(1).First() as GraphQLInputObjectTypeDefinition;
d2.Name.Value.ShouldBe("Parameter");
d2.Comment.ShouldBeNull();
d2.Fields.Count.ShouldBe(1);
d2.Fields[0].Comment.Value.ShouldBe("any value");
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
//[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Parse_FieldInput_HasCorrectLocations(IgnoreOptions options)
{
// { field }
var document = ParseGraphQLFieldSource(options);
document.Location.ShouldBe(new GraphQLLocation(0, 9)); // { field }
document.Definitions.First().Location.ShouldBe(new GraphQLLocation(0, 9)); // { field }
(document.Definitions.First() as GraphQLOperationDefinition).SelectionSet.Location.ShouldBe(new GraphQLLocation(0, 9)); // { field }
(document.Definitions.First() as GraphQLOperationDefinition).SelectionSet.Selections.First().Location.ShouldBe(new GraphQLLocation(2, 7)); // field
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Parse_FieldInput_HasOneOperationDefinition(IgnoreOptions options)
{
var document = ParseGraphQLFieldSource(options);
document.Definitions.First().Kind.ShouldBe(ASTNodeKind.OperationDefinition);
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Parse_FieldInput_NameIsNull(IgnoreOptions options)
{
var document = ParseGraphQLFieldSource(options);
GetSingleOperationDefinition(document).Name.ShouldBeNull();
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Parse_FieldInput_OperationIsQuery(IgnoreOptions options)
{
var document = ParseGraphQLFieldSource(options);
GetSingleOperationDefinition(document).Operation.ShouldBe(OperationType.Query);
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Parse_FieldInput_ReturnsDocumentNode(IgnoreOptions options)
{
var document = ParseGraphQLFieldSource(options);
document.Kind.ShouldBe(ASTNodeKind.Document);
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Parse_FieldInput_SelectionSetContainsSingleField(IgnoreOptions options)
{
var document = ParseGraphQLFieldSource(options);
GetSingleSelection(document).Kind.ShouldBe(ASTNodeKind.Field);
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
//[InlineData(IgnoreOptions.Locations)]
//[InlineData(IgnoreOptions.All)]
public void Parse_FieldWithOperationTypeAndNameInput_HasCorrectLocations(IgnoreOptions options)
{
// mutation Foo { field }
var document = ParseGraphQLFieldWithOperationTypeAndNameSource(options);
document.Location.ShouldBe(new GraphQLLocation(0, 22));
document.Definitions.First().Location.ShouldBe(new GraphQLLocation(0, 22));
(document.Definitions.First() as GraphQLOperationDefinition).Name.Location.ShouldBe(new GraphQLLocation(9, 12)); // Foo
(document.Definitions.First() as GraphQLOperationDefinition).SelectionSet.Location.ShouldBe(new GraphQLLocation(13, 22)); // { field }
(document.Definitions.First() as GraphQLOperationDefinition).SelectionSet.Selections.First().Location.ShouldBe(new GraphQLLocation(15, 20)); // field
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Parse_FieldWithOperationTypeAndNameInput_HasOneOperationDefinition(IgnoreOptions options)
{
var document = ParseGraphQLFieldWithOperationTypeAndNameSource(options);
document.Definitions.First().Kind.ShouldBe(ASTNodeKind.OperationDefinition);
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Parse_FieldWithOperationTypeAndNameInput_NameIsNull(IgnoreOptions options)
{
var document = ParseGraphQLFieldWithOperationTypeAndNameSource(options);
GetSingleOperationDefinition(document).Name.Value.ShouldBe("Foo");
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Parse_FieldWithOperationTypeAndNameInput_OperationIsQuery(IgnoreOptions options)
{
var document = ParseGraphQLFieldWithOperationTypeAndNameSource(options);
GetSingleOperationDefinition(document).Operation.ShouldBe(OperationType.Mutation);
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Parse_FieldWithOperationTypeAndNameInput_ReturnsDocumentNode(IgnoreOptions options)
{
var document = ParseGraphQLFieldWithOperationTypeAndNameSource(options);
document.Kind.ShouldBe(ASTNodeKind.Document);
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Parse_FieldWithOperationTypeAndNameInput_SelectionSetContainsSingleFieldWithOperationTypeAndNameSelection(IgnoreOptions options)
{
var document = ParseGraphQLFieldWithOperationTypeAndNameSource(options);
GetSingleSelection(document).Kind.ShouldBe(ASTNodeKind.Field);
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Parse_KitchenSink_DoesNotThrowError(IgnoreOptions options)
{
var document = "KitchenSink".ReadGraphQLFile().Parse(new ParserOptions { Ignore = options });
document.OperationsCount().ShouldBe(5);
document.FragmentsCount().ShouldBe(1);
document.FindFragmentDefinition("qwerty").ShouldBeNull();
document.FindFragmentDefinition("frag").ShouldNotBeNull();
document.OperationWithName("qwerty").ShouldBeNull();
document.OperationWithName("updateStory").ShouldNotBeNull().Name.Value.ShouldBe("updateStory");
document.OperationWithName("").ShouldNotBeNull().Name.Value.ShouldBe("queryName");
var typeDef = document.Definitions.OfType<GraphQLObjectTypeDefinition>().First(d => d.Name.Value == "Foo");
var fieldDef = typeDef.Fields.First(d => d.Name.Value == "three");
if (options.HasFlag(IgnoreOptions.Comments))
{
fieldDef.Comment.ShouldBeNull();
}
else
{
fieldDef.Comments.ShouldNotBeNull();
fieldDef.Comments.Count.ShouldBe(3);
fieldDef.Comments[0].Value.ShouldBe(" multiline comments");
fieldDef.Comments[1].Value.ShouldBe(" with very importand description #");
fieldDef.Comments[2].Value.ShouldBe(" # and symbol # and ##");
}
// Schema description
// https://github.com/graphql/graphql-spec/pull/466
var comments = document.Definitions.OfType<GraphQLSchemaDefinition>().First().Comments;
if (options.HasFlag(IgnoreOptions.Comments))
{
comments.ShouldBeNull();
}
else
{
comments.ShouldNotBeNull();
(comments[0].Value == " Copyright (c) 2015, Facebook, Inc.").ShouldBeTrue();
}
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Parse_NullInput_EmptyDocument(IgnoreOptions options)
{
var document = ((string)null).Parse(new ParserOptions { Ignore = options });
document.Definitions.ShouldBeEmpty();
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Parse_VariableInlineValues_DoesNotThrowError(IgnoreOptions options)
{
"{ field(complex: { a: { b: [ $var ] } }) }".Parse(new ParserOptions { Ignore = options });
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Should_Read_Directives_on_VariableDefinition(IgnoreOptions options)
{
var document = "query A($id: String @a @b(priority: 1, managed: true)) { name }".Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions[0].ShouldBeAssignableTo<GraphQLOperationDefinition>();
def.Variables.Count.ShouldBe(1);
def.Variables[0].Directives.Count.ShouldBe(2);
def.Variables[0].Directives[0].Name.Value.ShouldBe("a");
def.Variables[0].Directives[1].Name.Value.ShouldBe("b");
def.Variables[0].Directives[1].Arguments.Count.ShouldBe(2);
// ASTListNode small test
def.Variables.GetEnumerator().ShouldBe(((IEnumerable)def.Variables).GetEnumerator());
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Should_Read_Directives_on_OperationDefinition(IgnoreOptions options)
{
var document = "query A @easy { name }".Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions[0].ShouldBeAssignableTo<GraphQLOperationDefinition>();
def.Directives.Count.ShouldBe(1);
def.Directives[0].Name.Value.ShouldBe("easy");
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Should_Read_Directives_on_FragmentSpread(IgnoreOptions options)
{
var document = "query { ...spread1 @skip(if: false) }".Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions[0].ShouldBeAssignableTo<GraphQLOperationDefinition>();
var spread = def.SelectionSet.Selections[0].ShouldBeAssignableTo<GraphQLFragmentSpread>();
spread.Directives.Count.ShouldBe(1);
spread.Directives[0].Name.Value.ShouldBe("skip");
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Should_Read_Directives_on_FragmentDefinition(IgnoreOptions options)
{
var document = "fragment f on User @documented { name }".Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions[0].ShouldBeAssignableTo<GraphQLFragmentDefinition>();
def.Directives.Count.ShouldBe(1);
def.Directives[0].Name.Value.ShouldBe("documented");
}
private static GraphQLOperationDefinition GetSingleOperationDefinition(GraphQLDocument document)
{
return (GraphQLOperationDefinition)document.Definitions.Single();
}
private static ASTNode GetSingleSelection(GraphQLDocument document)
{
return GetSingleOperationDefinition(document).SelectionSet.Selections.Single();
}
private static GraphQLDocument ParseGraphQLFieldSource(IgnoreOptions options) => "{ field }".Parse(new ParserOptions { Ignore = options });
private static GraphQLDocument ParseGraphQLFieldWithOperationTypeAndNameSource(IgnoreOptions options) => "mutation Foo { field }".Parse(new ParserOptions { Ignore = options });
[Theory]
[InlineData("directive @dir repeatable on FIELD_DEFINITION", true)]
[InlineData("directive @dir(a: Int) repeatable on FIELD_DEFINITION", true)]
[InlineData("directive @dir on FIELD_DEFINITION | ENUM_VALUE", false)]
[InlineData("directive @dir on | FIELD_DEFINITION | ENUM_VALUE", false)]
[InlineData(@"directive @dir on
FIELD_DEFINITION | ENUM_VALUE", false)]
[InlineData(@"directive @dir on
FIELD_DEFINITION
| ENUM_VALUE", false)]
[InlineData(@"directive @dir on
| FIELD_DEFINITION
| ENUM_VALUE", false)]
[InlineData(@"directive @dir on
| FIELD_DEFINITION
| ENUM_VALUE", false)]
public void Should_Parse_Directives(string text, bool repeatable)
{
var document = text.Parse();
document.ShouldNotBeNull();
document.Definitions.Count.ShouldBe(1);
document.Definitions[0].ShouldBeAssignableTo<GraphQLDirectiveDefinition>().Repeatable.ShouldBe(repeatable);
}
// http://spec.graphql.org/October2021/#sec--specifiedBy
[Fact]
public void Should_Parse_SpecifiedBy()
{
string text = @"scalar UUID @specifiedBy(url: ""https://tools.ietf.org/html/rfc4122"")";
var document = text.Parse();
document.ShouldNotBeNull();
document.Definitions.Count.ShouldBe(1);
var def = document.Definitions[0].ShouldBeAssignableTo<GraphQLScalarTypeDefinition>();
def.Directives.Count.ShouldBe(1);
def.Directives[0].Name.Value.ShouldBe("specifiedBy");
def.Directives[0].Arguments.Count.ShouldBe(1);
def.Directives[0].Arguments[0].Name.Value.ShouldBe("url");
var value = def.Directives[0].Arguments[0].Value.ShouldBeAssignableTo<GraphQLStringValue>();
value.Value.ShouldBe("https://tools.ietf.org/html/rfc4122");
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Should_Parse_Interfaces_Implemented_By_Interface(IgnoreOptions options)
{
string text = "InterfacesOnInterface".ReadGraphQLFile();
var document = text.Parse(new ParserOptions { Ignore = options });
document.Definitions.Count.ShouldBe(4);
var def1 = document.Definitions[0].ShouldBeAssignableTo<GraphQLInterfaceTypeDefinition>();
def1.Name.Value.ShouldBe("Dog");
def1.Interfaces.ShouldBeNull();
var def2 = document.Definitions[1].ShouldBeAssignableTo<GraphQLInterfaceTypeDefinition>();
def2.Name.Value.ShouldBe("Dog");
def2.Interfaces.Count.ShouldBe(1);
def2.Interfaces[0].Name.Value.ShouldBe("Eat");
var def3 = document.Definitions[2].ShouldBeAssignableTo<GraphQLInterfaceTypeDefinition>();
def3.Name.Value.ShouldBe("Dog");
def3.Interfaces.Count.ShouldBe(2);
def3.Interfaces[0].Name.Value.ShouldBe("Eat");
def3.Interfaces[1].Name.Value.ShouldBe("Sleep");
var def4 = document.Definitions[3].ShouldBeAssignableTo<GraphQLInterfaceTypeDefinition>();
def4.Name.Value.ShouldBe("Dog");
def4.Interfaces.Count.ShouldBe(2);
def4.Interfaces[0].Name.Value.ShouldBe("Eat");
def4.Interfaces[1].Name.Value.ShouldBe("Sleep");
def4.Fields.Count.ShouldBe(1);
def4.Fields[0].Name.Value.ShouldBe("name");
}
[Theory]
[InlineData("union Animal = Cat | Dog")]
[InlineData("union Animal = | Cat | Dog")]
[InlineData(@"union Animal =
Cat | Dog")]
[InlineData(@"union Animal =
Cat
| Dog")]
[InlineData(@"union Animal =
| Cat
| Dog")]
[InlineData(@"union Animal =
| Cat
| Dog")]
public void Should_Parse_Unions(string text)
{
var document = text.Parse();
document.ShouldNotBeNull();
}
[Theory]
[InlineData("extend scalar Foo @exportable", ASTNodeKind.ScalarTypeExtension)]
[InlineData("extend type Foo implements Bar @exportable { a: String }", ASTNodeKind.ObjectTypeExtension)]
[InlineData("extend type Foo implements Bar @exportable", ASTNodeKind.ObjectTypeExtension)]
[InlineData("extend type Foo implements Bar { a: String }", ASTNodeKind.ObjectTypeExtension)]
[InlineData("extend type Foo implements Bar", ASTNodeKind.ObjectTypeExtension)]
[InlineData("extend type Foo { a: String }", ASTNodeKind.ObjectTypeExtension)]
[InlineData("extend interface Foo implements Bar @exportable { a: String }", ASTNodeKind.InterfaceTypeExtension)]
[InlineData("extend interface Foo implements Bar @exportable", ASTNodeKind.InterfaceTypeExtension)]
[InlineData("extend interface Foo implements Bar { a: String }", ASTNodeKind.InterfaceTypeExtension)]
[InlineData("extend interface Foo { a: String }", ASTNodeKind.InterfaceTypeExtension)]
[InlineData("extend interface Foo implements Bar", ASTNodeKind.InterfaceTypeExtension)]
[InlineData("extend union Foo @exportable = A | B", ASTNodeKind.UnionTypeExtension)]
[InlineData("extend union Foo = A | B", ASTNodeKind.UnionTypeExtension)]
[InlineData("extend union Foo @exportable", ASTNodeKind.UnionTypeExtension)]
[InlineData("extend enum Foo @exportable { ONE TWO }", ASTNodeKind.EnumTypeExtension)]
[InlineData("extend enum Foo { ONE TWO }", ASTNodeKind.EnumTypeExtension)]
[InlineData("extend enum Foo @exportable", ASTNodeKind.EnumTypeExtension)]
[InlineData("extend input Foo @exportable { a: String }", ASTNodeKind.InputObjectTypeExtension)]
[InlineData("extend input Foo { a: String }", ASTNodeKind.InputObjectTypeExtension)]
[InlineData("extend input Foo @exportable", ASTNodeKind.InputObjectTypeExtension)]
public void Should_Parse_Extensions(string text, ASTNodeKind kind)
{
var document = text.Parse();
document.ShouldNotBeNull();
document.Definitions[0].Kind.ShouldBe(kind);
}
[Theory]
[InlineData("scalar Empty", ASTNodeKind.ScalarTypeDefinition)]
[InlineData("union Empty", ASTNodeKind.UnionTypeDefinition)]
[InlineData("type Empty", ASTNodeKind.ObjectTypeDefinition)]
[InlineData("input Empty", ASTNodeKind.InputObjectTypeDefinition)]
[InlineData("interface Empty", ASTNodeKind.InterfaceTypeDefinition)]
[InlineData("enum Empty", ASTNodeKind.EnumTypeDefinition)]
public void Should_Parse_Empty_Types(string text, ASTNodeKind kind)
{
var document = text.Parse();
document.ShouldNotBeNull();
document.Definitions[0].Kind.ShouldBe(kind);
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Descriptions_Should_Read_Correctly(IgnoreOptions options)
{
var document = @"
""Super schema""
schema {
query: String
}
""A JSON scalar""
scalar JSON
""""""
Human type
""""""
type Human {
""""""
Name of human
""""""
name: String
""Test""
test(
""desc""
arg: Int
): Int
}
""Test interface""
interface TestInterface {
""Object name""
name: String
}
""""""
Test union
""""""
union TestUnion = Test1 | Test2
""Example enum""
enum Colors {
""Red"" RED
""Blue"" BLUE
}
""""""
This is an example input object
Line two of the description
""""""
input TestInputObject {
""""""
The value of the input object
(any JSON value is accepted)
""""""
Value: JSON
}
""Test directive""
directive @TestDirective (
""Example""
Value: Int
) on QUERY
".Parse(new ParserOptions { Ignore = options });
var defs = document.Definitions;
defs.Count.ShouldBe(8);
var schemaDef = defs.Single(x => x is GraphQLSchemaDefinition) as GraphQLSchemaDefinition;
schemaDef.Description.Value.ShouldBe("Super schema");
var scalarDef = defs.Single(x => x is GraphQLScalarTypeDefinition) as GraphQLScalarTypeDefinition;
scalarDef.Name.Value.ShouldBe("JSON");
scalarDef.Description.Value.ShouldBe("A JSON scalar");
var objectDef = defs.Single(x => x is GraphQLObjectTypeDefinition) as GraphQLObjectTypeDefinition;
objectDef.Name.Value.ShouldBe("Human");
objectDef.Description.Value.ShouldBe("Human type");
objectDef.Fields.Count.ShouldBe(2);
objectDef.Fields[0].Name.Value.ShouldBe("name");
objectDef.Fields[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("String");
objectDef.Fields[0].Description.Value.ShouldBe("Name of human");
objectDef.Fields[1].Name.Value.ShouldBe("test");
objectDef.Fields[1].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("Int");
objectDef.Fields[1].Description.Value.ShouldBe("Test");
objectDef.Fields[1].Arguments.Count.ShouldBe(1);
objectDef.Fields[1].Arguments[0].Name.Value.ShouldBe("arg");
objectDef.Fields[1].Arguments[0].Description.Value.ShouldBe("desc");
objectDef.Fields[1].Arguments[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("Int");
var interfaceDef = defs.Single(x => x is GraphQLInterfaceTypeDefinition) as GraphQLInterfaceTypeDefinition;
interfaceDef.Name.Value.ShouldBe("TestInterface");
interfaceDef.Description.Value.ShouldBe("Test interface");
interfaceDef.Fields.Count.ShouldBe(1);
interfaceDef.Fields[0].Name.Value.ShouldBe("name");
interfaceDef.Fields[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("String");
interfaceDef.Fields[0].Description.Value.ShouldBe("Object name");
var unionDef = defs.Single(x => x is GraphQLUnionTypeDefinition) as GraphQLUnionTypeDefinition;
unionDef.Name.Value.ShouldBe("TestUnion");
unionDef.Description.Value.ShouldBe("Test union");
unionDef.Types.Count.ShouldBe(2);
unionDef.Types[0].Name.Value.ShouldBe("Test1");
unionDef.Types[1].Name.Value.ShouldBe("Test2");
var enumDef = defs.Single(x => x is GraphQLEnumTypeDefinition) as GraphQLEnumTypeDefinition;
enumDef.Name.Value.ShouldBe("Colors");
enumDef.Description.Value.ShouldBe("Example enum");
enumDef.Values.Count.ShouldBe(2);
enumDef.Values[0].Name.Value.ShouldBe("RED");
enumDef.Values[0].Description.Value.ShouldBe("Red");
enumDef.Values[1].Name.Value.ShouldBe("BLUE");
enumDef.Values[1].Description.Value.ShouldBe("Blue");
var inputDef = defs.Single(x => x is GraphQLInputObjectTypeDefinition) as GraphQLInputObjectTypeDefinition;
inputDef.Name.Value.ShouldBe("TestInputObject");
inputDef.Description.Value.ShouldBe("This is an example input object\nLine two of the description");
inputDef.Fields.Count.ShouldBe(1);
inputDef.Fields[0].Name.Value.ShouldBe("Value");
inputDef.Fields[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("JSON");
inputDef.Fields[0].Description.Value.ShouldBe("The value of the input object\n (any JSON value is accepted)");
var directiveDef = defs.Single(x => x is GraphQLDirectiveDefinition) as GraphQLDirectiveDefinition;
directiveDef.Name.Value.ShouldBe("TestDirective");
directiveDef.Description.Value.ShouldBe("Test directive");
directiveDef.Arguments.Count.ShouldBe(1);
directiveDef.Arguments[0].Name.Value.ShouldBe("Value");
directiveDef.Arguments[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("Int");
directiveDef.Arguments[0].Description.Value.ShouldBe("Example");
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Descriptions_WithComments_Should_Read_Correctly_1(IgnoreOptions options)
{
var document = @"
# comment -1
""Super schema""
# comment 0
schema {
query: String
}
# comment 1
""A JSON scalar""
# comment 2
scalar JSON
# comment 3
""""""
Human type
""""""
# comment 4
type Human {
# comment 5
""""""
Name of human
""""""
# comment 6
name: String
# comment 7
""Test""
# comment 8
test(
# comment 9
""desc""
# comment 10
arg: Int
): Int
}
# comment 11
""Test interface""
# comment 12
interface TestInterface {
# comment 13
""Object name""
# comment 14
name: String
}
# comment 15
""""""
Test union
""""""
# comment 16
union TestUnion = Test1 | Test2
# comment 17
""Example enum""
# comment 18
enum Colors {
# comment 19
""Red""
# comment 20
RED
# comment 21
""Blue""
# comment 22
BLUE
}
# comment 23
""""""
This is an example input object
Line two of the description
""""""
# comment 24
input TestInputObject {
# comment 25
""""""
The value of the input object
(any JSON value is accepted)
""""""
# comment 26
Value: JSON
}
# comment 27
""Test directive""
# comment 28
directive @TestDirective (
# comment 29
""Example""
# comment 30
Value: Int
) on QUERY
".Parse(new ParserOptions { Ignore = options });
var defs = document.Definitions;
defs.Count.ShouldBe(8);
var parseComments = !options.HasFlag(IgnoreOptions.Comments);
var schemaDef = defs.Single(x => x is GraphQLSchemaDefinition) as GraphQLSchemaDefinition;
schemaDef.Description.Value.ShouldBe("Super schema");
if (parseComments)
schemaDef.Comment.Value.ShouldBe(" comment 0");
var scalarDef = defs.Single(x => x is GraphQLScalarTypeDefinition) as GraphQLScalarTypeDefinition;
scalarDef.Name.Value.ShouldBe("JSON");
scalarDef.Description.Value.ShouldBe("A JSON scalar");
if (parseComments)
scalarDef.Comment.Value.ShouldBe(" comment 2");
var objectDef = defs.Single(x => x is GraphQLObjectTypeDefinition) as GraphQLObjectTypeDefinition;
objectDef.Name.Value.ShouldBe("Human");
objectDef.Description.Value.ShouldBe("Human type");
if (parseComments)
objectDef.Comment.Value.ShouldBe(" comment 4");
objectDef.Fields.Count.ShouldBe(2);
objectDef.Fields[0].Name.Value.ShouldBe("name");
objectDef.Fields[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("String");
objectDef.Fields[0].Description.Value.ShouldBe("Name of human");
if (parseComments)
objectDef.Fields[0].Comment.Value.ShouldBe(" comment 6");
objectDef.Fields[1].Name.Value.ShouldBe("test");
objectDef.Fields[1].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("Int");
objectDef.Fields[1].Description.Value.ShouldBe("Test");
if (parseComments)
objectDef.Fields[1].Comment.Value.ShouldBe(" comment 8");
objectDef.Fields[1].Arguments.Count.ShouldBe(1);
objectDef.Fields[1].Arguments[0].Name.Value.ShouldBe("arg");
objectDef.Fields[1].Arguments[0].Description.Value.ShouldBe("desc");
objectDef.Fields[1].Arguments[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("Int");
if (parseComments)
objectDef.Fields[1].Arguments[0].Comment.Value.ShouldBe(" comment 10");
var interfaceDef = defs.Single(x => x is GraphQLInterfaceTypeDefinition) as GraphQLInterfaceTypeDefinition;
interfaceDef.Name.Value.ShouldBe("TestInterface");
interfaceDef.Description.Value.ShouldBe("Test interface");
if (parseComments)
interfaceDef.Comment.Value.ShouldBe(" comment 12");
interfaceDef.Fields.Count.ShouldBe(1);
interfaceDef.Fields[0].Name.Value.ShouldBe("name");
interfaceDef.Fields[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("String");
interfaceDef.Fields[0].Description.Value.ShouldBe("Object name");
if (parseComments)
interfaceDef.Fields[0].Comment.Value.ShouldBe(" comment 14");
var unionDef = defs.Single(x => x is GraphQLUnionTypeDefinition) as GraphQLUnionTypeDefinition;
unionDef.Name.Value.ShouldBe("TestUnion");
unionDef.Description.Value.ShouldBe("Test union");
if (parseComments)
unionDef.Comment.Value.ShouldBe(" comment 16");
unionDef.Types.Count.ShouldBe(2);
unionDef.Types[0].Name.Value.ShouldBe("Test1");
unionDef.Types[1].Name.Value.ShouldBe("Test2");
var enumDef = defs.Single(x => x is GraphQLEnumTypeDefinition) as GraphQLEnumTypeDefinition;
enumDef.Name.Value.ShouldBe("Colors");
enumDef.Description.Value.ShouldBe("Example enum");
if (parseComments)
enumDef.Comment.Value.ShouldBe(" comment 18");
enumDef.Values.Count.ShouldBe(2);
enumDef.Values[0].Name.Value.ShouldBe("RED");
enumDef.Values[0].Description.Value.ShouldBe("Red");
if (parseComments)
enumDef.Values[0].Comment.Value.ShouldBe(" comment 20");
enumDef.Values[1].Name.Value.ShouldBe("BLUE");
enumDef.Values[1].Description.Value.ShouldBe("Blue");
if (parseComments)
enumDef.Values[1].Comment.Value.ShouldBe(" comment 22");
var inputDef = defs.Single(x => x is GraphQLInputObjectTypeDefinition) as GraphQLInputObjectTypeDefinition;
inputDef.Name.Value.ShouldBe("TestInputObject");
inputDef.Description.Value.ShouldBe("This is an example input object\nLine two of the description");
if (parseComments)
inputDef.Comment.Value.ShouldBe(" comment 24");
inputDef.Fields.Count.ShouldBe(1);
inputDef.Fields[0].Name.Value.ShouldBe("Value");
inputDef.Fields[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("JSON");
inputDef.Fields[0].Description.Value.ShouldBe("The value of the input object\n (any JSON value is accepted)");
if (parseComments)
inputDef.Fields[0].Comment.Value.ShouldBe(" comment 26");
var directiveDef = defs.Single(x => x is GraphQLDirectiveDefinition) as GraphQLDirectiveDefinition;
directiveDef.Name.Value.ShouldBe("TestDirective");
directiveDef.Description.Value.ShouldBe("Test directive");
if (parseComments)
directiveDef.Comment.Value.ShouldBe(" comment 28");
directiveDef.Arguments.Count.ShouldBe(1);
directiveDef.Arguments[0].Name.Value.ShouldBe("Value");
directiveDef.Arguments[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("Int");
directiveDef.Arguments[0].Description.Value.ShouldBe("Example");
if (parseComments)
directiveDef.Arguments[0].Comment.Value.ShouldBe(" comment 30");
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Descriptions_WithComments_Should_Read_Correctly_2(IgnoreOptions options)
{
var document = @"
""Super schema""
# comment 1
schema {
query: String
}
""A JSON scalar""
# comment 2
scalar JSON
""""""
Human type
""""""
# comment 4
type Human {
""""""
Name of human
""""""
# comment 6
name: String
""Test""
# comment 8
test(
""desc""
# comment 10
arg: Int
): Int
}
""Test interface""
# comment 12
interface TestInterface {
""Object name""
# comment 14
name: String
}
""""""
Test union
""""""
# comment 16
union TestUnion = Test1 | Test2
""Example enum""
# comment 18
enum Colors {
""Red""
# comment 20
RED
""Blue""
# comment 22
BLUE
}
""""""
This is an example input object
Line two of the description
""""""
# comment 24
input TestInputObject {
""""""
The value of the input object
(any JSON value is accepted)
""""""
# comment 26
Value: JSON
}
""Test directive""
# comment 28
directive @TestDirective (
""Example""
# comment 30
Value: Int
) on QUERY
".Parse(new ParserOptions { Ignore = options });
var defs = document.Definitions;
defs.Count.ShouldBe(8);
var parseComments = !options.HasFlag(IgnoreOptions.Comments);
var schemaDef = defs.Single(x => x is GraphQLSchemaDefinition) as GraphQLSchemaDefinition;
schemaDef.Description.Value.ShouldBe("Super schema");
if (parseComments)
schemaDef.Comment.Value.ShouldBe(" comment 1");
var scalarDef = defs.Single(x => x is GraphQLScalarTypeDefinition) as GraphQLScalarTypeDefinition;
scalarDef.Name.Value.ShouldBe("JSON");
scalarDef.Description.Value.ShouldBe("A JSON scalar");
if (parseComments)
scalarDef.Comment.Value.ShouldBe(" comment 2");
var objectDef = defs.Single(x => x is GraphQLObjectTypeDefinition) as GraphQLObjectTypeDefinition;
objectDef.Name.Value.ShouldBe("Human");
objectDef.Description.Value.ShouldBe("Human type");
if (parseComments)
objectDef.Comment.Value.ShouldBe(" comment 4");
objectDef.Fields.Count.ShouldBe(2);
objectDef.Fields[0].Name.Value.ShouldBe("name");
objectDef.Fields[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("String");
objectDef.Fields[0].Description.Value.ShouldBe("Name of human");
if (parseComments)
objectDef.Fields[0].Comment.Value.ShouldBe(" comment 6");
objectDef.Fields[1].Name.Value.ShouldBe("test");
objectDef.Fields[1].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("Int");
objectDef.Fields[1].Description.Value.ShouldBe("Test");
if (parseComments)
objectDef.Fields[1].Comment.Value.ShouldBe(" comment 8");
objectDef.Fields[1].Arguments.Count.ShouldBe(1);
objectDef.Fields[1].Arguments[0].Name.Value.ShouldBe("arg");
objectDef.Fields[1].Arguments[0].Description.Value.ShouldBe("desc");
objectDef.Fields[1].Arguments[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("Int");
if (parseComments)
objectDef.Fields[1].Arguments[0].Comment.Value.ShouldBe(" comment 10");
var interfaceDef = defs.Single(x => x is GraphQLInterfaceTypeDefinition) as GraphQLInterfaceTypeDefinition;
interfaceDef.Name.Value.ShouldBe("TestInterface");
interfaceDef.Description.Value.ShouldBe("Test interface");
if (parseComments)
interfaceDef.Comment.Value.ShouldBe(" comment 12");
interfaceDef.Fields.Count.ShouldBe(1);
interfaceDef.Fields[0].Name.Value.ShouldBe("name");
interfaceDef.Fields[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("String");
interfaceDef.Fields[0].Description.Value.ShouldBe("Object name");
if (parseComments)
interfaceDef.Fields[0].Comment.Value.ShouldBe(" comment 14");
var unionDef = defs.Single(x => x is GraphQLUnionTypeDefinition) as GraphQLUnionTypeDefinition;
unionDef.Name.Value.ShouldBe("TestUnion");
unionDef.Description.Value.ShouldBe("Test union");
if (parseComments)
unionDef.Comment.Value.ShouldBe(" comment 16");
unionDef.Types.Count.ShouldBe(2);
unionDef.Types[0].Name.Value.ShouldBe("Test1");
unionDef.Types[1].Name.Value.ShouldBe("Test2");
var enumDef = defs.Single(x => x is GraphQLEnumTypeDefinition) as GraphQLEnumTypeDefinition;
enumDef.Name.Value.ShouldBe("Colors");
enumDef.Description.Value.ShouldBe("Example enum");
if (parseComments)
enumDef.Comment.Value.ShouldBe(" comment 18");
enumDef.Values.Count.ShouldBe(2);
enumDef.Values[0].Name.Value.ShouldBe("RED");
enumDef.Values[0].Description.Value.ShouldBe("Red");
if (parseComments)
enumDef.Values[0].Comment.Value.ShouldBe(" comment 20");
enumDef.Values[1].Name.Value.ShouldBe("BLUE");
enumDef.Values[1].Description.Value.ShouldBe("Blue");
if (parseComments)
enumDef.Values[1].Comment.Value.ShouldBe(" comment 22");
var inputDef = defs.Single(x => x is GraphQLInputObjectTypeDefinition) as GraphQLInputObjectTypeDefinition;
inputDef.Name.Value.ShouldBe("TestInputObject");
inputDef.Description.Value.ShouldBe("This is an example input object\nLine two of the description");
if (parseComments)
inputDef.Comment.Value.ShouldBe(" comment 24");
inputDef.Fields.Count.ShouldBe(1);
inputDef.Fields[0].Name.Value.ShouldBe("Value");
inputDef.Fields[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("JSON");
inputDef.Fields[0].Description.Value.ShouldBe("The value of the input object\n (any JSON value is accepted)");
if (parseComments)
inputDef.Fields[0].Comment.Value.ShouldBe(" comment 26");
var directiveDef = defs.Single(x => x is GraphQLDirectiveDefinition) as GraphQLDirectiveDefinition;
directiveDef.Name.Value.ShouldBe("TestDirective");
directiveDef.Description.Value.ShouldBe("Test directive");
if (parseComments)
directiveDef.Comment.Value.ShouldBe(" comment 28");
directiveDef.Arguments.Count.ShouldBe(1);
directiveDef.Arguments[0].Name.Value.ShouldBe("Value");
directiveDef.Arguments[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("Int");
directiveDef.Arguments[0].Description.Value.ShouldBe("Example");
if (parseComments)
directiveDef.Arguments[0].Comment.Value.ShouldBe(" comment 30");
}
[Theory]
[InlineData(IgnoreOptions.None)]
[InlineData(IgnoreOptions.Comments)]
[InlineData(IgnoreOptions.Locations)]
[InlineData(IgnoreOptions.All)]
public void Descriptions_WithComments_Should_Read_Correctly_3(IgnoreOptions options)
{
var document = @"
# comment 0
""Super schema""
schema {
query: String
}
# comment 1
""A JSON scalar""
scalar JSON
# comment 3
""""""
Human type
""""""
type Human {
# comment 5
""""""
Name of human
""""""
name: String
# comment 7
""Test""
test(
# comment 9
""desc""
arg: Int
): Int
}
# comment 11
""Test interface""
interface TestInterface {
# comment 13
""Object name""
name: String
}
# comment 15
""""""
Test union
""""""
union TestUnion = Test1 | Test2
# comment 17
""Example enum""
enum Colors {
# comment 19
""Red""
RED
# comment 21
""Blue""
BLUE
}
# comment 23
""""""
This is an example input object
Line two of the description
""""""
input TestInputObject {
# comment 25
""""""
The value of the input object
(any JSON value is accepted)
""""""
Value: JSON
}
# comment 27
""Test directive""
directive @TestDirective (
# comment 29
""Example""
Value: Int
) on QUERY
".Parse(new ParserOptions { Ignore = options });
var defs = document.Definitions;
defs.Count.ShouldBe(8);
var parseComments = !options.HasFlag(IgnoreOptions.Comments);
var schemaDef = defs.Single(x => x is GraphQLSchemaDefinition) as GraphQLSchemaDefinition;
schemaDef.Description.Value.ShouldBe("Super schema");
if (parseComments)
schemaDef.Comment.Value.ShouldBe(" comment 0");
var scalarDef = defs.Single(x => x is GraphQLScalarTypeDefinition) as GraphQLScalarTypeDefinition;
scalarDef.Name.Value.ShouldBe("JSON");
scalarDef.Description.Value.ShouldBe("A JSON scalar");
if (parseComments)
scalarDef.Comment.Value.ShouldBe(" comment 1");
var objectDef = defs.Single(x => x is GraphQLObjectTypeDefinition) as GraphQLObjectTypeDefinition;
objectDef.Name.Value.ShouldBe("Human");
objectDef.Description.Value.ShouldBe("Human type");
if (parseComments)
objectDef.Comment.Value.ShouldBe(" comment 3");
objectDef.Fields.Count.ShouldBe(2);
objectDef.Fields[0].Name.Value.ShouldBe("name");
objectDef.Fields[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("String");
objectDef.Fields[0].Description.Value.ShouldBe("Name of human");
if (parseComments)
objectDef.Fields[0].Comment.Value.ShouldBe(" comment 5");
objectDef.Fields[1].Name.Value.ShouldBe("test");
objectDef.Fields[1].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("Int");
objectDef.Fields[1].Description.Value.ShouldBe("Test");
if (parseComments)
objectDef.Fields[1].Comment.Value.ShouldBe(" comment 7");
objectDef.Fields[1].Arguments.Count.ShouldBe(1);
objectDef.Fields[1].Arguments[0].Name.Value.ShouldBe("arg");
objectDef.Fields[1].Arguments[0].Description.Value.ShouldBe("desc");
objectDef.Fields[1].Arguments[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("Int");
if (parseComments)
objectDef.Fields[1].Arguments[0].Comment.Value.ShouldBe(" comment 9");
var interfaceDef = defs.Single(x => x is GraphQLInterfaceTypeDefinition) as GraphQLInterfaceTypeDefinition;
interfaceDef.Name.Value.ShouldBe("TestInterface");
interfaceDef.Description.Value.ShouldBe("Test interface");
if (parseComments)
interfaceDef.Comment.Value.ShouldBe(" comment 11");
interfaceDef.Fields.Count.ShouldBe(1);
interfaceDef.Fields[0].Name.Value.ShouldBe("name");
interfaceDef.Fields[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("String");
interfaceDef.Fields[0].Description.Value.ShouldBe("Object name");
if (parseComments)
interfaceDef.Fields[0].Comment.Value.ShouldBe(" comment 13");
var unionDef = defs.Single(x => x is GraphQLUnionTypeDefinition) as GraphQLUnionTypeDefinition;
unionDef.Name.Value.ShouldBe("TestUnion");
unionDef.Description.Value.ShouldBe("Test union");
if (parseComments)
unionDef.Comment.Value.ShouldBe(" comment 15");
unionDef.Types.Count.ShouldBe(2);
unionDef.Types[0].Name.Value.ShouldBe("Test1");
unionDef.Types[1].Name.Value.ShouldBe("Test2");
var enumDef = defs.Single(x => x is GraphQLEnumTypeDefinition) as GraphQLEnumTypeDefinition;
enumDef.Name.Value.ShouldBe("Colors");
enumDef.Description.Value.ShouldBe("Example enum");
if (parseComments)
enumDef.Comment.Value.ShouldBe(" comment 17");
enumDef.Values.Count.ShouldBe(2);
enumDef.Values[0].Name.Value.ShouldBe("RED");
enumDef.Values[0].Description.Value.ShouldBe("Red");
if (parseComments)
enumDef.Values[0].Comment.Value.ShouldBe(" comment 19");
enumDef.Values[1].Name.Value.ShouldBe("BLUE");
enumDef.Values[1].Description.Value.ShouldBe("Blue");
if (parseComments)
enumDef.Values[1].Comment.Value.ShouldBe(" comment 21");
var inputDef = defs.Single(x => x is GraphQLInputObjectTypeDefinition) as GraphQLInputObjectTypeDefinition;
inputDef.Name.Value.ShouldBe("TestInputObject");
inputDef.Description.Value.ShouldBe("This is an example input object\nLine two of the description");
if (parseComments)
inputDef.Comment.Value.ShouldBe(" comment 23");
inputDef.Fields.Count.ShouldBe(1);
inputDef.Fields[0].Name.Value.ShouldBe("Value");
inputDef.Fields[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("JSON");
inputDef.Fields[0].Description.Value.ShouldBe("The value of the input object\n (any JSON value is accepted)");
if (parseComments)
inputDef.Fields[0].Comment.Value.ShouldBe(" comment 25");
var directiveDef = defs.Single(x => x is GraphQLDirectiveDefinition) as GraphQLDirectiveDefinition;
directiveDef.Name.Value.ShouldBe("TestDirective");
directiveDef.Description.Value.ShouldBe("Test directive");
if (parseComments)
directiveDef.Comment.Value.ShouldBe(" comment 27");
directiveDef.Arguments.Count.ShouldBe(1);
directiveDef.Arguments[0].Name.Value.ShouldBe("Value");
directiveDef.Arguments[0].Type.ShouldBeAssignableTo<GraphQLNamedType>().Name.Value.ShouldBe("Int");
directiveDef.Arguments[0].Description.Value.ShouldBe("Example");
if (parseComments)
directiveDef.Arguments[0].Comment.Value.ShouldBe(" comment 29");
}
}
| |
// 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.Linq.Expressions;
using Microsoft.CSharp.RuntimeBinder;
using Xunit;
namespace System.Dynamic.Tests
{
public class DynamicObjectTests
{
// We'll test trying to access fields dynamically, but the compiler won't see that
// so disable CS0649.
#pragma warning disable 649
private class TestDynamicBase : DynamicObject
{
private Dictionary<int, int> _dictionary = new Dictionary<int, int>();
public int Field;
public readonly int ReadonlyField;
public int HideField;
public int Property { get; set; }
public int ReadonlyProperty => 0;
public int Method(int argument) => argument;
public virtual int VirtualProperty { get; set; }
public virtual int VirtualReadonlyProperty => 1;
public virtual int VirtualMethod(int argument) => argument;
public int HideProperty { get; set; }
public int HideMethod(int argument) => argument;
public int this[int index]
{
get { return _dictionary[index]; }
set { _dictionary[index] = value; }
}
}
private class TestDynamic : TestDynamicBase
{
public new int HideField;
public override int VirtualProperty { get; set; }
public override int VirtualReadonlyProperty => 2;
public override int VirtualMethod(int argument) => argument * 2;
public new int HideProperty { get; set; }
public new int HideMethod { get; set; }
}
#pragma warning restore 649
private class TestDynamicFagile : TestDynamic
{
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
throw new Exception();
}
}
private class TestDynamicNameReflective : TestDynamic
{
// Returns the name of the property back as the result, but is a stickler for .NET naming
// conventions and returns false if the first character isn't uppercase
// (Correct handling of Unicode category Lt omitted)
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
string name = binder.Name;
if (char.IsUpper(name[0]))
{
result = binder.Name;
return true;
}
result = null;
return false;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
string name = binder.Name;
if (char.IsUpper(name[0]))
{
// Allows set (as noop) if it means that it's being given the same value the get
// above would return anyway.
if (value as string != name)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
return true;
}
return false;
}
}
private class TestDynamicNameReflectiveNotOverride : TestDynamic
{
// Like TestDynamicNameReflective but hides rather than overiding.
// Because DynamicObject reflects upon itself to see if these methods are
// overridden, we test this override-detection against finding hiding
// methods.
public new bool TryGetMember(GetMemberBinder binder, out object result)
{
string name = binder.Name;
if (char.IsUpper(name[0]))
{
result = binder.Name;
return true;
}
result = null;
return false;
}
public new bool TrySetMember(SetMemberBinder binder, object value)
{
string name = binder.Name;
if (char.IsUpper(name[0]))
{
// Allows set (as noop) if it means that it's being given the same value the get
// above would return anyway.
if (value as string != name)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
return true;
}
return false;
}
}
private class SetOnlyProperties : DynamicObject
{
public override bool TrySetMember(SetMemberBinder binder, object value)
{
return true;
}
}
private class DynamicallyConvertable : DynamicObject
{
public override bool TryConvert(ConvertBinder binder, out object result)
{
if (binder.ReturnType == typeof(string))
{
result = nameof(DynamicallyConvertable);
return true;
}
if (binder.ReturnType == typeof(DateTime) && binder.Explicit)
{
result = new DateTime(1991, 8, 6);
return true;
}
result = null;
return false;
}
public static explicit operator DateTimeOffset(DynamicallyConvertable source) =>
new DateTimeOffset(1991, 8, 6, 0, 0, 0, new TimeSpan(2, 0, 0));
public static implicit operator Uri(DynamicallyConvertable source) =>
new Uri("http://example.net/");
}
private class DynamicallyConvertableNotOverride : DynamicObject
{
public new bool TryConvert(ConvertBinder binder, out object result)
{
if (binder.ReturnType == typeof(string))
{
result = nameof(DynamicallyConvertable);
return true;
}
if (binder.ReturnType == typeof(DateTime) && binder.Explicit)
{
result = new DateTime(1991, 8, 6);
return true;
}
result = null;
return false;
}
public static explicit operator DateTimeOffset(DynamicallyConvertableNotOverride source) =>
new DateTimeOffset(1991, 8, 6, 0, 0, 0, new TimeSpan(2, 0, 0));
public static implicit operator Uri(DynamicallyConvertableNotOverride source) =>
new Uri("http://example.net/");
}
private class DynamicallyInvokableIntPower : DynamicObject
{
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
if (args.Length == 2)
{
int x;
int y;
try
{
x = Convert.ToInt32(args[0]);
y = Convert.ToInt32(args[1]);
}
catch (Exception)
{
result = null;
return false;
}
result = checked((int)Math.Pow(x, y));
return true;
}
result = null;
return false;
}
}
private class DynamicallyInvokableIntPowerNotOverride : DynamicObject
{
public new bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
if (args.Length == 2)
{
int x;
int y;
try
{
x = Convert.ToInt32(args[0]);
y = Convert.ToInt32(args[1]);
}
catch (Exception)
{
result = null;
return false;
}
result = checked((int)Math.Pow(x, y));
return true;
}
result = null;
return false;
}
}
private class DynamicallyInvokableIntPowerMember : DynamicObject
{
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
if (binder.Name.Equals(
"Power", binder.IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)
&& args.Length == 2)
{
int x;
int y;
try
{
x = Convert.ToInt32(args[0]);
y = Convert.ToInt32(args[1]);
}
catch (Exception)
{
result = null;
return false;
}
result = checked((int)Math.Pow(x, y));
return true;
}
result = null;
return false;
}
public int Modulo(int x, int y) => x % y;
}
private class Swapper : DynamicObject
{
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
result = null;
if (args.Length == 2)
{
object temp = args[0];
args[0] = args[1];
args[1] = temp;
return true;
}
return false;
}
}
private class IndexableObject : DynamicObject
{
Dictionary<int, int> _oneDimension = new Dictionary<int, int>();
Dictionary<Tuple<int, int>, string> _twoDimensions = new Dictionary<Tuple<int, int>, string>();
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
switch (indexes.Length)
{
case 1:
if (indexes[0] is int)
{
int value = _oneDimension[(int)indexes[0]];
result = value;
return true;
}
break;
case 2:
if (indexes[0] is int && indexes[1] is int)
{
string value = _twoDimensions[Tuple.Create((int)indexes[0], (int)indexes[1])];
result = value;
return true;
}
break;
}
result = null;
return false;
}
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
switch (indexes.Length)
{
case 1:
if (indexes[0] is int && value is int)
{
_oneDimension[(int)indexes[0]] = (int)value;
return true;
}
break;
case 2:
if (indexes[0] is int && indexes[1] is int && value is string)
{
_twoDimensions[Tuple.Create((int)indexes[0], (int)indexes[1])] = (string)value;
return true;
}
break;
}
return false;
}
}
private class NegatableNum : DynamicObject
{
public NegatableNum(int value)
{
Value = value;
}
public int Value { get; }
public override bool TryUnaryOperation(UnaryOperationBinder binder, out object result)
{
if (binder.Operation == ExpressionType.Negate)
{
result = new NegatableNum(unchecked(-Value));
return true;
}
result = null;
return false;
}
}
private class AddableNum : DynamicObject
{
public AddableNum(int value)
{
Value = value;
}
public int Value { get; }
public override bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result)
{
if (binder.Operation == ExpressionType.Add)
{
AddableNum addend = arg as AddableNum;
if (addend != null)
{
result = new AddableNum(Value + addend.Value);
return true;
}
}
result = null;
return false;
}
}
private class Accumulator : DynamicObject
{
// Allows addition with itself on the lhs, but not with it on the rhs
public Accumulator(int value)
{
Value = value;
}
public int Value { get; }
public override bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result)
{
if (binder.Operation == ExpressionType.Add)
{
AddableNum addend = arg as AddableNum;
if (addend != null)
{
result = new Accumulator(Value + addend.Value);
return true;
}
}
result = null;
return false;
}
}
private class TraditionalDynamicObject : DynamicObject
{
private static readonly string[] Names =
{
"Foo", "Bar", "Baz", "Quux", "Quuux", "Quuuux", "Quuuuux",
"Quuuuuux"
};
public override IEnumerable<string> GetDynamicMemberNames() => Names;
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
for (int idx = 0; idx != Names.Length; ++idx)
{
if (binder.Name == Names[idx])
{
result = idx;
return true;
}
}
result = null;
return false;
}
}
[Fact]
public void GetSetDefinedField()
{
var test = new TestDynamicFagile();
test.Field = 43;
dynamic d = test;
Assert.Equal(43, d.Field);
d.Field = 93;
Assert.Equal(93, test.Field);
}
[Fact]
public void GetDynamicProperty()
{
dynamic d = new TestDynamicNameReflective();
Assert.Equal("DynProp", d.DynProp);
}
[Fact]
public void FailToGetDynamicProperty()
{
dynamic d = new TestDynamicNameReflective();
Assert.Throws<RuntimeBinderException>(() => d.notToBeFound);
}
[Fact]
public void GetDynamicPropertyWithHidingTryGetMember()
{
dynamic d = new TestDynamicNameReflectiveNotOverride();
Assert.Throws<RuntimeBinderException>(() => d.DynProp);
Assert.Equal(2, d.VirtualReadonlyProperty);
}
[Fact]
public void SetDynamicProperty()
{
dynamic d = new TestDynamicNameReflective();
d.DynProp = nameof(d.DynProp);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => d.DynProp = "I wandered lonely as a cloud.");
}
[Fact]
public void FailToSetDynamicProperty()
{
dynamic d = new TestDynamicNameReflective();
Assert.Throws<RuntimeBinderException>(() => d.notToBeFound = nameof(d.notToBeFound));
}
[Fact]
public void SetDynamicPropertyWithHidingTrySetMember()
{
dynamic d = new TestDynamicNameReflectiveNotOverride();
Assert.Throws<RuntimeBinderException>(() => d.DynProp = nameof(d.DynProp));
}
[Fact]
public void SetPropertyReturnsValueWithoutUsingGetter()
{
dynamic d = new SetOnlyProperties();
object value = new object();
object result = d.SomeProperty = value;
Assert.Same(value, result);
}
[Fact]
public void AttemptWriteReadonlyField()
{
TestDynamic td = new TestDynamic();
dynamic d = td;
Assert.Throws<RuntimeBinderException>(() => d.ReadonlyField = 3);
Assert.Equal(0, td.ReadonlyField); // Confirm exception happened before a write, rather than after.
}
[Fact]
public void ReadWriteHidingField()
{
TestDynamic td = new TestDynamic();
dynamic d = td;
td.HideField = 9;
Assert.Equal(9, d.HideField);
Assert.Equal(9, td.HideField);
Assert.Equal(0, ((TestDynamicBase)td).HideField);
}
[Fact]
public void MetaDynamicKnowsNamesFromDynamic()
{
var trad = new TraditionalDynamicObject();
Assert.Same(trad.GetDynamicMemberNames(), trad.GetMetaObject(Expression.Parameter(typeof(object))).GetDynamicMemberNames());
}
[Fact]
public void ConvertBuiltInImplicit()
{
dynamic d = new DynamicallyConvertable();
Uri u = d;
Assert.Equal(new Uri("http://example.net/"), u);
}
[Fact]
public void ConvertBuiltInExplicit()
{
dynamic d = new DynamicallyConvertable();
DateTimeOffset dto = (DateTimeOffset)d;
Assert.Equal(new DateTimeOffset(1991, 8, 6, 0, 0, 0, new TimeSpan(2, 0, 0)), dto);
}
[Fact]
public void ConvertFailImplicitWhenMatchingExplicit()
{
dynamic d = new DynamicallyConvertable();
DateTimeOffset dto = default(DateTimeOffset);
Assert.Throws<RuntimeBinderException>(() => dto = d);
}
[Fact]
public void ConvertDynamicImplicit()
{
dynamic d = new DynamicallyConvertable();
string name = d;
Assert.Equal(nameof(DynamicallyConvertable), name);
}
[Fact]
public void ConvertDynamicExplicit()
{
dynamic d = new DynamicallyConvertable();
DateTime dt = (DateTime)d;
Assert.Equal(new DateTime(1991, 8, 6), dt);
}
[Fact]
public void ConvertFailImplicitOfferedDynamicallyExplicit()
{
dynamic d = new DynamicallyConvertable();
DateTime dt = default(DateTime);
Assert.Throws<RuntimeBinderException>(() => dt = d);
}
[Fact]
public void ConvertFailNotOfferedConversion()
{
dynamic d = new DynamicallyConvertable();
Expression ex = null;
Assert.Throws<RuntimeBinderException>(() => ex = d);
Assert.Throws<RuntimeBinderException>(() => ex = (Expression)d);
}
[Fact]
public void ConvertHidingTryConvert()
{
dynamic d = new DynamicallyConvertableNotOverride();
Uri u = d;
Assert.Equal(new Uri("http://example.net/"), u);
DateTimeOffset dto = (DateTimeOffset)d;
Assert.Equal(new DateTimeOffset(1991, 8, 6, 0, 0, 0, new TimeSpan(2, 0, 0)), dto);
DateTime dt = default(DateTime);
string s = null;
Assert.Throws<RuntimeBinderException>(() => dt = d);
Assert.Throws<RuntimeBinderException>(() => dto = d);
Assert.Throws<RuntimeBinderException>(() => s = d);
}
[Fact]
public void DynamicInvoke()
{
dynamic d = new DynamicallyInvokableIntPower();
int pow = d(8, 9);
Assert.Equal(134217728, pow);
Assert.Throws<OverflowException>(() => d(int.MaxValue, int.MaxValue));
}
[Fact]
public void DynamicInvokeMismatch()
{
dynamic d = new DynamicallyInvokableIntPower();
Assert.Throws<RuntimeBinderException>(() => d(9));
Assert.Throws<RuntimeBinderException>(() => d());
Assert.Throws<RuntimeBinderException>(() => d(1, 2, 3));
Assert.Throws<RuntimeBinderException>(() => d("eight", "nine"));
}
[Fact]
public void DynamicInvokeNotOverride()
{
dynamic d = new DynamicallyInvokableIntPowerNotOverride();
Assert.Throws<RuntimeBinderException>(() => d(8, 9));
Assert.Throws<RuntimeBinderException>(() => d(int.MaxValue, int.MaxValue));
}
[Fact]
public void DynamicInvokeMember()
{
dynamic d = new DynamicallyInvokableIntPowerMember();
int pow = d.Power(8, 9);
Assert.Equal(134217728, pow);
Assert.Throws<OverflowException>(() => d.Power(int.MaxValue, int.MaxValue));
}
[Fact]
public void DynamicInvokeMemberMismatch()
{
dynamic d = new DynamicallyInvokableIntPowerMember();
Assert.Throws<RuntimeBinderException>(() => d.Power(9));
Assert.Throws<RuntimeBinderException>(() => d.Power());
Assert.Throws<RuntimeBinderException>(() => d.Power(1, 2, 3));
Assert.Throws<RuntimeBinderException>(() => d.Power("eight", "nine"));
Assert.Throws<RuntimeBinderException>(() => d.power(8, 9));
}
[Fact]
public void DynamicInvokeMemberStaticMember()
{
dynamic d = new DynamicallyInvokableIntPowerMember();
int mod = d.Modulo(233, 12);
Assert.Equal(5, mod);
Assert.Throws<RuntimeBinderException>(() => d.Modulo(2));
Assert.Throws<RuntimeBinderException>(() => d.modulo(233, 12));
Assert.Throws<RuntimeBinderException>(() => d.Modulo());
Assert.Throws<RuntimeBinderException>(() => d.Modulo(233, 12, 9));
Assert.Throws<RuntimeBinderException>(() => d.Modulo("two hundred and thirty-three", "twelve"));
}
[Fact]
public void DynamicUnaryOperation()
{
dynamic d = new NegatableNum(23);
dynamic r = -d;
Assert.Equal(-23, r.Value);
d = new NegatableNum(int.MinValue);
r = -d;
Assert.Equal(int.MinValue, r.Value);
}
[Fact]
public void DynamicUnaryOperationNotSupported()
{
dynamic d = new NegatableNum(23);
Assert.Throws<RuntimeBinderException>(() => ~d);
}
[Fact]
public void DynamicUnaryOperationNoOverrides()
{
dynamic d = new TestDynamic();
Assert.Throws<RuntimeBinderException>(() => -d);
}
[Fact]
public void DynamicAddition()
{
dynamic x = new AddableNum(23);
dynamic y = new AddableNum(42);
dynamic r = x + y;
Assert.Equal(23 + 42, r.Value);
}
[Fact]
public void DynamicBinaryUnsupported()
{
dynamic x = new AddableNum(23);
dynamic y = new AddableNum(42);
Assert.Throws<RuntimeBinderException>(() => x * y);
}
[Fact]
public void DynamicBinaryUnidirectional()
{
dynamic x = new Accumulator(23);
dynamic y = new AddableNum(42);
dynamic r = x + y;
Assert.Equal(23 + 42, r.Value);
Assert.Throws<RuntimeBinderException>(() => y + x);
}
[Fact]
public void DynamicBinaryNoOverride()
{
dynamic x = new TestDynamic();
dynamic y = new TestDynamic();
Assert.Throws<RuntimeBinderException>(() => x + y);
}
[Fact]
public void ByRefInvoke()
{
dynamic d = new Swapper();
int x = 23;
int y = 42;
d(ref x, ref y);
Assert.Equal(42, x);
Assert.Equal(23, y);
}
[Fact]
public void ByRefMismatch()
{
dynamic d = new Swapper();
long x = 23;
int y = 42;
d(x, y); // Okay because no write-back.
Assert.Throws<InvalidCastException>(() => d(ref x, ref y));
}
[Fact]
public void IndexGetAndRetrieve()
{
dynamic d = new IndexableObject();
d[23] = 42;
Assert.Equal(42, d[23]);
d[1, 2] = "Hello";
Assert.Equal("Hello", d[1, 2]);
Assert.Throws<KeyNotFoundException>(() => d[1]);
Assert.Throws<KeyNotFoundException>(() => d[2, 3]);
Assert.Throws<RuntimeBinderException>(() => d[2] = "Test");
Assert.Throws<RuntimeBinderException>(() => d[2, 4] = 1);
Assert.Throws<RuntimeBinderException>(() => d["index"]);
Assert.Throws<RuntimeBinderException>(() => d["index"] = 2);
Assert.Throws<RuntimeBinderException>(() =>
{
string val = d[23];
});
Assert.Throws<RuntimeBinderException>(() =>
{
int val = d[1, 2];
});
Assert.Throws<RuntimeBinderException>(() => d[1, 2, 3]);
}
[Fact]
public void IndexingFromStaticMember()
{
dynamic d = new TestDynamic();
d[0] = 1;
Assert.Equal(1, d[0]);
Assert.Throws<RuntimeBinderException>(() => d[0] = "One");
Assert.Throws<RuntimeBinderException>(() =>
{
string val = d[0];
});
Assert.Throws<RuntimeBinderException>(() => d["index"]);
}
}
}
| |
/*
* Copyright 2022 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/routing.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Api {
/// <summary>Holder for reflection information generated from google/api/routing.proto</summary>
public static partial class RoutingReflection {
#region Descriptor
/// <summary>File descriptor for google/api/routing.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static RoutingReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Chhnb29nbGUvYXBpL3JvdXRpbmcucHJvdG8SCmdvb2dsZS5hcGkaIGdvb2ds",
"ZS9wcm90b2J1Zi9kZXNjcmlwdG9yLnByb3RvIkcKC1JvdXRpbmdSdWxlEjgK",
"EnJvdXRpbmdfcGFyYW1ldGVycxgCIAMoCzIcLmdvb2dsZS5hcGkuUm91dGlu",
"Z1BhcmFtZXRlciI4ChBSb3V0aW5nUGFyYW1ldGVyEg0KBWZpZWxkGAEgASgJ",
"EhUKDXBhdGhfdGVtcGxhdGUYAiABKAk6SwoHcm91dGluZxIeLmdvb2dsZS5w",
"cm90b2J1Zi5NZXRob2RPcHRpb25zGLHKvCIgASgLMhcuZ29vZ2xlLmFwaS5S",
"b3V0aW5nUnVsZUJqCg5jb20uZ29vZ2xlLmFwaUIMUm91dGluZ1Byb3RvUAFa",
"QWdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3RvL2dvb2dsZWFwaXMvYXBpL2Fu",
"bm90YXRpb25zO2Fubm90YXRpb25zogIER0FQSWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Protobuf.Reflection.DescriptorReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pb::Extension[] { RoutingExtensions.Routing }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.RoutingRule), global::Google.Api.RoutingRule.Parser, new[]{ "RoutingParameters" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.RoutingParameter), global::Google.Api.RoutingParameter.Parser, new[]{ "Field", "PathTemplate" }, null, null, null, null)
}));
}
#endregion
}
/// <summary>Holder for extension identifiers generated from the top level of google/api/routing.proto</summary>
public static partial class RoutingExtensions {
/// <summary>
/// See RoutingRule.
/// </summary>
public static readonly pb::Extension<global::Google.Protobuf.Reflection.MethodOptions, global::Google.Api.RoutingRule> Routing =
new pb::Extension<global::Google.Protobuf.Reflection.MethodOptions, global::Google.Api.RoutingRule>(72295729, pb::FieldCodec.ForMessage(578365834, global::Google.Api.RoutingRule.Parser));
}
#region Messages
/// <summary>
/// Specifies the routing information that should be sent along with the request
/// in the form of routing header.
/// **NOTE:** All service configuration rules follow the "last one wins" order.
///
/// The examples below will apply to an RPC which has the following request type:
///
/// Message Definition:
///
/// message Request {
/// // The name of the Table
/// // Values can be of the following formats:
/// // - `projects/<project>/tables/<table>`
/// // - `projects/<project>/instances/<instance>/tables/<table>`
/// // - `region/<region>/zones/<zone>/tables/<table>`
/// string table_name = 1;
///
/// // This value specifies routing for replication.
/// // It can be in the following formats:
/// // - `profiles/<profile_id>`
/// // - a legacy `profile_id` that can be any string
/// string app_profile_id = 2;
/// }
///
/// Example message:
///
/// {
/// table_name: projects/proj_foo/instances/instance_bar/table/table_baz,
/// app_profile_id: profiles/prof_qux
/// }
///
/// The routing header consists of one or multiple key-value pairs. Every key
/// and value must be percent-encoded, and joined together in the format of
/// `key1=value1&key2=value2`.
/// In the examples below I am skipping the percent-encoding for readablity.
///
/// Example 1
///
/// Extracting a field from the request to put into the routing header
/// unchanged, with the key equal to the field name.
///
/// annotation:
///
/// option (google.api.routing) = {
/// // Take the `app_profile_id`.
/// routing_parameters {
/// field: "app_profile_id"
/// }
/// };
///
/// result:
///
/// x-goog-request-params: app_profile_id=profiles/prof_qux
///
/// Example 2
///
/// Extracting a field from the request to put into the routing header
/// unchanged, with the key different from the field name.
///
/// annotation:
///
/// option (google.api.routing) = {
/// // Take the `app_profile_id`, but name it `routing_id` in the header.
/// routing_parameters {
/// field: "app_profile_id"
/// path_template: "{routing_id=**}"
/// }
/// };
///
/// result:
///
/// x-goog-request-params: routing_id=profiles/prof_qux
///
/// Example 3
///
/// Extracting a field from the request to put into the routing
/// header, while matching a path template syntax on the field's value.
///
/// NB: it is more useful to send nothing than to send garbage for the purpose
/// of dynamic routing, since garbage pollutes cache. Thus the matching.
///
/// Sub-example 3a
///
/// The field matches the template.
///
/// annotation:
///
/// option (google.api.routing) = {
/// // Take the `table_name`, if it's well-formed (with project-based
/// // syntax).
/// routing_parameters {
/// field: "table_name"
/// path_template: "{table_name=projects/*/instances/*/**}"
/// }
/// };
///
/// result:
///
/// x-goog-request-params:
/// table_name=projects/proj_foo/instances/instance_bar/table/table_baz
///
/// Sub-example 3b
///
/// The field does not match the template.
///
/// annotation:
///
/// option (google.api.routing) = {
/// // Take the `table_name`, if it's well-formed (with region-based
/// // syntax).
/// routing_parameters {
/// field: "table_name"
/// path_template: "{table_name=regions/*/zones/*/**}"
/// }
/// };
///
/// result:
///
/// <no routing header will be sent>
///
/// Sub-example 3c
///
/// Multiple alternative conflictingly named path templates are
/// specified. The one that matches is used to construct the header.
///
/// annotation:
///
/// option (google.api.routing) = {
/// // Take the `table_name`, if it's well-formed, whether
/// // using the region- or projects-based syntax.
///
/// routing_parameters {
/// field: "table_name"
/// path_template: "{table_name=regions/*/zones/*/**}"
/// }
/// routing_parameters {
/// field: "table_name"
/// path_template: "{table_name=projects/*/instances/*/**}"
/// }
/// };
///
/// result:
///
/// x-goog-request-params:
/// table_name=projects/proj_foo/instances/instance_bar/table/table_baz
///
/// Example 4
///
/// Extracting a single routing header key-value pair by matching a
/// template syntax on (a part of) a single request field.
///
/// annotation:
///
/// option (google.api.routing) = {
/// // Take just the project id from the `table_name` field.
/// routing_parameters {
/// field: "table_name"
/// path_template: "{routing_id=projects/*}/**"
/// }
/// };
///
/// result:
///
/// x-goog-request-params: routing_id=projects/proj_foo
///
/// Example 5
///
/// Extracting a single routing header key-value pair by matching
/// several conflictingly named path templates on (parts of) a single request
/// field. The last template to match "wins" the conflict.
///
/// annotation:
///
/// option (google.api.routing) = {
/// // If the `table_name` does not have instances information,
/// // take just the project id for routing.
/// // Otherwise take project + instance.
///
/// routing_parameters {
/// field: "table_name"
/// path_template: "{routing_id=projects/*}/**"
/// }
/// routing_parameters {
/// field: "table_name"
/// path_template: "{routing_id=projects/*/instances/*}/**"
/// }
/// };
///
/// result:
///
/// x-goog-request-params:
/// routing_id=projects/proj_foo/instances/instance_bar
///
/// Example 6
///
/// Extracting multiple routing header key-value pairs by matching
/// several non-conflicting path templates on (parts of) a single request field.
///
/// Sub-example 6a
///
/// Make the templates strict, so that if the `table_name` does not
/// have an instance information, nothing is sent.
///
/// annotation:
///
/// option (google.api.routing) = {
/// // The routing code needs two keys instead of one composite
/// // but works only for the tables with the "project-instance" name
/// // syntax.
///
/// routing_parameters {
/// field: "table_name"
/// path_template: "{project_id=projects/*}/instances/*/**"
/// }
/// routing_parameters {
/// field: "table_name"
/// path_template: "projects/*/{instance_id=instances/*}/**"
/// }
/// };
///
/// result:
///
/// x-goog-request-params:
/// project_id=projects/proj_foo&instance_id=instances/instance_bar
///
/// Sub-example 6b
///
/// Make the templates loose, so that if the `table_name` does not
/// have an instance information, just the project id part is sent.
///
/// annotation:
///
/// option (google.api.routing) = {
/// // The routing code wants two keys instead of one composite
/// // but will work with just the `project_id` for tables without
/// // an instance in the `table_name`.
///
/// routing_parameters {
/// field: "table_name"
/// path_template: "{project_id=projects/*}/**"
/// }
/// routing_parameters {
/// field: "table_name"
/// path_template: "projects/*/{instance_id=instances/*}/**"
/// }
/// };
///
/// result (is the same as 6a for our example message because it has the instance
/// information):
///
/// x-goog-request-params:
/// project_id=projects/proj_foo&instance_id=instances/instance_bar
///
/// Example 7
///
/// Extracting multiple routing header key-value pairs by matching
/// several path templates on multiple request fields.
///
/// NB: note that here there is no way to specify sending nothing if one of the
/// fields does not match its template. E.g. if the `table_name` is in the wrong
/// format, the `project_id` will not be sent, but the `routing_id` will be.
/// The backend routing code has to be aware of that and be prepared to not
/// receive a full complement of keys if it expects multiple.
///
/// annotation:
///
/// option (google.api.routing) = {
/// // The routing needs both `project_id` and `routing_id`
/// // (from the `app_profile_id` field) for routing.
///
/// routing_parameters {
/// field: "table_name"
/// path_template: "{project_id=projects/*}/**"
/// }
/// routing_parameters {
/// field: "app_profile_id"
/// path_template: "{routing_id=**}"
/// }
/// };
///
/// result:
///
/// x-goog-request-params:
/// project_id=projects/proj_foo&routing_id=profiles/prof_qux
///
/// Example 8
///
/// Extracting a single routing header key-value pair by matching
/// several conflictingly named path templates on several request fields. The
/// last template to match "wins" the conflict.
///
/// annotation:
///
/// option (google.api.routing) = {
/// // The `routing_id` can be a project id or a region id depending on
/// // the table name format, but only if the `app_profile_id` is not set.
/// // If `app_profile_id` is set it should be used instead.
///
/// routing_parameters {
/// field: "table_name"
/// path_template: "{routing_id=projects/*}/**"
/// }
/// routing_parameters {
/// field: "table_name"
/// path_template: "{routing_id=regions/*}/**"
/// }
/// routing_parameters {
/// field: "app_profile_id"
/// path_template: "{routing_id=**}"
/// }
/// };
///
/// result:
///
/// x-goog-request-params: routing_id=profiles/prof_qux
///
/// Example 9
///
/// Bringing it all together.
///
/// annotation:
///
/// option (google.api.routing) = {
/// // For routing both `table_location` and a `routing_id` are needed.
/// //
/// // table_location can be either an instance id or a region+zone id.
/// //
/// // For `routing_id`, take the value of `app_profile_id`
/// // - If it's in the format `profiles/<profile_id>`, send
/// // just the `<profile_id>` part.
/// // - If it's any other literal, send it as is.
/// // If the `app_profile_id` is empty, and the `table_name` starts with
/// // the project_id, send that instead.
///
/// routing_parameters {
/// field: "table_name"
/// path_template: "projects/*/{table_location=instances/*}/tables/*"
/// }
/// routing_parameters {
/// field: "table_name"
/// path_template: "{table_location=regions/*/zones/*}/tables/*"
/// }
/// routing_parameters {
/// field: "table_name"
/// path_template: "{routing_id=projects/*}/**"
/// }
/// routing_parameters {
/// field: "app_profile_id"
/// path_template: "{routing_id=**}"
/// }
/// routing_parameters {
/// field: "app_profile_id"
/// path_template: "profiles/{routing_id=*}"
/// }
/// };
///
/// result:
///
/// x-goog-request-params:
/// table_location=instances/instance_bar&routing_id=prof_qux
/// </summary>
public sealed partial class RoutingRule : pb::IMessage<RoutingRule>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<RoutingRule> _parser = new pb::MessageParser<RoutingRule>(() => new RoutingRule());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<RoutingRule> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.RoutingReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public RoutingRule() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public RoutingRule(RoutingRule other) : this() {
routingParameters_ = other.routingParameters_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public RoutingRule Clone() {
return new RoutingRule(this);
}
/// <summary>Field number for the "routing_parameters" field.</summary>
public const int RoutingParametersFieldNumber = 2;
private static readonly pb::FieldCodec<global::Google.Api.RoutingParameter> _repeated_routingParameters_codec
= pb::FieldCodec.ForMessage(18, global::Google.Api.RoutingParameter.Parser);
private readonly pbc::RepeatedField<global::Google.Api.RoutingParameter> routingParameters_ = new pbc::RepeatedField<global::Google.Api.RoutingParameter>();
/// <summary>
/// A collection of Routing Parameter specifications.
/// **NOTE:** If multiple Routing Parameters describe the same key
/// (via the `path_template` field or via the `field` field when
/// `path_template` is not provided), "last one wins" rule
/// determines which Parameter gets used.
/// See the examples for more details.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::RepeatedField<global::Google.Api.RoutingParameter> RoutingParameters {
get { return routingParameters_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as RoutingRule);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(RoutingRule other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!routingParameters_.Equals(other.routingParameters_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
hash ^= routingParameters_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
routingParameters_.WriteTo(output, _repeated_routingParameters_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
routingParameters_.WriteTo(ref output, _repeated_routingParameters_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
size += routingParameters_.CalculateSize(_repeated_routingParameters_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(RoutingRule other) {
if (other == null) {
return;
}
routingParameters_.Add(other.routingParameters_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 18: {
routingParameters_.AddEntriesFrom(input, _repeated_routingParameters_codec);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 18: {
routingParameters_.AddEntriesFrom(ref input, _repeated_routingParameters_codec);
break;
}
}
}
}
#endif
}
/// <summary>
/// A projection from an input message to the GRPC or REST header.
/// </summary>
public sealed partial class RoutingParameter : pb::IMessage<RoutingParameter>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<RoutingParameter> _parser = new pb::MessageParser<RoutingParameter>(() => new RoutingParameter());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<RoutingParameter> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.RoutingReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public RoutingParameter() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public RoutingParameter(RoutingParameter other) : this() {
field_ = other.field_;
pathTemplate_ = other.pathTemplate_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public RoutingParameter Clone() {
return new RoutingParameter(this);
}
/// <summary>Field number for the "field" field.</summary>
public const int FieldFieldNumber = 1;
private string field_ = "";
/// <summary>
/// A request field to extract the header key-value pair from.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Field {
get { return field_; }
set {
field_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "path_template" field.</summary>
public const int PathTemplateFieldNumber = 2;
private string pathTemplate_ = "";
/// <summary>
/// A pattern matching the key-value field. Optional.
/// If not specified, the whole field specified in the `field` field will be
/// taken as value, and its name used as key. If specified, it MUST contain
/// exactly one named segment (along with any number of unnamed segments) The
/// pattern will be matched over the field specified in the `field` field, then
/// if the match is successful:
/// - the name of the single named segment will be used as a header name,
/// - the match value of the segment will be used as a header value;
/// if the match is NOT successful, nothing will be sent.
///
/// Example:
///
/// -- This is a field in the request message
/// | that the header value will be extracted from.
/// |
/// | -- This is the key name in the
/// | | routing header.
/// V |
/// field: "table_name" v
/// path_template: "projects/*/{table_location=instances/*}/tables/*"
/// ^ ^
/// | |
/// In the {} brackets is the pattern that -- |
/// specifies what to extract from the |
/// field as a value to be sent. |
/// |
/// The string in the field must match the whole pattern --
/// before brackets, inside brackets, after brackets.
///
/// When looking at this specific example, we can see that:
/// - A key-value pair with the key `table_location`
/// and the value matching `instances/*` should be added
/// to the x-goog-request-params routing header.
/// - The value is extracted from the request message's `table_name` field
/// if it matches the full pattern specified:
/// `projects/*/instances/*/tables/*`.
///
/// **NB:** If the `path_template` field is not provided, the key name is
/// equal to the field name, and the whole field should be sent as a value.
/// This makes the pattern for the field and the value functionally equivalent
/// to `**`, and the configuration
///
/// {
/// field: "table_name"
/// }
///
/// is a functionally equivalent shorthand to:
///
/// {
/// field: "table_name"
/// path_template: "{table_name=**}"
/// }
///
/// See Example 1 for more details.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string PathTemplate {
get { return pathTemplate_; }
set {
pathTemplate_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as RoutingParameter);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(RoutingParameter other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Field != other.Field) return false;
if (PathTemplate != other.PathTemplate) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Field.Length != 0) hash ^= Field.GetHashCode();
if (PathTemplate.Length != 0) hash ^= PathTemplate.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Field.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Field);
}
if (PathTemplate.Length != 0) {
output.WriteRawTag(18);
output.WriteString(PathTemplate);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Field.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Field);
}
if (PathTemplate.Length != 0) {
output.WriteRawTag(18);
output.WriteString(PathTemplate);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Field.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Field);
}
if (PathTemplate.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(PathTemplate);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(RoutingParameter other) {
if (other == null) {
return;
}
if (other.Field.Length != 0) {
Field = other.Field;
}
if (other.PathTemplate.Length != 0) {
PathTemplate = other.PathTemplate;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Field = input.ReadString();
break;
}
case 18: {
PathTemplate = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Field = input.ReadString();
break;
}
case 18: {
PathTemplate = input.ReadString();
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
| |
// 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 Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Metadata;
using System.Collections.ObjectModel;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
/// <summary>
/// Debugger type proxy expansion.
/// </summary>
/// <remarks>
/// May include <see cref="System.Collections.IEnumerable"/> and
/// <see cref="System.Collections.Generic.IEnumerable{T}"/> as special cases.
/// (The proxy is not declared by an attribute, but is known to debugger.)
/// </remarks>
internal sealed class DebuggerTypeProxyExpansion : Expansion
{
internal static Expansion CreateExpansion(
ResultProvider resultProvider,
DkmInspectionContext inspectionContext,
string name,
Type typeDeclaringMemberOpt,
Type declaredType,
DkmClrValue value,
bool childShouldParenthesize,
string fullName,
string childFullNamePrefix,
ReadOnlyCollection<string> formatSpecifiers,
DkmEvaluationResultFlags flags,
string editableValue)
{
Debug.Assert((inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoExpansion) == 0);
// Note: The native EE uses the proxy type, even for
// null instances, so statics on the proxy type are
// displayed. That case is not supported currently.
if (!value.IsNull)
{
var proxyType = value.Type.GetProxyType();
if (proxyType != null)
{
if ((inspectionContext.EvaluationFlags & DkmEvaluationFlags.ShowValueRaw) != 0)
{
var rawView = CreateRawView(resultProvider, inspectionContext, declaredType, value);
Debug.Assert(rawView != null);
return rawView;
}
DkmClrValue proxyValue;
try
{
proxyValue = value.InstantiateProxyType(proxyType);
}
catch
{
proxyValue = null;
}
if (proxyValue != null)
{
return new DebuggerTypeProxyExpansion(
proxyValue,
name,
typeDeclaringMemberOpt,
declaredType,
value,
childShouldParenthesize,
fullName,
childFullNamePrefix,
formatSpecifiers,
flags,
editableValue,
resultProvider.Formatter);
}
}
}
return null;
}
private readonly EvalResultDataItem proxyItem;
private readonly string name;
private readonly Type typeDeclaringMemberOpt;
private readonly Type _declaredType;
private readonly DkmClrValue value;
private readonly bool childShouldParenthesize;
private readonly string fullName;
private readonly string childFullNamePrefix;
private readonly ReadOnlyCollection<string> formatSpecifiers;
private readonly DkmEvaluationResultFlags flags;
private readonly string editableValue;
private DebuggerTypeProxyExpansion(
DkmClrValue proxyValue,
string name,
Type typeDeclaringMemberOpt,
Type declaredType,
DkmClrValue value,
bool childShouldParenthesize,
string fullName,
string childFullNamePrefix,
ReadOnlyCollection<string> formatSpecifiers,
DkmEvaluationResultFlags flags,
string editableValue,
Formatter formatter)
{
Debug.Assert(proxyValue != null);
var proxyType = proxyValue.Type.GetLmrType();
var proxyMembers = MemberExpansion.CreateExpansion(
proxyType,
proxyValue,
ExpansionFlags.IncludeBaseMembers,
TypeHelpers.IsPublic,
formatter);
if (proxyMembers != null)
{
var proxyMemberFullNamePrefix = (childFullNamePrefix == null) ?
null :
formatter.GetObjectCreationExpression(formatter.GetTypeName(proxyType, escapeKeywordIdentifiers: true), childFullNamePrefix);
this.proxyItem = new EvalResultDataItem(
name: null,
typeDeclaringMember: null,
declaredType: proxyType,
value: proxyValue,
expansion: proxyMembers,
childShouldParenthesize: false,
fullName: null,
childFullNamePrefixOpt: proxyMemberFullNamePrefix,
formatSpecifiers: Formatter.NoFormatSpecifiers,
category: default(DkmEvaluationResultCategory),
flags: default(DkmEvaluationResultFlags),
editableValue: null);
}
this.name = name;
this.typeDeclaringMemberOpt = typeDeclaringMemberOpt;
_declaredType = declaredType;
this.value = value;
this.childShouldParenthesize = childShouldParenthesize;
this.fullName = fullName;
this.childFullNamePrefix = childFullNamePrefix;
this.formatSpecifiers = formatSpecifiers;
this.flags = flags;
this.editableValue = editableValue;
}
internal override void GetRows(
ResultProvider resultProvider,
ArrayBuilder<DkmEvaluationResult> rows,
DkmInspectionContext inspectionContext,
EvalResultDataItem parent,
DkmClrValue value,
int startIndex,
int count,
bool visitAll,
ref int index)
{
if (this.proxyItem != null)
{
this.proxyItem.Expansion.GetRows(resultProvider, rows, inspectionContext, this.proxyItem, this.proxyItem.Value, startIndex, count, visitAll, ref index);
}
if (InRange(startIndex, count, index))
{
rows.Add(this.CreateRawViewRow(resultProvider, inspectionContext));
}
index++;
}
private DkmEvaluationResult CreateRawViewRow(
ResultProvider resultProvider,
DkmInspectionContext inspectionContext)
{
var dataItem = new EvalResultDataItem(
this.name,
this.typeDeclaringMemberOpt,
_declaredType,
this.value,
CreateRawView(resultProvider, inspectionContext, _declaredType, this.value),
this.childShouldParenthesize,
this.fullName,
this.childFullNamePrefix,
Formatter.AddFormatSpecifier(this.formatSpecifiers, "raw"),
DkmEvaluationResultCategory.Data,
this.flags | DkmEvaluationResultFlags.ReadOnly,
this.editableValue);
return ResultProvider.CreateEvaluationResult(
value,
Resources.RawView,
typeName: "",
display: null,
dataItem: dataItem);
}
private static Expansion CreateRawView(
ResultProvider resultProvider,
DkmInspectionContext inspectionContext,
Type declaredType,
DkmClrValue value)
{
return resultProvider.GetTypeExpansion(inspectionContext, declaredType, value, ExpansionFlags.IncludeBaseMembers);
}
}
}
| |
//-----------------------------------------------------------------------
// This file is part of the Microsoft Robotics Studio Code Samples.
//
// Copyright (C) Microsoft Corporation. All rights reserved.
//
// $File: DriveControl.cs $ $Revision: 15 $
//
// Modified by Ben Axelrod 8/25/07
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Ccr.Core;
using game = Microsoft.Robotics.Services.GameController.Proxy;
using drive = Microsoft.Robotics.Services.Drive.Proxy;
using arm = Microsoft.Robotics.Services.ArticulatedArm.Proxy;
using sicklrf = Microsoft.Robotics.Services.Sensors.SickLRF.Proxy;
using cs = Microsoft.Dss.Services.Constructor;
using Microsoft.Dss.ServiceModel.Dssp;
using System.Drawing.Drawing2D;
using System.IO;
using Microsoft.Dss.Core;
using Microsoft.Robotics.Simulation.Physics.Proxy;
using Microsoft.Robotics.PhysicalModel.Proxy;
namespace Microsoft.Robotics.Services.SimpleDashboard
{
partial class DriveControl : Form
{
DriveControlEvents _eventsPort;
/// <summary>
/// Width of robot. change this value to change the red indicators in the laser views
/// </summary>
private static readonly int robotWidth = 400; //mm
/// <summary>
/// maximum distance the laser can see
/// </summary>
private static readonly int maxDist = 8000; //mm
bool driveCheck = true;
bool stopCheck = false;
public DriveControl(DriveControlEvents EventsPort)
{
_eventsPort = EventsPort;
InitializeComponent();
txtPort.ValidatingType = typeof(ushort);
}
private void cbJoystick_SelectedIndexChanged(object sender, EventArgs e)
{
IEnumerable<game.Controller> list = cbJoystick.Tag as IEnumerable<game.Controller>;
if (list != null)
{
if (cbJoystick.SelectedIndex >= 0)
{
int index = 0;
foreach (game.Controller controller in list)
{
if (index == cbJoystick.SelectedIndex)
{
OnChangeJoystick change = new OnChangeJoystick(this);
change.Joystick = controller;
_eventsPort.Post(change);
return;
}
index++;
}
}
}
}
private void DriveControl_Load(object sender, EventArgs e)
{
_eventsPort.Post(new OnLoad(this));
}
private void DriveControl_FormClosed(object sender, FormClosedEventArgs e)
{
_eventsPort.Post(new OnClosed(this));
}
public void ReplaceJoystickList(IEnumerable<game.Controller> controllers)
{
cbJoystick.BeginUpdate();
try
{
cbJoystick.Items.Clear();
foreach (game.Controller controller in controllers)
{
int index = cbJoystick.Items.Add(controller.InstanceName);
if (controller.Current == true)
{
cbJoystick.SelectedIndex = index;
}
}
cbJoystick.Tag = controllers;
}
finally
{
cbJoystick.EndUpdate();
}
}
public void UpdateJoystickAxes(game.Axes axes)
{
int x = axes.X;
int y = -axes.Y;
lblX.Text = x.ToString();
lblY.Text = y.ToString();
lblZ.Text = axes.Z.ToString();
DrawJoystick(x, y);
//if (!chkStop.Checked)
//{
// int left;
// int right;
// if (chkDrive.Checked == true)
// {
// if (y > -100)
// {
// left = y + axes.X / 4;
// right = y - axes.X / 4;
// }
// else
// {
// left = y - axes.X / 4;
// right = y + axes.X / 4;
// }
// }
// else
// {
// left = right = 0;
// }
// _eventsPort.Post(new OnMove(this, left, right));
//}
if (!stopCheck)
{
double left;
double right;
if (driveCheck == true)
{
//this is the raw length of the vector
double magnitude = Math.Sqrt(y * y + x * x);
//angle of the vector
double theta = Math.Atan2(y, x);
//this is the maximum magnitude for a given angle
double maxMag;
if (Math.Abs(x) > Math.Abs(y))
maxMag = Math.Abs(1000 / Math.Cos(theta));
else
maxMag = Math.Abs(1000 / Math.Sin(theta));
//a scaled down magnitude according to above
double scaledMag = magnitude * 1000 / maxMag;
//decompose the vector into motor components
left = scaledMag * Math.Sin(theta) + scaledMag * Math.Cos(theta) / 3;
right = scaledMag * Math.Sin(theta) - scaledMag * Math.Cos(theta) / 3;
}
else
{
left = right = 0;
}
//cap at 1000
left = Math.Min(left, 1000);
right = Math.Min(right, 1000);
left = Math.Max(left, -1000);
right = Math.Max(right, -1000);
//throttle control
left *= (double)throttle.Value / 100.0;
right *= (double)throttle.Value / 100.0;
_eventsPort.Post(new OnMove(this, (int)Math.Round(left), (int)Math.Round(right)));
}
}
public void UpdateJoystickButtons(game.Buttons buttons)
{
if (buttons.Pressed != null && buttons.Pressed.Count > 0)
{
string[] buttonString = buttons.Pressed.ConvertAll<string>(
delegate(bool button)
{
return button ? "X" : "O";
}
).ToArray();
lblButtons.Text = string.Join(" ", buttonString);
if (stopCheck && buttons.Pressed.Count > 2)
{
if (buttons.Pressed[2] == true)
{
stopCheck = false;
}
}
else if (buttons.Pressed[1] == true && buttons.Pressed.Count > 1)
{
stopCheck = true;
}
if (buttons.Pressed[0] != driveCheck)
{
driveCheck = buttons.Pressed[0];
}
}
}
private void DrawJoystick(int x, int y)
{
Bitmap bmp = new Bitmap(picJoystick.Width, picJoystick.Height);
Graphics g = Graphics.FromImage(bmp);
int width = bmp.Width - 1;
int height = bmp.Height - 1;
g.Clear(Color.Transparent);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, width, height);
PathGradientBrush pathBrush = new PathGradientBrush(path);
pathBrush.CenterPoint = new PointF(width / 3f, height / 3f);
pathBrush.CenterColor = Color.White;
pathBrush.SurroundColors = new Color[] { Color.LightGray };
g.FillPath(pathBrush, path);
g.DrawPath(Pens.Black, path);
int partial = y * height / 2200;
if (partial > 0)
{
g.DrawArc(Pens.Black,
0,
height / 2 - partial,
width,
2 * partial,
180,
180);
}
else if (partial == 0)
{
g.DrawLine(Pens.Black, 0, height / 2, width, height / 2);
}
else
{
g.DrawArc(Pens.Black,
0,
height / 2 + partial,
width,
-2 * partial,
0,
180);
}
partial = x * width / 2200;
if (partial > 0)
{
g.DrawArc(Pens.Black,
width / 2 - partial,
0,
2 * partial,
height,
270,
180);
}
else if (partial == 0)
{
g.DrawLine(Pens.Black, width / 2, 0, width / 2, height);
}
else
{
g.DrawArc(Pens.Black,
width / 2 + partial,
0,
-2 * partial,
height,
90,
180);
}
picJoystick.Image = bmp;
}
private void btnConnect_Click(object sender, EventArgs e)
{
string machine = txtMachine.Text;
if (machine.Length == 0)
{
txtMachine.Focus();
return;
}
object obj = txtPort.ValidateText();
if (obj == null)
{
obj = (ushort)0;
}
ushort port = (ushort)obj;
UriBuilder builder = new UriBuilder(Schemes.DsspTcp, machine, port, ServicePaths.InstanceDirectory);
_eventsPort.Post(new OnConnect(this, builder.ToString()));
}
public void ReplaceDirectoryList(ServiceInfoType[] list)
{
listDirectory.BeginUpdate();
try
{
listDirectory.Tag = list;
listDirectory.Items.Clear();
if (list.Length > 0)
{
UriBuilder node = new UriBuilder(list[0].Service);
node.Path = null;
lblNode.Text = node.Host + ":" + node.Port;
txtMachine.Text = node.Host;
txtPort.Text = node.Port.ToString();
linkDirectory.Enabled = true;
}
else
{
lblNode.Text = string.Empty;
linkDirectory.Enabled = false;
}
foreach (ServiceInfoType info in list)
{
if (info.Contract == sicklrf.Contract.Identifier ||
info.Contract == drive.Contract.Identifier ||
info.Contract == arm.Contract.Identifier)
{
string prefix = string.Empty;
foreach(PartnerType partner in info.PartnerList)
{
if(partner.Name.ToString().EndsWith(":Entity"))
{
prefix = partner.Service;
int last = prefix.LastIndexOf('/');
prefix = "(" + prefix.Substring(last + 1) + ")";
break;
}
}
Uri serviceUri = new Uri(info.Service);
listDirectory.Items.Add(prefix + " " + serviceUri.AbsolutePath);
}
}
if (ServiceByContract(sicklrf.Contract.Identifier) == null)
{
btnStartLRF.Enabled = true;
btnConnectLRF.Enabled = false;
}
else
{
btnStartLRF.Enabled = false;
btnConnectLRF.Enabled = true;
}
btnConnect_ArticulatedArm.Enabled = ServiceByContract(arm.Contract.Identifier) != null;
btnJointParamsApply.Enabled = btnConnect_ArticulatedArm.Enabled;
}
finally
{
listDirectory.EndUpdate();
}
}
private void linkDirectory_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (listDirectory.Tag is ServiceInfoType[])
{
ServiceInfoType[] list = (ServiceInfoType[])listDirectory.Tag;
if (list.Length > 0)
{
UriBuilder node;
if (list[0].AliasList != null &&
list[0].AliasList.Count > 0)
{
node = new UriBuilder(list[0].AliasList[0]);
}
else
{
node = new UriBuilder(list[0].Service);
}
node.Path = "directory";
System.Diagnostics.Process.Start(node.ToString());
}
}
}
string ServiceByContract(string contract)
{
if (listDirectory.Tag is ServiceInfoType[])
{
ServiceInfoType[] list = (ServiceInfoType[])listDirectory.Tag;
foreach (ServiceInfoType service in list)
{
if (service.Contract == contract)
{
return service.Service;
}
}
}
return null;
}
private void btnStartLRF_Click(object sender, EventArgs e)
{
OnStartService start = new OnStartService(this, sicklrf.Contract.Identifier);
start.Constructor = ServiceByContract(cs.Contract.Identifier);
if (start.Constructor != null)
{
_eventsPort.Post(start);
}
}
private void btnConnectLRF_Click(object sender, EventArgs e)
{
string lrf = ServiceByContract(sicklrf.Contract.Identifier);
if (lrf != null)
{
_eventsPort.Post(new OnConnectSickLRF(this, lrf));
}
}
public void StartedSickLRF()
{
btnConnect_Click(this, EventArgs.Empty);
}
//private void chkDrive_CheckedChanged(object sender, EventArgs e)
//{
//}
//private void chkStop_CheckedChanged(object sender, EventArgs e)
//{
// if (chkStop.Checked)
// {
// _eventsPort.Post(new OnEStop(this));
// }
//}
DateTime _lastLaser = DateTime.Now;
public void ReplaceLaserData(sicklrf.State stateType)
{
if (stateType.TimeStamp < _lastLaser)
{
return;
}
_lastLaser = stateType.TimeStamp;
TimeSpan delay = DateTime.Now - stateType.TimeStamp;
lblDelay.Text = delay.ToString();
createCylinder(stateType);
createTop(stateType);
if (btnConnectLRF.Enabled)
{
btnConnectLRF.Enabled = false;
}
if (!btnDisconnect.Enabled)
{
btnDisconnect.Enabled = true;
}
}
private void createCylinder(sicklrf.State stateType)
{
Bitmap bmp = new Bitmap(stateType.DistanceMeasurements.Length, 100);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.LightGray);
int half = bmp.Height / 2;
for (int x = 0; x < stateType.DistanceMeasurements.Length; x++)
{
int range = stateType.DistanceMeasurements[x];
//for red marking
double angle = x * Math.PI * stateType.AngularRange / stateType.DistanceMeasurements.Length / 180; //radians
double obsThresh = Math.Abs(robotWidth / (2 * Math.Cos(angle)));
if (range > 0 && range < maxDist)
{
int h = (int)Math.Round(bmp.Height * 500.0 / range);
if (h < 0)
h = 0;
Color col;
if (range < obsThresh)
col = LinearColor(Color.DarkRed, Color.LightGray, 0, maxDist, range);
else
col = LinearColor(Color.DarkBlue, Color.LightGray, 0, maxDist, range);
g.DrawLine(new Pen(col), bmp.Width - x, half - h, bmp.Width - x, half + h);
}
int hlim = (int)Math.Round(bmp.Height * 500.0 / obsThresh);
if (hlim < 0)
hlim = 0;
if (hlim < half)
bmp.SetPixel(bmp.Width - x, half + hlim, Color.Green);
}
picLRF.Image = bmp;
}
private void createTop(sicklrf.State stateType)
{
int height = 200;
int width = 400;
Bitmap bmp = new Bitmap(width, height);
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.LightGray);
double angularOffset = -90 + stateType.AngularRange / 2.0;
double piBy180 = Math.PI / 180.0;
double halfAngle = stateType.AngularRange / 360.0 / 2.0;
double scale = (double)height / (double)maxDist;
GraphicsPath path = new GraphicsPath();
for (int pass = 0; pass != 2; pass++)
{
for (int i = 0; i < stateType.DistanceMeasurements.Length; i++)
{
int range = stateType.DistanceMeasurements[i];
if (range <= 0)
range = maxDist;
double angle = i * (stateType.AngularRange / 360.0) - angularOffset;
double lowAngle = (angle - halfAngle) * piBy180;
double highAngle = (angle + halfAngle) * piBy180;
double drange = range * scale;
float lx = (float)(height + drange * Math.Cos(lowAngle));
float ly = (float)(height - drange * Math.Sin(lowAngle));
float hx = (float)(height + drange * Math.Cos(highAngle));
float hy = (float)(height - drange * Math.Sin(highAngle));
if (pass == 0)
{
if (i == 0)
{
path.AddLine(height, height, lx, ly);
}
path.AddLine(lx, ly, hx, hy);
}
else
{
if (range < maxDist)
{
double myangle = i * Math.PI * stateType.AngularRange / stateType.DistanceMeasurements.Length / 180; //radians
double obsThresh = Math.Abs(robotWidth / (2 * Math.Cos(myangle)));
if (range < obsThresh)
g.DrawLine(Pens.Red, lx, ly, hx, hy);
else
g.DrawLine(Pens.DarkBlue, lx, ly, hx, hy);
}
}
}
if (pass == 0)
{
g.FillPath(Brushes.White, path);
}
}
float botWidth = (float)((robotWidth / 2.0) * scale);
g.DrawLine(Pens.Red, height, height - botWidth, height, height);
g.DrawLine(Pens.Red, height - 3, height - botWidth, height + 3, height - botWidth);
g.DrawLine(Pens.Red, height - botWidth, height - 3, height - botWidth, height);
g.DrawLine(Pens.Red, height + botWidth, height - 3, height + botWidth, height);
g.DrawLine(Pens.Red, height - botWidth, height - 1, height + botWidth, height - 1);
g.DrawString(
stateType.TimeStamp.ToString(),
new Font(FontFamily.GenericSansSerif, 10, GraphicsUnit.Pixel),
Brushes.Gray, 0, 0
);
picLRFtop.Image = bmp;
}
private Color LinearColor(Color nearColor, Color farColor, int nearLimit, int farLimit, int value)
{
if (value <= nearLimit)
{
return nearColor;
}
else if (value >= farLimit)
{
return farColor;
}
int span = farLimit - nearLimit;
int pos = value - nearLimit;
int r = (nearColor.R * (span - pos) + farColor.R * pos) / span;
int g = (nearColor.G * (span - pos) + farColor.G * pos) / span;
int b = (nearColor.B * (span - pos) + farColor.B * pos) / span;
return Color.FromArgb(r, g, b);
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
_eventsPort.Post(new OnDisconnectSickLRF(this));
btnConnectLRF.Enabled = true;
btnDisconnect.Enabled = false;
}
DateTime _lastMotor = DateTime.Now;
public void UpdateMotorData(drive.DriveDifferentialTwoWheelState data)
{
if (data.TimeStamp > _lastMotor)
{
_lastMotor = data.TimeStamp;
TimeSpan lag = DateTime.Now - data.TimeStamp;
lblMotor.Text = data.IsEnabled ? "On" : "Off";
lblLag.Text = string.Format("{0}.{1:D000}",
lag.TotalSeconds, lag.Milliseconds);
}
}
private void chkLog_CheckedChanged(object sender, EventArgs e)
{
txtLogFile.Enabled = !chkLog.Checked;
btnBrowse.Enabled = !chkLog.Checked;
_eventsPort.Post(new OnLogSetting(this, chkLog.Checked, txtLogFile.Text));
}
private void btnBrowse_Click(object sender, EventArgs e)
{
saveFileDialog.InitialDirectory = LayoutPaths.RootDir + LayoutPaths.StoreDir;
saveFileDialog.FileName = txtLogFile.Text;
if (DialogResult.OK == saveFileDialog.ShowDialog(this))
{
txtLogFile.Text = saveFileDialog.FileName;
}
}
public void ErrorLogging(Exception ex)
{
MessageBox.Show(this,
"Exception thrown by logging:\n" + ex.Message,
Text,
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation
);
chkLog.Checked = false;
txtLogFile.Enabled = true;
btnBrowse.Enabled = true;
}
private void picJoystick_MouseLeave(object sender, EventArgs e)
{
UpdateJoystickButtons(new game.Buttons());
UpdateJoystickAxes(new game.Axes());
}
private void picJoystick_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int x, y;
x = Math.Min(picJoystick.Width, Math.Max(e.X, 0));
y = Math.Min(picJoystick.Height, Math.Max(e.Y, 0));
x = x * 2000 / picJoystick.Width - 1000;
y = y * 2000 / picJoystick.Height - 1000;
game.Axes axes = new game.Axes();
axes.X = x;
axes.Y = y;
UpdateJoystickAxes(axes);
}
}
private void picJoystick_MouseUp(object sender, MouseEventArgs e)
{
picJoystick_MouseLeave(sender, e);
}
public void PerformedRoundTrip(bool roundTrip)
{
string title = roundTrip ? "Remote Drive Control" : "Remote Drive Control - Connection Down";
if (Text != title)
{
Text = title;
}
}
private void listDirectory_DoubleClick(object sender, EventArgs e)
{
ServiceInfoType[] list = listDirectory.Tag as ServiceInfoType[];
if (list != null &&
listDirectory.SelectedIndex >= 0 &&
listDirectory.SelectedIndex < list.Length)
{
// get the service path from the selected item
string[] tokens = ((string)listDirectory.SelectedItem).Split(new char[] { ' ' });
if (tokens.Length == 0)
return;
ServiceInfoType info = FindServiceInfoFromServicePath(tokens[tokens.Length - 1]);
if (info == null)
return;
if (info.Contract == drive.Contract.Identifier)
{
_eventsPort.Post(new OnConnectMotor(this, info.Service));
}
else if (info.Contract == sicklrf.Contract.Identifier)
{
_eventsPort.Post(new OnConnectSickLRF(this, info.Service));
}
else if (info.Contract == arm.Contract.Identifier)
{
_eventsPort.Post(new OnConnectArticulatedArm(this, info.Service));
}
}
}
ServiceInfoType FindServiceInfoFromServicePath(string path)
{
ServiceInfoType[] list = (ServiceInfoType[])listDirectory.Tag;
UriBuilder builder = new UriBuilder(list[0].Service);
builder.Path = path;
string uri = builder.ToString();
return FindServiceInfoFromServiceUri(uri);
}
ServiceInfoType FindServiceInfoFromServiceUri(string uri)
{
ServiceInfoType[] list = (ServiceInfoType[])listDirectory.Tag;
foreach (ServiceInfoType si in list)
{
if (si.Service == uri)
return si;
}
return null;
}
private void saveFileDialog_FileOk(object sender, CancelEventArgs e)
{
string path = Path.GetFullPath(saveFileDialog.FileName);
if (!path.StartsWith(saveFileDialog.InitialDirectory))
{
MessageBox.Show("Log file must be in a subdirectory of the store", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
e.Cancel = true;
}
}
private void btnJointParamsApply_Click(object sender, EventArgs e)
{
try
{
short angle = short.Parse(textBoxJointAngle.Text);
OnApplyJointParameters j = new OnApplyJointParameters(this,
angle,
lblActiveJointValue.Text);
_eventsPort.Post(j);
}
catch
{
MessageBox.Show("Invalid angle", Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void btnConnect_ArticulatedArm_Click(object sender, EventArgs e)
{
string armService = ServiceByContract(arm.Contract.Identifier);
if (armService != null)
{
_eventsPort.Post(new OnConnectArticulatedArm(this, armService));
}
}
public void ReplaceArticulatedArmJointList(arm.ArticulatedArmState state)
{
btnConnect_ArticulatedArm.Enabled = false;
btnJointParamsApply.Enabled = true;
listArticulatedArmJoints.BeginUpdate();
try
{
listArticulatedArmJoints.Tag = state;
listArticulatedArmJoints.Items.Clear();
if (state.Joints.Count > 0)
{
UriBuilder node = new UriBuilder(state.Joints[0].State.Name);
node.Path = null;
lblActiveJointValue.Text = state.Joints[0].State.Name;
foreach (Joint j in state.Joints)
{
listArticulatedArmJoints.Items.Add(j.State.Name);
}
}
else
{
lblActiveJointValue.Text = string.Empty;
}
}
finally
{
listArticulatedArmJoints.EndUpdate();
}
}
private void listArticulatedArmJointList_DoubleClick(object sender, EventArgs e)
{
arm.ArticulatedArmState state = listArticulatedArmJoints.Tag as arm.ArticulatedArmState;
if (state != null &&
listArticulatedArmJoints.SelectedIndex >= 0 &&
listArticulatedArmJoints.SelectedIndex < state.Joints.Count)
{
lblActiveJointValue.Text = (string)listArticulatedArmJoints.SelectedItem;
}
}
private void throttle_Scroll(object sender, EventArgs e)
{
throttleLbl.Text = throttle.Value.ToString() + " %";
}
bool upKey = false;
bool downKey = false;
bool leftKey = false;
bool rightKey = false;
/// <summary>
/// arrow key control.
/// note that when user holds down a key, this event gets called many times
/// </summary>
void listDirectory_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
//Console.WriteLine(e.KeyValue + " down");
switch (e.KeyValue)
{
case 37: // left key
if (leftKey)
return;
leftKey = true;
break;
case 38: // up key
if (upKey)
return;
upKey = true;
break;
case 39: // right key
if (rightKey)
return;
rightKey = true;
break;
case 40: // down key
if (downKey)
return;
downKey = true;
break;
}
SendProperDriveRequest();
}
/// <summary>
/// arrow key control.
/// gets called when user lifts key
/// </summary>
void listDirectory_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
{
//Console.WriteLine(e.KeyValue + " up");
switch (e.KeyValue)
{
case 37: // left key
leftKey = false;
break;
case 38: // up key
upKey = false;
break;
case 39: // right key
rightKey = false;
break;
case 40: // down key
downKey = false;
break;
}
SendProperDriveRequest();
}
/// <summary>
/// parse the 4 arrow keys into motor movements and send to service.
/// </summary>
void SendProperDriveRequest()
{
double FwdBackPwr = 1000.0 * ((double)throttle.Value / 100.0);
double LeftRightPwr = 200.0 * ((double)throttle.Value / 100.0);
double LeftWheel = 0.0;
double RightWheel = 0.0;
if (upKey)
{
LeftWheel += FwdBackPwr;
RightWheel += FwdBackPwr;
}
if (downKey)
{
LeftWheel -= FwdBackPwr;
RightWheel -= FwdBackPwr;
}
if (leftKey)
{
LeftWheel -= LeftRightPwr;
RightWheel += LeftRightPwr;
}
if (rightKey)
{
LeftWheel += LeftRightPwr;
RightWheel -= LeftRightPwr;
}
//Console.WriteLine("power = " + (int)Math.Round(LeftWheel) + " " + (int)Math.Round(RightWheel));
_eventsPort.Post(new OnMove(this, (int)Math.Round(LeftWheel), (int)Math.Round(RightWheel)));
}
}
class WebCamView : Form
{
PictureBox picture;
public WebCamView()
{
SuspendLayout();
Text = "WebCam";
FormBorderStyle = FormBorderStyle.FixedToolWindow;
ControlBox = false;
ClientSize = new Size(320, 240);
ShowIcon = false;
ShowInTaskbar = false;
picture = new PictureBox();
picture.Name = "Picture";
picture.Dock = DockStyle.Fill;
Controls.Add(picture);
ResumeLayout();
}
public Image Image
{
get { return picture.Image; }
set
{
picture.Image = value;
ClientSize = value.Size;
}
}
private DateTime _timestamp;
public DateTime TimeStamp
{
get { return _timestamp; }
set
{
_timestamp = value;
Text = "WebCam - " + _timestamp.ToString("hh:mm:ss.ff");
}
}
}
class DriveControlEvents
: PortSet<
OnLoad,
OnClosed,
OnChangeJoystick,
OnConnect,
OnConnectMotor,
OnConnectSickLRF,
OnConnectArticulatedArm,
OnConnectWebCam,
OnStartService,
OnMove,
OnEStop,
OnApplyJointParameters,
OnDisconnectSickLRF,
OnDisconnectWebCam,
OnLogSetting,
OnQueryFrame
>
{
}
class DriveControlEvent
{
private DriveControl _driveControl;
public DriveControl DriveControl
{
get { return _driveControl; }
set { _driveControl = value; }
}
public DriveControlEvent(DriveControl driveControl)
{
_driveControl = driveControl;
}
}
class OnLoad : DriveControlEvent
{
public OnLoad(DriveControl form)
: base(form)
{
}
}
class OnConnect : DriveControlEvent
{
string _service;
public string Service
{
get { return _service; }
set { _service = value; }
}
public OnConnect(DriveControl form, string service)
: base(form)
{
_service = service;
}
}
class OnConnectMotor : OnConnect
{
public OnConnectMotor(DriveControl form, string service)
: base(form, service)
{
}
}
class OnConnectSickLRF : OnConnect
{
public OnConnectSickLRF(DriveControl form, string service)
: base(form, service)
{
}
}
class OnConnectArticulatedArm : OnConnect
{
public OnConnectArticulatedArm(DriveControl form, string service)
: base(form, service)
{
}
}
class OnConnectSimulatedArm : OnConnect
{
public OnConnectSimulatedArm(DriveControl form, string service)
: base(form, service)
{
}
}
class OnStartService : DriveControlEvent
{
string _contract;
string _constructor;
public string Contract
{
get { return _contract; }
set { _contract = value; }
}
public string Constructor
{
get { return _constructor; }
set { _constructor = value; }
}
public OnStartService(DriveControl form, string contract)
: base(form)
{
_contract = contract;
}
}
class OnClosed : DriveControlEvent
{
public OnClosed(DriveControl form)
: base(form)
{
}
}
class OnChangeJoystick : DriveControlEvent
{
game.Controller _joystick;
public game.Controller Joystick
{
get { return _joystick; }
set { _joystick = value; }
}
public OnChangeJoystick(DriveControl form)
: base(form)
{
}
}
class OnMove : DriveControlEvent
{
int _left;
public int Left
{
get { return _left; }
set { _left = value; }
}
int _right;
public int Right
{
get { return _right; }
set { _right = value; }
}
public OnMove(DriveControl form, int left, int right)
: base(form)
{
//_left = left * 750 / 1250;
//_right = right * 750 / 1250;
_left = left;
_right = right;
}
}
class OnEStop : DriveControlEvent
{
public OnEStop(DriveControl form)
: base(form)
{
}
}
class OnSynchronizeArms : DriveControlEvent
{
public OnSynchronizeArms(DriveControl form)
: base(form)
{
}
}
class OnApplyJointParameters : DriveControlEvent
{
int _angle;
public int Angle
{
get { return _angle; }
set { _angle = value; }
}
string _jointName;
public string JointName
{
get { return _jointName; }
set { _jointName = value; }
}
public OnApplyJointParameters(DriveControl form, int angle, string name)
: base(form)
{
_angle = angle;
_jointName = name;
}
}
class OnDisconnectSickLRF : DriveControlEvent
{
public OnDisconnectSickLRF(DriveControl form)
: base(form)
{
}
}
class OnLogSetting : DriveControlEvent
{
bool _log;
string _file;
public bool Log
{
get { return _log; }
set { _log = value; }
}
public string File
{
get { return _file; }
set { _file = value; }
}
public OnLogSetting(DriveControl form, bool log, string file)
: base(form)
{
_log = log;
_file = file;
}
}
class OnConnectWebCam : OnConnect
{
public OnConnectWebCam(DriveControl form, string service)
: base(form, service)
{
}
}
class OnDisconnectWebCam : DriveControlEvent
{
public OnDisconnectWebCam(DriveControl form)
: base(form)
{
}
}
class OnQueryFrame : DriveControlEvent
{
public OnQueryFrame(DriveControl form)
: base(form)
{
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Orleans.Runtime.Configuration;
#pragma warning disable CS0618 // Type or member is obsolete
namespace Orleans.Runtime.Host
{
/// <summary>
/// Utility class for initializing an Orleans client running inside Azure.
/// </summary>
public static class AzureClient
{
private static readonly IServiceRuntimeWrapper serviceRuntimeWrapper = new ServiceRuntimeWrapper(AzureSilo.CreateDefaultLoggerFactory("AzureClient.log"));
/// <summary>Number of retry attempts to make when searching for gateway silos to connect to.</summary>
public static readonly int MaxRetries = AzureConstants.MAX_RETRIES; // 120 x 5s = Total: 10 minutes
/// <summary>Amount of time to pause before each retry attempt.</summary>
public static readonly TimeSpan StartupRetryPause = AzureConstants.STARTUP_TIME_PAUSE; // 5 seconds
/// <summary> delegate to configure logging, default to none logger configured </summary>
public static Action<ILoggingBuilder> ConfigureLoggingDelegate { get; set; } = builder => { };
/// <summary>delegate to add some configuration to the client</summary>
public static Action<IClientBuilder> ConfigureClientDelegate { get; set; } = builder => { };
/// <summary>
/// Whether the Orleans Azure client runtime has already been initialized
/// </summary>
/// <returns><c>true</c> if client runtime is already initialized</returns>
public static bool IsInitialized { get { return GrainClient.IsInitialized; } }
/// <summary>
/// Initialise the Orleans client runtime in this Azure process
/// </summary>
public static void Initialize()
{
InitializeImpl_FromFile(null);
}
/// <summary>
/// Initialise the Orleans client runtime in this Azure process
/// </summary>
/// <param name="orleansClientConfigFile">Location of the Orleans client config file to use for base config settings</param>
/// <remarks>Any silo gateway address specified in the config file is ignored, and gateway endpoint info is read from the silo instance table in Azure storage instead.</remarks>
public static void Initialize(FileInfo orleansClientConfigFile)
{
InitializeImpl_FromFile(orleansClientConfigFile);
}
/// <summary>
/// Initialise the Orleans client runtime in this Azure process
/// </summary>
/// <param name="clientConfigFilePath">Location of the Orleans client config file to use for base config settings</param>
/// <remarks>Any silo gateway address specified in the config file is ignored, and gateway endpoint info is read from the silo instance table in Azure storage instead.</remarks>
public static void Initialize(string clientConfigFilePath)
{
InitializeImpl_FromFile(new FileInfo(clientConfigFilePath));
}
/// <summary>
/// Initializes the Orleans client runtime in this Azure process from the provided client configuration object.
/// If the configuration object is null, the initialization fails.
/// </summary>
/// <param name="config">A ClientConfiguration object.</param>
public static void Initialize(ClientConfiguration config)
{
InitializeImpl_FromConfig(config);
}
/// <summary>
/// Uninitializes the Orleans client runtime in this Azure process.
/// </summary>
public static void Uninitialize()
{
if (!GrainClient.IsInitialized) return;
Trace.TraceInformation("Uninitializing connection to Orleans gateway silo.");
GrainClient.Uninitialize();
}
/// <summary>
/// Returns default client configuration object for passing to AzureClient.
/// </summary>
/// <returns></returns>
public static ClientConfiguration DefaultConfiguration()
{
var config = new ClientConfiguration
{
GatewayProvider = ClientConfiguration.GatewayProviderType.AzureTable,
ClusterId = GetDeploymentId(),
DataConnectionString = GetDataConnectionString(),
};
return config;
}
#region Internal implementation of client initialization processing
private static void InitializeImpl_FromFile(FileInfo configFile)
{
if (GrainClient.IsInitialized)
{
Trace.TraceInformation("Connection to Orleans gateway silo already initialized.");
return;
}
ClientConfiguration config;
try
{
if (configFile == null)
{
Trace.TraceInformation("Looking for standard Orleans client config file");
config = ClientConfiguration.StandardLoad();
}
else
{
var configFileLocation = configFile.FullName;
Trace.TraceInformation("Loading Orleans client config file {0}", configFileLocation);
config = ClientConfiguration.LoadFromFile(configFileLocation);
}
}
catch (Exception ex)
{
var msg = String.Format("Error loading Orleans client configuration file {0} {1} -- unable to continue. {2}", configFile, ex.Message, LogFormatter.PrintException(ex));
Trace.TraceError(msg);
throw new AggregateException(msg, ex);
}
Trace.TraceInformation("Overriding Orleans client config from Azure runtime environment.");
try
{
config.ClusterId = GetDeploymentId();
config.DataConnectionString = GetDataConnectionString();
config.GatewayProvider = ClientConfiguration.GatewayProviderType.AzureTable;
}
catch (Exception ex)
{
var msg = string.Format("ERROR: No AzureClient role setting value '{0}' specified for this role -- unable to continue", AzureConstants.DataConnectionConfigurationSettingName);
Trace.TraceError(msg);
throw new AggregateException(msg, ex);
}
InitializeImpl_FromConfig(config);
}
internal static string GetDeploymentId()
{
return GrainClient.TestOnlyNoConnect ? "FakeDeploymentId" : serviceRuntimeWrapper.DeploymentId;
}
internal static string GetDataConnectionString()
{
return GrainClient.TestOnlyNoConnect
? "FakeConnectionString"
: serviceRuntimeWrapper.GetConfigurationSettingValue(AzureConstants.DataConnectionConfigurationSettingName);
}
private static void InitializeImpl_FromConfig(ClientConfiguration config)
{
if (GrainClient.IsInitialized)
{
Trace.TraceInformation("Connection to Orleans gateway silo already initialized.");
return;
}
//// Find endpoint info for the gateway to this Orleans silo cluster
//Trace.WriteLine("Searching for Orleans gateway silo via Orleans instance table...");
var clusterId = config.ClusterId;
var connectionString = config.DataConnectionString;
if (String.IsNullOrEmpty(clusterId))
throw new ArgumentException("Cannot connect to Azure silos with null deploymentId", "config.ClusterId");
if (String.IsNullOrEmpty(connectionString))
throw new ArgumentException("Cannot connect to Azure silos with null connectionString", "config.DataConnectionString");
bool initSucceeded = false;
Exception lastException = null;
for (int i = 0; i < MaxRetries; i++)
{
try
{
GrainClient.ConfigureLoggingDelegate = ConfigureLoggingDelegate;
GrainClient.ConfigureClientDelegate = ConfigureClientDelegate;
// Initialize will throw if cannot find Gateways
GrainClient.Initialize(config);
initSucceeded = true;
break;
}
catch (Exception exc)
{
lastException = exc;
Trace.TraceError("Client.Initialize failed with exc -- {0}. Will try again", exc.Message);
}
// Pause to let Primary silo start up and register
Trace.TraceInformation("Pausing {0} awaiting silo and gateways registration for Deployment={1}", StartupRetryPause, clusterId);
Thread.Sleep(StartupRetryPause);
}
if (initSucceeded) return;
OrleansException err;
err = lastException != null ? new OrleansException(String.Format("Could not Initialize Client for ClusterId={0}. Last exception={1}",
clusterId, lastException.Message), lastException) : new OrleansException(String.Format("Could not Initialize Client for ClusterId={0}.", clusterId));
Trace.TraceError("Error starting Orleans Azure client application -- {0} -- bailing. {1}", err.Message, LogFormatter.PrintException(err));
throw err;
}
#endregion
}
}
#pragma warning restore CS0618 // Type or member is obsolete
| |
// WARNING
//
// This file has been generated automatically by Xamarin Studio from the outlets and
// actions declared in your storyboard file.
// Manual changes to this file will not be maintained.
//
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
namespace MDKControl.iOS
{
[Register ("ModePanoViewController")]
partial class ModePanoViewController
{
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel ExposureValueLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
MDKControl.iOS.TimePickerTableViewCell ExposureValuePickerTableViewCell { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel PanFovSizeValueLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel PanSizeValueLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel PanStartPosValueLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel PanStopPosValueLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel PauseValueLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
MDKControl.iOS.TimePickerTableViewCell PauseValuePickerTableViewCell { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel PostDelayValueLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
MDKControl.iOS.TimePickerTableViewCell PostDelayValuePickerTableViewCell { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel PreDelayValueLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
MDKControl.iOS.TimePickerTableViewCell PreDelayValuePickerTableViewCell { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
MDKControl.iOS.NumberPickerTableViewCell RepetitionsValuePickerTableViewCell { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel RepititionsValueLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
MDKControl.iOS.NumberPickerTableViewCell RepititionsValuePickerTableViewCell { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UIBarButtonItem StartButton { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITableViewCell StartFovTableViewCell { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITableViewCell StartTableViewCell { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITableViewCell StopFovTableViewCell { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITableViewCell StopTableViewCell { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel TiltFovSizeValueLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel TiltSizeValueLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel TiltStartPosValueLabel { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel TiltStopPosValueLabel { get; set; }
void ReleaseDesignerOutlets ()
{
if (ExposureValueLabel != null) {
ExposureValueLabel.Dispose ();
ExposureValueLabel = null;
}
if (ExposureValuePickerTableViewCell != null) {
ExposureValuePickerTableViewCell.Dispose ();
ExposureValuePickerTableViewCell = null;
}
if (PanFovSizeValueLabel != null) {
PanFovSizeValueLabel.Dispose ();
PanFovSizeValueLabel = null;
}
if (PanSizeValueLabel != null) {
PanSizeValueLabel.Dispose ();
PanSizeValueLabel = null;
}
if (PanStartPosValueLabel != null) {
PanStartPosValueLabel.Dispose ();
PanStartPosValueLabel = null;
}
if (PanStopPosValueLabel != null) {
PanStopPosValueLabel.Dispose ();
PanStopPosValueLabel = null;
}
if (PauseValueLabel != null) {
PauseValueLabel.Dispose ();
PauseValueLabel = null;
}
if (PauseValuePickerTableViewCell != null) {
PauseValuePickerTableViewCell.Dispose ();
PauseValuePickerTableViewCell = null;
}
if (PostDelayValueLabel != null) {
PostDelayValueLabel.Dispose ();
PostDelayValueLabel = null;
}
if (PostDelayValuePickerTableViewCell != null) {
PostDelayValuePickerTableViewCell.Dispose ();
PostDelayValuePickerTableViewCell = null;
}
if (PreDelayValueLabel != null) {
PreDelayValueLabel.Dispose ();
PreDelayValueLabel = null;
}
if (PreDelayValuePickerTableViewCell != null) {
PreDelayValuePickerTableViewCell.Dispose ();
PreDelayValuePickerTableViewCell = null;
}
if (RepetitionsValuePickerTableViewCell != null) {
RepetitionsValuePickerTableViewCell.Dispose ();
RepetitionsValuePickerTableViewCell = null;
}
if (RepititionsValueLabel != null) {
RepititionsValueLabel.Dispose ();
RepititionsValueLabel = null;
}
if (RepititionsValuePickerTableViewCell != null) {
RepititionsValuePickerTableViewCell.Dispose ();
RepititionsValuePickerTableViewCell = null;
}
if (StartButton != null) {
StartButton.Dispose ();
StartButton = null;
}
if (StartFovTableViewCell != null) {
StartFovTableViewCell.Dispose ();
StartFovTableViewCell = null;
}
if (StartTableViewCell != null) {
StartTableViewCell.Dispose ();
StartTableViewCell = null;
}
if (StopFovTableViewCell != null) {
StopFovTableViewCell.Dispose ();
StopFovTableViewCell = null;
}
if (StopTableViewCell != null) {
StopTableViewCell.Dispose ();
StopTableViewCell = null;
}
if (TiltFovSizeValueLabel != null) {
TiltFovSizeValueLabel.Dispose ();
TiltFovSizeValueLabel = null;
}
if (TiltSizeValueLabel != null) {
TiltSizeValueLabel.Dispose ();
TiltSizeValueLabel = null;
}
if (TiltStartPosValueLabel != null) {
TiltStartPosValueLabel.Dispose ();
TiltStartPosValueLabel = null;
}
if (TiltStopPosValueLabel != null) {
TiltStopPosValueLabel.Dispose ();
TiltStopPosValueLabel = null;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace CloudStack.Net
{
public class CreateNetworkRequest : APIRequest
{
public CreateNetworkRequest() : base("createNetwork") {}
/// <summary>
/// the display text of the network
/// </summary>
public string DisplayText {
get { return GetParameterValue<string>(nameof(DisplayText).ToLower()); }
set { SetParameterValue(nameof(DisplayText).ToLower(), value); }
}
/// <summary>
/// the name of the network
/// </summary>
public string Name {
get { return GetParameterValue<string>(nameof(Name).ToLower()); }
set { SetParameterValue(nameof(Name).ToLower(), value); }
}
/// <summary>
/// the network offering ID
/// </summary>
public Guid NetworkOfferingId {
get { return GetParameterValue<Guid>(nameof(NetworkOfferingId).ToLower()); }
set { SetParameterValue(nameof(NetworkOfferingId).ToLower(), value); }
}
/// <summary>
/// the zone ID for the network
/// </summary>
public Guid ZoneId {
get { return GetParameterValue<Guid>(nameof(ZoneId).ToLower()); }
set { SetParameterValue(nameof(ZoneId).ToLower(), value); }
}
/// <summary>
/// account that will own the network
/// </summary>
public string Account {
get { return GetParameterValue<string>(nameof(Account).ToLower()); }
set { SetParameterValue(nameof(Account).ToLower(), value); }
}
/// <summary>
/// Network ACL ID associated for the network
/// </summary>
public Guid? AclId {
get { return GetParameterValue<Guid?>(nameof(AclId).ToLower()); }
set { SetParameterValue(nameof(AclId).ToLower(), value); }
}
/// <summary>
/// Access control type; supported values are account and domain. In 3.0 all shared networks should have aclType=Domain, and all isolated networks - Account. Account means that only the account owner can use the network, domain - all accounts in the domain can use the network
/// </summary>
public string AclType {
get { return GetParameterValue<string>(nameof(AclType).ToLower()); }
set { SetParameterValue(nameof(AclType).ToLower(), value); }
}
/// <summary>
/// an optional field, whether to the display the network to the end user or not.
/// </summary>
public bool? DisplayNetwork {
get { return GetParameterValue<bool?>(nameof(DisplayNetwork).ToLower()); }
set { SetParameterValue(nameof(DisplayNetwork).ToLower(), value); }
}
/// <summary>
/// domain ID of the account owning a network
/// </summary>
public Guid? DomainId {
get { return GetParameterValue<Guid?>(nameof(DomainId).ToLower()); }
set { SetParameterValue(nameof(DomainId).ToLower(), value); }
}
/// <summary>
/// the ending IP address in the network IP range. If not specified, will be defaulted to startIP
/// </summary>
public string EndIp {
get { return GetParameterValue<string>(nameof(EndIp).ToLower()); }
set { SetParameterValue(nameof(EndIp).ToLower(), value); }
}
/// <summary>
/// the ending IPv6 address in the IPv6 network range
/// </summary>
public string EndIpv6 {
get { return GetParameterValue<string>(nameof(EndIpv6).ToLower()); }
set { SetParameterValue(nameof(EndIpv6).ToLower(), value); }
}
/// <summary>
/// the gateway of the network. Required for shared networks and isolated networks when it belongs to VPC
/// </summary>
public string Gateway {
get { return GetParameterValue<string>(nameof(Gateway).ToLower()); }
set { SetParameterValue(nameof(Gateway).ToLower(), value); }
}
/// <summary>
/// the CIDR of IPv6 network, must be at least /64
/// </summary>
public string Ip6Cidr {
get { return GetParameterValue<string>(nameof(Ip6Cidr).ToLower()); }
set { SetParameterValue(nameof(Ip6Cidr).ToLower(), value); }
}
/// <summary>
/// the gateway of the IPv6 network. Required for Shared networks
/// </summary>
public string Ip6Gateway {
get { return GetParameterValue<string>(nameof(Ip6Gateway).ToLower()); }
set { SetParameterValue(nameof(Ip6Gateway).ToLower(), value); }
}
/// <summary>
/// the isolated private VLAN for this network
/// </summary>
public string IsolatedPvlan {
get { return GetParameterValue<string>(nameof(IsolatedPvlan).ToLower()); }
set { SetParameterValue(nameof(IsolatedPvlan).ToLower(), value); }
}
/// <summary>
/// the netmask of the network. Required for shared networks and isolated networks when it belongs to VPC
/// </summary>
public string Netmask {
get { return GetParameterValue<string>(nameof(Netmask).ToLower()); }
set { SetParameterValue(nameof(Netmask).ToLower(), value); }
}
/// <summary>
/// network domain
/// </summary>
public string NetworkDomain {
get { return GetParameterValue<string>(nameof(NetworkDomain).ToLower()); }
set { SetParameterValue(nameof(NetworkDomain).ToLower(), value); }
}
/// <summary>
/// the physical network ID the network belongs to
/// </summary>
public Guid? PhysicalNetworkId {
get { return GetParameterValue<Guid?>(nameof(PhysicalNetworkId).ToLower()); }
set { SetParameterValue(nameof(PhysicalNetworkId).ToLower(), value); }
}
/// <summary>
/// an optional project for the SSH key
/// </summary>
public Guid? ProjectId {
get { return GetParameterValue<Guid?>(nameof(ProjectId).ToLower()); }
set { SetParameterValue(nameof(ProjectId).ToLower(), value); }
}
/// <summary>
/// the beginning IP address in the network IP range
/// </summary>
public string StartIp {
get { return GetParameterValue<string>(nameof(StartIp).ToLower()); }
set { SetParameterValue(nameof(StartIp).ToLower(), value); }
}
/// <summary>
/// the beginning IPv6 address in the IPv6 network range
/// </summary>
public string StartIpv6 {
get { return GetParameterValue<string>(nameof(StartIpv6).ToLower()); }
set { SetParameterValue(nameof(StartIpv6).ToLower(), value); }
}
/// <summary>
/// Defines whether to allow subdomains to use networks dedicated to their parent domain(s). Should be used with aclType=Domain, defaulted to allow.subdomain.network.access global config if not specified
/// </summary>
public bool? SubdomainAccess {
get { return GetParameterValue<bool?>(nameof(SubdomainAccess).ToLower()); }
set { SetParameterValue(nameof(SubdomainAccess).ToLower(), value); }
}
/// <summary>
/// the ID or VID of the network
/// </summary>
public string Vlan {
get { return GetParameterValue<string>(nameof(Vlan).ToLower()); }
set { SetParameterValue(nameof(Vlan).ToLower(), value); }
}
/// <summary>
/// the VPC network belongs to
/// </summary>
public Guid? VpcId {
get { return GetParameterValue<Guid?>(nameof(VpcId).ToLower()); }
set { SetParameterValue(nameof(VpcId).ToLower(), value); }
}
}
/// <summary>
/// Creates a network
/// </summary>
public partial interface ICloudStackAPIClient
{
NetworkResponse CreateNetwork(CreateNetworkRequest request);
Task<NetworkResponse> CreateNetworkAsync(CreateNetworkRequest request);
}
public partial class CloudStackAPIClient : ICloudStackAPIClient
{
public NetworkResponse CreateNetwork(CreateNetworkRequest request) => Proxy.Request<NetworkResponse>(request);
public Task<NetworkResponse> CreateNetworkAsync(CreateNetworkRequest request) => Proxy.RequestAsync<NetworkResponse>(request);
}
}
| |
using System.Diagnostics;
using System.Text;
namespace Community.CsharpSqlite
{
using sqlite3_int64 = System.Int64;
using i64 = System.Int64;
using sqlite3_uint64 = System.UInt64;
using u32 = System.UInt32;
using System;
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** Memory allocation functions used throughout sqlite.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
//#include <stdarg.h>
/*
** Attempt to release up to n bytes of non-essential memory currently
** held by SQLite. An example of non-essential memory is memory used to
** cache database pages that are not currently in use.
*/
static int sqlite3_release_memory( int n )
{
#if SQLITE_ENABLE_MEMORY_MANAGEMENT
int nRet = 0;
nRet += sqlite3PcacheReleaseMemory(n-nRet);
return nRet;
#else
UNUSED_PARAMETER( n );
return SQLITE_OK;
#endif
}
/*
** State information local to the memory allocation subsystem.
*/
//static SQLITE_WSD struct Mem0Global {
public class Mem0Global
{/* Number of free pages for scratch and page-cache memory */
public int nScratchFree;
public int nPageFree;
public sqlite3_mutex mutex; /* Mutex to serialize access */
/*
** The alarm callback and its arguments. The mem0.mutex lock will
** be held while the callback is running. Recursive calls into
** the memory subsystem are allowed, but no new callbacks will be
** issued.
*/
public sqlite3_int64 alarmThreshold;
public dxalarmCallback alarmCallback; // (*alarmCallback)(void*, sqlite3_int64,int);
public object alarmArg;
/*
** Pointers to the end of sqlite3GlobalConfig.pScratch and
** sqlite3GlobalConfig.pPage to a block of memory that records
** which pages are available.
*/
//u32 *aScratchFree;
/*
** True if heap is nearly "full" where "full" is defined by the
** sqlite3_soft_heap_limit() setting.
*/
public bool nearlyFull;
public byte[][][] aByte;
public int[] aByteSize;
public int[] aByte_used;
public int[][] aInt;
public Mem[] aMem;
public BtCursor[] aBtCursor;
public struct memstat
{
public int alloc; // # of allocation requests
public int dealloc; // # of deallocations
public int cached; // # of cache hits
public int next; // # Next slot to use
public int max; // # Max slot used
}
public memstat msByte;
public memstat msInt;
public memstat msMem;
public memstat msBtCursor;
public Mem0Global()
{
}
public Mem0Global( int nScratchFree, int nPageFree, sqlite3_mutex mutex, sqlite3_int64 alarmThreshold, dxalarmCallback alarmCallback, object alarmArg, int Byte_Allocation, int Int_Allocation, int Mem_Allocation, int BtCursor_Allocation )
{
this.nScratchFree = nScratchFree;
this.nPageFree = nPageFree;
this.mutex = mutex;
this.alarmThreshold = alarmThreshold;
this.alarmCallback = alarmCallback;
this.alarmArg = alarmArg;
this.msByte.next = -1;
this.msInt.next = -1;
this.msMem.next = -1;
this.aByteSize = new int[] { 32, 256, 1024, 8192, 0 };
this.aByte_used = new int[] { -1, -1, -1, -1, -1 };
this.aByte = new byte[this.aByteSize.Length][][];
for ( int i = 0; i < this.aByteSize.Length; i++ )
this.aByte[i] = new byte[Byte_Allocation][];
this.aInt = new int[Int_Allocation][];
this.aMem = new Mem[Mem_Allocation <= 4 ? 4 : Mem_Allocation];
this.aBtCursor = new BtCursor[BtCursor_Allocation <= 4 ? 4 : BtCursor_Allocation];
this.nearlyFull = false;
}
}
//mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
//#define mem0 GLOBAL(struct Mem0Global, mem0)
static Mem0Global mem0 = new Mem0Global();
/*
** This routine runs when the memory allocator sees that the
** total memory allocation is about to exceed the soft heap
** limit.
*/
static void softHeapLimitEnforcer(
object NotUsed,
sqlite3_int64 NotUsed2,
int allocSize
)
{
UNUSED_PARAMETER2( NotUsed, NotUsed2 );
sqlite3_release_memory( allocSize );
}
//#if !SQLITE_OMIT_DEPRECATED
#if NOT_SQLITE_OMIT_DEPRECATED
/*
** Deprecated external interface. Internal/core SQLite code
** should call sqlite3MemoryAlarm.
*/
int sqlite3_memory_alarm(
void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
void *pArg,
sqlite3_int64 iThreshold
){
return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
}
#endif
/*
** Set the soft heap-size limit for the library. Passing a zero or
** negative value indicates no limit.
*/
static sqlite3_int64 sqlite3_soft_heap_limit64( sqlite3_int64 n )
{
sqlite3_int64 priorLimit;
sqlite3_int64 excess;
#if !SQLITE_OMIT_AUTOINIT
sqlite3_initialize();
#endif
sqlite3_mutex_enter( mem0.mutex );
priorLimit = mem0.alarmThreshold;
sqlite3_mutex_leave( mem0.mutex );
if ( n < 0 )
return priorLimit;
if ( n > 0 )
{
sqlite3MemoryAlarm( softHeapLimitEnforcer, 0, n );
}
else
{
sqlite3MemoryAlarm( null, 0, 0 );
}
excess = sqlite3_memory_used() - n;
if ( excess > 0 )
sqlite3_release_memory( (int)( excess & 0x7fffffff ) );
return priorLimit;
}
void sqlite3_soft_heap_limit( int n )
{
if ( n < 0 )
n = 0;
sqlite3_soft_heap_limit64( n );
}
/*
** Initialize the memory allocation subsystem.
*/
static int sqlite3MallocInit()
{
if ( sqlite3GlobalConfig.m.xMalloc == null )
{
sqlite3MemSetDefault();
}
mem0 = new Mem0Global( 0, 0, null, 0, null, null, 1, 1, 8, 8 ); //memset(&mem0, 0, sizeof(mem0));
if ( sqlite3GlobalConfig.bCoreMutex )
{
mem0.mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MEM );
}
if ( sqlite3GlobalConfig.pScratch != null && sqlite3GlobalConfig.szScratch >= 100
&& sqlite3GlobalConfig.nScratch >= 0 )
{
int i;
sqlite3GlobalConfig.szScratch = ROUNDDOWN8( sqlite3GlobalConfig.szScratch - 4 );
//mem0.aScratchFree = (u32)&((char)sqlite3GlobalConfig.pScratch)
// [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
//for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
//mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
}
else
{
sqlite3GlobalConfig.pScratch = null;
sqlite3GlobalConfig.szScratch = 0;
}
if ( sqlite3GlobalConfig.pPage == null || sqlite3GlobalConfig.szPage < 512
|| sqlite3GlobalConfig.nPage < 1 )
{
sqlite3GlobalConfig.pPage = null;
sqlite3GlobalConfig.szPage = 0;
sqlite3GlobalConfig.nPage = 0;
}
return sqlite3GlobalConfig.m.xInit( sqlite3GlobalConfig.m.pAppData );
}
/*
** Return true if the heap is currently under memory pressure - in other
** words if the amount of heap used is close to the limit set by
** sqlite3_soft_heap_limit().
*/
static bool sqlite3HeapNearlyFull()
{
return mem0.nearlyFull;
}
/*
** Deinitialize the memory allocation subsystem.
*/
static void sqlite3MallocEnd()
{
if ( sqlite3GlobalConfig.m.xShutdown != null )
{
sqlite3GlobalConfig.m.xShutdown( sqlite3GlobalConfig.m.pAppData );
}
mem0 = new Mem0Global();//memset(&mem0, 0, sizeof(mem0));
}
/*
** Return the amount of memory currently checked out.
*/
static sqlite3_int64 sqlite3_memory_used()
{
int n = 0, mx = 0;
sqlite3_int64 res;
sqlite3_status( SQLITE_STATUS_MEMORY_USED, ref n, ref mx, 0 );
res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
return res;
}
/*
** Return the maximum amount of memory that has ever been
** checked out since either the beginning of this process
** or since the most recent reset.
*/
static sqlite3_int64 sqlite3_memory_highwater( int resetFlag )
{
int n = 0, mx = 0;
sqlite3_int64 res;
sqlite3_status( SQLITE_STATUS_MEMORY_USED, ref n, ref mx, resetFlag );
res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
return res;
}
/*
** Change the alarm callback
*/
static int sqlite3MemoryAlarm(
dxalarmCallback xCallback, //void(*xCallback)(object pArg, sqlite3_int64 used,int N),
object pArg,
sqlite3_int64 iThreshold
)
{
int nUsed;
sqlite3_mutex_enter( mem0.mutex );
mem0.alarmCallback = xCallback;
mem0.alarmArg = pArg;
mem0.alarmThreshold = iThreshold;
nUsed = sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED );
mem0.nearlyFull = ( iThreshold > 0 && iThreshold <= nUsed );
sqlite3_mutex_leave( mem0.mutex );
return SQLITE_OK;
}
/*
** Trigger the alarm
*/
static void sqlite3MallocAlarm( int nByte )
{
dxalarmCallback xCallback;//void (*xCallback)(void*,sqlite3_int64,int);
sqlite3_int64 nowUsed;
object pArg;// void* pArg;
if ( mem0.alarmCallback == null )
return;
xCallback = mem0.alarmCallback;
nowUsed = sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED );
pArg = mem0.alarmArg;
mem0.alarmCallback = null;
sqlite3_mutex_leave( mem0.mutex );
xCallback( pArg, nowUsed, nByte );
sqlite3_mutex_enter( mem0.mutex );
mem0.alarmCallback = xCallback;
mem0.alarmArg = pArg;
}
/*
** Do a memory allocation with statistics and alarms. Assume the
** lock is already held.
*/
static int mallocWithAlarm( int n, ref int[] pp )
{
int nFull;
int[] p;
Debug.Assert( sqlite3_mutex_held( mem0.mutex ) );
nFull = sqlite3GlobalConfig.m.xRoundup( n );
sqlite3StatusSet( SQLITE_STATUS_MALLOC_SIZE, n );
if ( mem0.alarmCallback != null )
{
int nUsed = sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED );
if ( nUsed >= mem0.alarmThreshold - nFull )
{
mem0.nearlyFull = true;
sqlite3MallocAlarm( nFull );
}
else
{
mem0.nearlyFull = false;
}
}
p = sqlite3GlobalConfig.m.xMallocInt( nFull );
#if SQLITE_ENABLE_MEMORY_MANAGEMENT
if( p==null && mem0.alarmCallback!=null ){
sqlite3MallocAlarm(nFull);
p = sqlite3GlobalConfig.m.xMalloc(nFull);
}
#endif
if ( p != null )
{
nFull = sqlite3MallocSize( p );
sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, nFull );
}
pp = p;
return nFull;
}
static int mallocWithAlarm( int n, ref byte[] pp )
{
int nFull;
byte[] p;
Debug.Assert( sqlite3_mutex_held( mem0.mutex ) );
nFull = sqlite3GlobalConfig.m.xRoundup( n );
sqlite3StatusSet( SQLITE_STATUS_MALLOC_SIZE, n );
if ( mem0.alarmCallback != null )
{
int nUsed = sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED );
if ( nUsed + nFull >= mem0.alarmThreshold )
{
sqlite3MallocAlarm( nFull );
}
}
p = sqlite3GlobalConfig.m.xMalloc( nFull );
if ( p == null && mem0.alarmCallback != null )
{
sqlite3MallocAlarm( nFull );
p = sqlite3GlobalConfig.m.xMalloc( nFull );
}
if ( p != null )
{
nFull = sqlite3MallocSize( p );
sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, nFull );
sqlite3StatusAdd( SQLITE_STATUS_MALLOC_COUNT, 1 );
}
pp = p;
return nFull;
}
/*
** Allocate memory. This routine is like sqlite3_malloc() except that it
** assumes the memory subsystem has already been initialized.
*/
static Mem sqlite3Malloc( Mem pMem )
{
return sqlite3GlobalConfig.m.xMallocMem( pMem );
}
static int[] sqlite3Malloc( int[] pInt, u32 n )
{
return sqlite3Malloc( pInt, (int)n );
}
static int[] sqlite3Malloc( int[] pInt, int n )
{
int[] p = null;
if ( n < 0 || n >= 0x7fffff00 )
{
/* A memory allocation of a number of bytes which is near the maximum
** signed integer value might cause an integer overflow inside of the
** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
** 255 bytes of overhead. SQLite itself will never use anything near
** this amount. The only way to reach the limit is with sqlite3_malloc() */
p = null;
}
else if ( sqlite3GlobalConfig.bMemstat )
{
sqlite3_mutex_enter( mem0.mutex );
mallocWithAlarm( n, ref p );
sqlite3_mutex_leave( mem0.mutex );
}
else
{
p = sqlite3GlobalConfig.m.xMallocInt( n );
}
return p;
}
static byte[] sqlite3Malloc( u32 n )
{
return sqlite3Malloc( (int)n );
}
static byte[] sqlite3Malloc( int n )
{
byte[] p = null;
if ( n < 0 || n >= 0x7fffff00 )
{
/* A memory allocation of a number of bytes which is near the maximum
** signed integer value might cause an integer overflow inside of the
** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
** 255 bytes of overhead. SQLite itself will never use anything near
** this amount. The only way to reach the limit is with sqlite3_malloc() */
p = null;
}
else if ( sqlite3GlobalConfig.bMemstat )
{
sqlite3_mutex_enter( mem0.mutex );
mallocWithAlarm( n, ref p );
sqlite3_mutex_leave( mem0.mutex );
}
else
{
p = sqlite3GlobalConfig.m.xMalloc( n );
}
return p;
}
/*
** This version of the memory allocation is for use by the application.
** First make sure the memory subsystem is initialized, then do the
** allocation.
*/
static byte[] sqlite3_malloc( int n )
{
#if !SQLITE_OMIT_AUTOINIT
if ( sqlite3_initialize() != 0 )
return null;
#endif
return sqlite3Malloc( n );
}
/*
** Each thread may only have a single outstanding allocation from
** xScratchMalloc(). We verify this constraint in the single-threaded
** case by setting scratchAllocOut to 1 when an allocation
** is outstanding clearing it when the allocation is freed.
*/
#if SQLITE_THREADSAFE && !(NDEBUG)
static int scratchAllocOut = 0;
#endif
/*
** Allocate memory that is to be used and released right away.
** This routine is similar to alloca() in that it is not intended
** for situations where the memory might be held long-term. This
** routine is intended to get memory to old large transient data
** structures that would not normally fit on the stack of an
** embedded processor.
*/
static byte[][] sqlite3ScratchMalloc( byte[][] apCell, int n )
{
apCell = sqlite3GlobalConfig.pScratch2;
if ( apCell == null )
apCell = new byte[n < 200 ? 200 : n][];
else if ( apCell.Length < n )
Array.Resize( ref apCell, n );
sqlite3GlobalConfig.pScratch2 = null;
return apCell;
}
static byte[] sqlite3ScratchMalloc( int n )
{
byte[] p = null;
Debug.Assert( n > 0 );
#if SQLITE_THREADSAFE && !(NDEBUG)
/* Verify that no more than two scratch allocation per thread
** is outstanding at one time. (This is only checked in the
** single-threaded case since checking in the multi-threaded case
** would be much more complicated.) */
Debug.Assert( scratchAllocOut <= 1 );
#endif
if ( sqlite3GlobalConfig.szScratch < n )
{
goto scratch_overflow;
}
else
{
sqlite3_mutex_enter( mem0.mutex );
if ( mem0.nScratchFree == 0 )
{
sqlite3_mutex_leave( mem0.mutex );
goto scratch_overflow;
}
else
{
int i;
//i = mem0.aScratchFree[--mem0.nScratchFree];
//i *= sqlite3GlobalConfig.szScratch;
for ( i = 0; i < sqlite3GlobalConfig.pScratch.Length; i++ )
{
if ( sqlite3GlobalConfig.pScratch[i] == null || sqlite3GlobalConfig.pScratch[i].Length < n )
continue;
p = sqlite3GlobalConfig.pScratch[i];// (void)&((char)sqlite3GlobalConfig.pScratch)[i];
sqlite3GlobalConfig.pScratch[i] = null;
break;
}
sqlite3_mutex_leave( mem0.mutex );
if ( p == null )
goto scratch_overflow;
sqlite3StatusAdd( SQLITE_STATUS_SCRATCH_USED, 1 );
sqlite3StatusSet( SQLITE_STATUS_SCRATCH_SIZE, n );
//Debug.Assert( (((u8)p - (u8)0) & 7)==0 );
}
}
#if SQLITE_THREADSAFE && !(NDEBUG)
scratchAllocOut = ( p != null ? 1 : 0 );
#endif
return p;
scratch_overflow:
if ( sqlite3GlobalConfig.bMemstat )
{
sqlite3_mutex_enter( mem0.mutex );
sqlite3StatusSet( SQLITE_STATUS_SCRATCH_SIZE, n );
n = mallocWithAlarm( n, ref p );
if ( p != null )
sqlite3StatusAdd( SQLITE_STATUS_SCRATCH_OVERFLOW, n );
sqlite3_mutex_leave( mem0.mutex );
}
else
{
p = sqlite3GlobalConfig.m.xMalloc( n );
}
sqlite3MemdebugSetType( p, MEMTYPE_SCRATCH );
#if SQLITE_THREADSAFE && !(NDEBUG)
scratchAllocOut = ( p != null ) ? 1 : 0;
#endif
return p;
}
static void sqlite3ScratchFree( byte[][] p )
{
if ( p != null )
{
if ( sqlite3GlobalConfig.pScratch2 == null || sqlite3GlobalConfig.pScratch2.Length < p.Length )
{
Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_SCRATCH ) );
Debug.Assert( sqlite3MemdebugNoType( p, ~MEMTYPE_SCRATCH ) );
sqlite3MemdebugSetType( p, MEMTYPE_HEAP );
if ( sqlite3GlobalConfig.bMemstat )
{
int iSize = sqlite3MallocSize( p );
sqlite3_mutex_enter( mem0.mutex );
sqlite3StatusAdd( SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize );
sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, -iSize );
sqlite3StatusAdd( SQLITE_STATUS_MALLOC_COUNT, -1 );
sqlite3GlobalConfig.pScratch2 = p;// sqlite3GlobalConfig.m.xFree(ref p);
sqlite3_mutex_leave( mem0.mutex );
}
else
{
sqlite3GlobalConfig.pScratch2 = p;//sqlite3GlobalConfig.m.xFree(ref p);
}
}
else // larger Scratch 2 already in use, let the C# GC handle
{
//int i;
//i = (int)((u8)p - (u8)sqlite3GlobalConfig.pScratch);
//i /= sqlite3GlobalConfig.szScratch;
//Debug.Assert(i >= 0 && i < sqlite3GlobalConfig.nScratch);
//sqlite3_mutex_enter(mem0.mutex);
//Debug.Assert(mem0.nScratchFree < (u32)sqlite3GlobalConfig.nScratch);
//mem0.aScratchFree[mem0.nScratchFree++] = i;
//sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
//sqlite3_mutex_leave(mem0.mutex);
#if SQLITE_THREADSAFE && !(NDEBUG)
/* Verify that no more than two scratch allocation per thread
** is outstanding at one time. (This is only checked in the
** single-threaded case since checking in the multi-threaded case
** would be much more complicated.) */
Debug.Assert( scratchAllocOut >= 1 && scratchAllocOut <= 2 );
scratchAllocOut = 0;
#endif
}
//if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
// /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
// ScratchFreeslot *pSlot;
// pSlot = (ScratchFreeslot)p;
// sqlite3_mutex_enter(mem0.mutex);
// pSlot->pNext = mem0.pScratchFree;
// mem0.pScratchFree = pSlot;
// mem0.nScratchFree++;
// Debug.Assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
// sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
// sqlite3_mutex_leave(mem0.mutex);
//}else{
// /* Release memory back to the heap */
// Debug.Assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
// Debug.Assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
// sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
// if( sqlite3GlobalConfig.bMemstat ){
// int iSize = sqlite3MallocSize(p);
// sqlite3_mutex_enter(mem0.mutex);
// sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
// sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
// sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
// sqlite3GlobalConfig.m.xFree(p);
// sqlite3_mutex_leave(mem0.mutex);
// }else{
// sqlite3GlobalConfig.m.xFree(p);
// }
p = null;
}
}
/*
** TRUE if p is a lookaside memory allocation from db
*/
#if NO_SQLITE_OMIT_LOOKASIDE //#if !SQLITE_OMIT_LOOKASIDE
static int isLookaside(sqlite3 db, object *p){
return p && p>=db.lookaside.pStart && p<db.lookaside.pEnd;
}
#else
//#define isLookaside(A,B) 0
static bool isLookaside( sqlite3 db, object p )
{
return false;
}
#endif
/*
** Return the size of a memory allocation previously obtained from
** sqlite3Malloc() or sqlite3_malloc().
*/
//int sqlite3MallocSize(void* p)
//{
// Debug.Assert(sqlite3MemdebugHasType(p, MEMTYPE_HEAP));
// Debug.Assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
// return sqlite3GlobalConfig.m.xSize(p);
//}
static int sqlite3MallocSize( byte[][] p )
{
return p.Length * p[0].Length;
}
static int sqlite3MallocSize( int[] p )
{
return p.Length;
}
static int sqlite3MallocSize( byte[] p )
{
return sqlite3GlobalConfig.m.xSize( p );
}
static int sqlite3DbMallocSize( sqlite3 db, byte[] p )
{
Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) );
if ( db != null && isLookaside( db, p ) )
{
return db.lookaside.sz;
}
else
{
Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_DB ) );
Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_LOOKASIDE | MEMTYPE_HEAP ) );
Debug.Assert( db != null || sqlite3MemdebugNoType( p, MEMTYPE_LOOKASIDE ) );
return sqlite3GlobalConfig.m.xSize( p );
}
}
/*
** Free memory previously obtained from sqlite3Malloc().
*/
static void sqlite3_free( ref byte[] p )
{
if ( p == null )
return;
Debug.Assert( sqlite3MemdebugNoType( p, MEMTYPE_DB ) );
Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_HEAP ) );
if ( sqlite3GlobalConfig.bMemstat )
{
sqlite3_mutex_enter( mem0.mutex );
sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize( p ) );
sqlite3StatusAdd( SQLITE_STATUS_MALLOC_COUNT, -1 );
sqlite3GlobalConfig.m.xFree( ref p );
sqlite3_mutex_leave( mem0.mutex );
}
else
{
sqlite3GlobalConfig.m.xFree( ref p );
}
p = null;
}
static void sqlite3_free( ref Mem p )
{
if ( p == null )
return;
if ( sqlite3GlobalConfig.bMemstat )
{
sqlite3_mutex_enter( mem0.mutex );
//sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize( p ) );
sqlite3GlobalConfig.m.xFreeMem( ref p );
sqlite3_mutex_leave( mem0.mutex );
}
else
{
sqlite3GlobalConfig.m.xFreeMem( ref p );
}
p = null;
}
/*
** Free memory that might be associated with a particular database
** connection.
*/
static void sqlite3DbFree( sqlite3 db, ref byte[] p )
{
Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) );
if ( db != null )
{
//if ( db.pnBytesFreed != 0 )
//{
#if !NO_SQLITE_OMIT_LOOKASIDE
//db.pnBytesFreed += 1;
#else
db.pnBytesFreed += sqlite3DbMallocSize( db, p );
#endif
return;
//}
#if NO_SQLITE_OMIT_LOOKASIDE //#if !SQLITE_OMIT_LOOKASIDE
if( isLookaside(db, p) ){
LookasideSlot *pBuf = (LookasideSlot)p;
pBuf.pNext = db.lookaside.pFree;
db.lookaside.pFree = pBuf;
db.lookaside.nOut--;
}else
#endif
//{
// Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_DB ) );
// Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_LOOKASIDE | MEMTYPE_HEAP ) );
// Debug.Assert( db != null || sqlite3MemdebugNoType( p, MEMTYPE_LOOKASIDE ) );
// sqlite3MemdebugSetType( p, MEMTYPE_HEAP );
// sqlite3_free( ref p );
//}
}
}
/*
** Change the size of an existing memory allocation
*/
static byte[] sqlite3Realloc( byte[] pOld, int nBytes )
{
int nOld, nNew, nDiff;
byte[] pNew;
if ( pOld == null )
{
pOld = sqlite3Malloc( nBytes );
return pOld;
}
if ( nBytes < 0 )
{
sqlite3_free( ref pOld );
return null;
}
if ( nBytes >= 0x7fffff00 )
{
/* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
return null;
}
nOld = sqlite3MallocSize( pOld );
nNew = sqlite3GlobalConfig.m.xRoundup( nBytes );
if ( nOld == nNew )
{
pNew = pOld;
}
else if ( sqlite3GlobalConfig.bMemstat )
{
sqlite3_mutex_enter( mem0.mutex );
sqlite3StatusSet( SQLITE_STATUS_MALLOC_SIZE, nBytes );
nDiff = nNew - nOld;
if ( sqlite3StatusValue( SQLITE_STATUS_MEMORY_USED ) >=
mem0.alarmThreshold - nDiff )
{
sqlite3MallocAlarm( nDiff );
}
Debug.Assert( sqlite3MemdebugHasType( pOld, MEMTYPE_HEAP ) );
Debug.Assert( sqlite3MemdebugNoType( pOld, ~MEMTYPE_HEAP ) );
pNew = sqlite3GlobalConfig.m.xRealloc( pOld, nNew );
if ( pNew == null && mem0.alarmCallback != null )
{
sqlite3MallocAlarm( nBytes );
pNew = sqlite3GlobalConfig.m.xRealloc( pOld, nNew );
}
if ( pNew != null )
{
nNew = sqlite3MallocSize( pNew );
sqlite3StatusAdd( SQLITE_STATUS_MEMORY_USED, nNew - nOld );
}
sqlite3_mutex_leave( mem0.mutex );
}
else
{
pNew = sqlite3GlobalConfig.m.xRealloc( pOld, nNew );
}
return pNew;
}
/*
** The public interface to sqlite3Realloc. Make sure that the memory
** subsystem is initialized prior to invoking sqliteRealloc.
*/
static byte[] sqlite3_realloc( byte[] pOld, int n )
{
#if !SQLITE_OMIT_AUTOINIT
if ( sqlite3_initialize() != 0 )
return null;
#endif
return sqlite3Realloc( pOld, n );
}
/*
** Allocate and zero memory.
*/
static byte[] sqlite3MallocZero( int n )
{
byte[] p = sqlite3Malloc( n );
if ( p != null )
{
Array.Clear( p, 0, n );// memset(p, 0, n);
}
return p;
}
/*
** Allocate and zero memory. If the allocation fails, make
** the mallocFailed flag in the connection pointer.
*/
static Mem sqlite3DbMallocZero( sqlite3 db, Mem m )
{
return new Mem();
}
static byte[] sqlite3DbMallocZero( sqlite3 db, int n )
{
byte[] p = sqlite3DbMallocRaw( db, n );
if ( p != null )
{
Array.Clear( p, 0, n );// memset(p, 0, n);
}
return p;
}
/*
** Allocate and zero memory. If the allocation fails, make
** the mallocFailed flag in the connection pointer.
**
** If db!=0 and db->mallocFailed is true (indicating a prior malloc
** failure on the same database connection) then always return 0.
** Hence for a particular database connection, once malloc starts
** failing, it fails consistently until mallocFailed is reset.
** This is an important assumption. There are many places in the
** code that do things like this:
**
** int *a = (int)sqlite3DbMallocRaw(db, 100);
** int *b = (int)sqlite3DbMallocRaw(db, 200);
** if( b ) a[10] = 9;
**
** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
** that all prior mallocs (ex: "a") worked too.
*/
static byte[] sqlite3DbMallocRaw( sqlite3 db, int n )
{
byte[] p;
Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) );
Debug.Assert( db == null || db.pnBytesFreed == 0 );
#if NO_SQLITE_OMIT_LOOKASIDE //#if !SQLITE_OMIT_LOOKASIDE
if( db ){
LookasideSlot *pBuf;
if( db->mallocFailed ){
return 0;
}
if( db->lookaside.bEnabled ){
if( n>db->lookaside.sz ){
db->lookaside.anStat[1]++;
}else if( (pBuf = db->lookaside.pFree)==0 ){
db->lookaside.anStat[2]++;
}else{
db->lookaside.pFree = pBuf->pNext;
db->lookaside.nOut++;
db->lookaside.anStat[0]++;
if( db->lookaside.nOut>db->lookaside.mxOut ){
db->lookaside.mxOut = db->lookaside.nOut;
}
return (void)pBuf;
}
}
}
#else
//if( db && db->mallocFailed ){
// return 0;
//}
#endif
p = sqlite3Malloc( n );
//if( null==p && db ){
// db->mallocFailed = 1;
//}
#if NO_SQLITE_OMIT_LOOKASIDE //#if !SQLITE_OMIT_LOOKASIDE
sqlite3MemdebugSetType(p, MEMTYPE_DB |
((db !=null && db.lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
#endif
return p;
}
/*
** Resize the block of memory pointed to by p to n bytes. If the
** resize fails, set the mallocFailed flag in the connection object.
*/
static byte[] sqlite3DbRealloc( sqlite3 db, byte[] p, int n )
{
byte[] pNew = null;
Debug.Assert( db != null );
Debug.Assert( sqlite3_mutex_held( db.mutex ) );
//if( db->mallocFailed==0 ){
if ( p == null )
{
return sqlite3DbMallocRaw( db, n );
}
#if NO_SQLITE_OMIT_LOOKASIDE //#if !SQLITE_OMIT_LOOKASIDE
if( isLookaside(db, p) ){
if( n<=db->lookaside.sz ){
return p;
}
pNew = sqlite3DbMallocRaw(db, n);
if( pNew ){
memcpy(pNew, p, db->lookaside.sz);
sqlite3DbFree(db, ref p);
}
}else
#else
{
{
#endif
Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_DB ) );
Debug.Assert( sqlite3MemdebugHasType( p, MEMTYPE_LOOKASIDE | MEMTYPE_HEAP ) );
sqlite3MemdebugSetType( p, MEMTYPE_HEAP );
pNew = sqlite3_realloc( p, n );
//if( null==pNew ){
//sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
// db->mallocFailed = 1;
//}
#if NO_SQLITE_OMIT_LOOKASIDE //#if !SQLITE_OMIT_LOOKASIDE
sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
(db.lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
#endif
}
}
return pNew;
}
/*
** Attempt to reallocate p. If the reallocation fails, then free p
** and set the mallocFailed flag in the database connection.
*/
static byte[] sqlite3DbReallocOrFree( sqlite3 db, byte[] p, int n )
{
byte[] pNew;
pNew = sqlite3DbRealloc( db, p, n );
if ( null == pNew )
{
sqlite3DbFree( db, ref p );
}
return pNew;
}
/*
** Make a copy of a string in memory obtained from sqliteMalloc(). These
** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
** is because when memory debugging is turned on, these two functions are
** called via macros that record the current file and line number in the
** ThreadData structure.
*/
//char *sqlite3DbStrDup(sqlite3 db, string z){
// string zNew;
// size_t n;
// if( z==0 ){
// return 0;
// }
// n = sqlite3Strlen30(z) + 1;
// Debug.Assert( (n&0x7fffffff)==n );
// zNew = sqlite3DbMallocRaw(db, (int)n);
// if( zNew ){
// memcpy(zNew, z, n);
// }
// return zNew;
//}
//char *sqlite3DbStrNDup(sqlite3 db, string z, int n){
// string zNew;
// if( z==0 ){
// return 0;
// }
// Debug.Assert( (n&0x7fffffff)==n );
// zNew = sqlite3DbMallocRaw(db, n+1);
// if( zNew ){
// memcpy(zNew, z, n);
// zNew[n] = 0;
// }
// return zNew;
//}
/*
** Create a string from the zFromat argument and the va_list that follows.
** Store the string in memory obtained from sqliteMalloc() and make pz
** point to that string.
*/
static void sqlite3SetString( ref string pz, sqlite3 db, string zFormat, params string[] ap )
{
//va_list ap;
lock ( lock_va_list )
{
string z;
va_start( ap, zFormat );
z = sqlite3VMPrintf( db, zFormat, ap );
va_end( ref ap );
sqlite3DbFree( db, ref pz );
pz = z;
}
}
/*
** This function must be called before exiting any API function (i.e.
** returning control to the user) that has called sqlite3_malloc or
** sqlite3_realloc.
**
** The returned value is normally a copy of the second argument to this
** function. However, if a malloc() failure has occurred since the previous
** invocation SQLITE_NOMEM is returned instead.
**
** If the first argument, db, is not NULL and a malloc() error has occurred,
** then the connection error-code (the value returned by sqlite3_errcode())
** is set to SQLITE_NOMEM.
*/
static int sqlite3ApiExit( int zero, int rc )
{
sqlite3 db = null;
return sqlite3ApiExit( db, rc );
}
static int sqlite3ApiExit( sqlite3 db, int rc )
{
/* If the db handle is not NULL, then we must hold the connection handle
** mutex here. Otherwise the read (and possible write) of db.mallocFailed
** is unsafe, as is the call to sqlite3Error().
*/
Debug.Assert( db == null || sqlite3_mutex_held( db.mutex ) );
if ( /*db != null && db.mallocFailed != 0 || */ rc == SQLITE_IOERR_NOMEM )
{
sqlite3Error( db, SQLITE_NOMEM, "" );
//db.mallocFailed = 0;
rc = SQLITE_NOMEM;
}
return rc & ( db != null ? db.errMask : 0xff );
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2012-2018 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NUnit.Compatibility;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal
{
/// <summary>
/// The Test abstract class represents a test within the framework.
/// </summary>
public abstract class Test : ITest, IComparable
{
#region Fields
/// <summary>
/// Static value to seed ids. It's started at 1000 so any
/// uninitialized ids will stand out.
/// </summary>
private static int _nextID = 1000;
#endregion
#region Construction
/// <summary>
/// Constructs a test given its name
/// </summary>
/// <param name="name">The name of the test</param>
protected Test( string name )
{
Guard.ArgumentNotNullOrEmpty(name, nameof(name));
Initialize(name);
}
/// <summary>
/// Constructs a test given the path through the
/// test hierarchy to its parent and a name.
/// </summary>
/// <param name="pathName">The parent tests full name</param>
/// <param name="name">The name of the test</param>
protected Test( string pathName, string name )
{
Initialize(name);
if (!string.IsNullOrEmpty(pathName))
FullName = pathName + "." + name;
}
/// <summary>
/// Constructs a test for a specific type.
/// </summary>
protected Test(Type type)
{
Initialize(TypeHelper.GetDisplayName(type));
string nspace = type.Namespace;
if (nspace != null && nspace != "")
FullName = nspace + "." + Name;
Type = type;
}
/// <summary>
/// Constructs a test for a specific method.
/// </summary>
protected Test(FixtureMethod method)
{
Initialize(method.Method.Name);
Method = method.Method;
Type = method.FixtureType;
FullName = Type.FullName + "." + Name;
}
private void Initialize(string name)
{
FullName = Name = name;
Id = GetNextId();
Properties = new PropertyBag();
RunState = RunState.Runnable;
SetUpMethods = new MethodInfo[0];
TearDownMethods = new MethodInfo[0];
}
private static string GetNextId()
{
return IdPrefix + unchecked(_nextID++);
}
#endregion
#region ITest Members
/// <summary>
/// Gets or sets the id of the test
/// </summary>
/// <value></value>
public string Id { get; set; }
/// <summary>
/// Gets or sets the name of the test
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the fully qualified name of the test
/// </summary>
/// <value></value>
public string FullName { get; set; }
/// <summary>
/// Gets the name of the class where this test was declared.
/// Returns null if the test is not associated with a class.
/// </summary>
public string ClassName
{
get
{
Type type = Method?.DeclaringType ?? Type;
if (type == null)
return null;
return type.GetTypeInfo().IsGenericType
? type.GetGenericTypeDefinition().FullName
: type.FullName;
}
}
/// <summary>
/// Gets the name of the method implementing this test.
/// Returns null if the test is not implemented as a method.
/// </summary>
public virtual string MethodName
{
get { return null; }
}
/// <summary>
/// The arguments to use in creating the test or empty array if none required.
/// </summary>
public abstract object[] Arguments { get; }
/// <summary>
/// Gets the type which declares the fixture, or <see langword="null"/>
/// if no fixture type is associated with this test.
/// </summary>
public Type Type { get; }
/// <summary>
/// Gets the method which declares the test, or <see langword="null"/>
/// if no method is associated with this test.
/// </summary>
public MethodInfo Method { get; internal set; }
/// <summary>
/// Whether or not the test should be run
/// </summary>
public RunState RunState { get; set; }
/// <summary>
/// Gets the name used for the top-level element in the
/// XML representation of this test
/// </summary>
public abstract string XmlElementName { get; }
/// <summary>
/// Gets a string representing the type of test. Used as an attribute
/// value in the XML representation of a test and has no other
/// function in the framework.
/// </summary>
public virtual string TestType
{
get { return this.GetType().Name; }
}
/// <summary>
/// Gets a count of test cases represented by
/// or contained under this test.
/// </summary>
public virtual int TestCaseCount
{
get { return 1; }
}
/// <summary>
/// Gets the properties for this test
/// </summary>
public IPropertyBag Properties { get; private set; }
/// <summary>
/// Returns true if this is a TestSuite
/// </summary>
public bool IsSuite
{
get { return this is TestSuite; }
}
/// <summary>
/// Gets a bool indicating whether the current test
/// has any descendant tests.
/// </summary>
public abstract bool HasChildren { get; }
/// <summary>
/// Gets the parent as a Test object.
/// Used by the core to set the parent.
/// </summary>
public ITest Parent { get; set; }
/// <summary>
/// Gets this test's child tests
/// </summary>
/// <value>A list of child tests</value>
public abstract IList<ITest> Tests { get; }
/// <summary>
/// Gets or sets a fixture object for running this test.
/// </summary>
public virtual object Fixture { get; set; }
#endregion
#region Other Public Properties
/// <summary>
/// Static prefix used for ids in this AppDomain.
/// Set by FrameworkController.
/// </summary>
public static string IdPrefix { get; set; }
/// <summary>
/// Gets or Sets the Int value representing the seed for the RandomGenerator
/// </summary>
/// <value></value>
public int Seed { get; set; }
/// <summary>
/// The SetUp methods.
/// </summary>
public MethodInfo[] SetUpMethods { get; protected set; }
/// <summary>
/// The teardown methods
/// </summary>
public MethodInfo[] TearDownMethods { get; protected set; }
#endregion
#region Internal Properties
internal bool RequiresThread { get; set; }
private ITestAction[] _actions;
internal ITestAction[] Actions
{
get
{
if (_actions == null)
{
// For fixtures, we use special rules to get actions
// Otherwise we just get the attributes
_actions = Method == null && Type != null
? GetActionsForType(Type)
: GetCustomAttributes<ITestAction>(false);
}
return _actions;
}
}
#endregion
#region Other Public Methods
/// <summary>
/// Creates a TestResult for this test.
/// </summary>
/// <returns>A TestResult suitable for this type of test.</returns>
public abstract TestResult MakeTestResult();
#if NETSTANDARD1_4
/// <summary>
/// Modify a newly constructed test by applying any of NUnit's common
/// attributes, based on a supplied <see cref="MemberInfo"/>, which is
/// usually the reflection element from which the test was constructed,
/// but may not be in some instances. The attributes retrieved are
/// saved for use in subsequent operations.
/// </summary>
public void ApplyAttributesToTest(MemberInfo provider)
{
ApplyAttributesToTest(provider.GetAttributes<IApplyToTest>(inherit: true));
}
/// <summary>
/// Modify a newly constructed test by applying any of NUnit's common
/// attributes, based on a supplied <see cref="TypeInfo"/>, which is
/// usually the reflection element from which the test was constructed,
/// but may not be in some instances. The attributes retrieved are
/// saved for use in subsequent operations.
/// </summary>
public void ApplyAttributesToTest(TypeInfo provider)
{
ApplyAttributesToTest(provider.GetAttributes<IApplyToTest>(inherit: true));
}
/// <summary>
/// Modify a newly constructed test by applying any of NUnit's common
/// attributes, based on a supplied <see cref="Assembly"/>, which is
/// usually the reflection element from which the test was constructed,
/// but may not be in some instances. The attributes retrieved are
/// saved for use in subsequent operations.
/// </summary>
public void ApplyAttributesToTest(Assembly provider)
{
ApplyAttributesToTest(provider.GetAttributes<IApplyToTest>());
}
#else
/// <summary>
/// Modify a newly constructed test by applying any of NUnit's common
/// attributes, based on a supplied <see cref="ICustomAttributeProvider"/>, which is
/// usually the reflection element from which the test was constructed,
/// but may not be in some instances. The attributes retrieved are
/// saved for use in subsequent operations.
/// </summary>
public void ApplyAttributesToTest(ICustomAttributeProvider provider)
{
ApplyAttributesToTest(provider.GetAttributes<IApplyToTest>(inherit: true));
}
#endif
private void ApplyAttributesToTest(IEnumerable<IApplyToTest> attributes)
{
foreach (IApplyToTest iApply in attributes)
iApply.ApplyToTest(this);
}
/// <summary>
/// Mark the test as Invalid (not runnable) specifying a reason
/// </summary>
/// <param name="reason">The reason the test is not runnable</param>
public void MakeInvalid(string reason)
{
Guard.ArgumentNotNullOrEmpty(reason, nameof(reason));
RunState = RunState.NotRunnable;
Properties.Add(PropertyNames.SkipReason, reason);
}
/// <summary>
/// Get custom attributes applied to a test
/// </summary>
public virtual TAttr[] GetCustomAttributes<TAttr>(bool inherit) where TAttr : class
{
if (Method != null)
return Method.GetAttributes<TAttr>(inherit);
if (Type != null)
return Type.GetAttributes<TAttr>(inherit);
return new TAttr[0];
}
#endregion
#region Protected Methods
/// <summary>
/// Add standard attributes and members to a test node.
/// </summary>
/// <param name="thisNode"></param>
/// <param name="recursive"></param>
protected void PopulateTestNode(TNode thisNode, bool recursive)
{
thisNode.AddAttribute("id", this.Id.ToString());
thisNode.AddAttribute("name", this.Name);
thisNode.AddAttribute("fullname", this.FullName);
if (this.MethodName != null)
thisNode.AddAttribute("methodname", this.MethodName);
if (this.ClassName != null)
thisNode.AddAttribute("classname", this.ClassName);
thisNode.AddAttribute("runstate", this.RunState.ToString());
if (Properties.Keys.Count > 0)
Properties.AddToXml(thisNode, recursive);
}
#endregion
#region Private Methods
private static ITestAction[] GetActionsForType(Type type)
{
var actions = new List<ITestAction>();
if (type != null && type != typeof(object))
{
actions.AddRange(GetActionsForType(type.GetTypeInfo().BaseType));
foreach (Type interfaceType in TypeHelper.GetDeclaredInterfaces(type))
actions.AddRange(interfaceType.GetTypeInfo().GetAttributes<ITestAction>(false));
actions.AddRange(type.GetTypeInfo().GetAttributes<ITestAction>(false));
}
return actions.ToArray();
}
#endregion
#region IXmlNodeBuilder Members
/// <summary>
/// Returns the XML representation of the test
/// </summary>
/// <param name="recursive">If true, include child tests recursively</param>
/// <returns></returns>
public TNode ToXml(bool recursive)
{
return AddToXml(new TNode("dummy"), recursive);
}
/// <summary>
/// Returns an XmlNode representing the current result after
/// adding it as a child of the supplied parent node.
/// </summary>
/// <param name="parentNode">The parent node.</param>
/// <param name="recursive">If true, descendant results are included</param>
/// <returns></returns>
public abstract TNode AddToXml(TNode parentNode, bool recursive);
#endregion
#region IComparable Members
/// <summary>
/// Compares this test to another test for sorting purposes
/// </summary>
/// <param name="obj">The other test</param>
/// <returns>Value of -1, 0 or +1 depending on whether the current test is less than, equal to or greater than the other test</returns>
public int CompareTo(object obj)
{
Test other = obj as Test;
if (other == null)
return -1;
return this.FullName.CompareTo(other.FullName);
}
#endregion
}
}
| |
using Microsoft.Azure.Commands.Compute.Common;
using Microsoft.Azure.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC;
using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC.Publish;
using Microsoft.WindowsAzure.Storage.Auth;
using System;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Extension.DSC
{
/// <summary>
/// Uploads a Desired State Configuration script to Azure blob storage, which
/// later can be applied to Azure Virtual Machines using the
/// Set-AzureRmVMDscExtension cmdlet.
/// </summary>
[Cmdlet(
VerbsData.Publish,
ProfileNouns.VirtualMachineDscConfiguration,
SupportsShouldProcess = true,
DefaultParameterSetName = UploadArchiveParameterSetName),
OutputType(
typeof(String))]
public class PublishAzureVMDscConfigurationCommand : DscExtensionPublishCmdletCommonBase
{
private const string CreateArchiveParameterSetName = "CreateArchive";
private const string UploadArchiveParameterSetName = "UploadArchive";
[Parameter(
Mandatory = true,
Position = 2,
ParameterSetName = UploadArchiveParameterSetName,
ValueFromPipelineByPropertyName = true,
HelpMessage = "The name of the resource group that contains the storage account.")]
[ValidateNotNullOrEmpty]
public string ResourceGroupName { get; set; }
/// <summary>
/// Path to a file containing one or more configurations; the file can be a
/// PowerShell script (*.ps1) or MOF interface (*.mof).
/// </summary>
[Parameter(
Mandatory = true,
Position = 1,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a file containing one or more configurations")]
[ValidateNotNullOrEmpty]
public string ConfigurationPath { get; set; }
/// <summary>
/// Name of the Azure Storage Container the configuration is uploaded to.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
Position = 4,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "Name of the Azure Storage Container the configuration is uploaded to")]
[ValidateNotNullOrEmpty]
public string ContainerName { get; set; }
/// <summary>
/// The Azure Storage Account name used to upload the configuration script to the container specified by ContainerName.
/// </summary>
[Parameter(
Mandatory = true,
Position = 3,
ValueFromPipelineByPropertyName = true,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "The Azure Storage Account name used to upload the configuration script to the container " +
"specified by ContainerName ")]
[ValidateNotNullOrEmpty]
public String StorageAccountName { get; set; }
/// <summary>
/// Path to a local ZIP file to write the configuration archive to.
/// When using this parameter, Publish-AzureRmVMDscConfiguration creates a
/// local ZIP archive instead of uploading it to blob storage..
/// </summary>
[Alias("ConfigurationArchivePath")]
[Parameter(
Position = 2,
ValueFromPipelineByPropertyName = true,
ParameterSetName = CreateArchiveParameterSetName,
HelpMessage = "Path to a local ZIP file to write the configuration archive to.")]
[ValidateNotNullOrEmpty]
public string OutputArchivePath { get; set; }
/// <summary>
/// Suffix for the storage end point, e.g. core.windows.net
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
ParameterSetName = UploadArchiveParameterSetName,
HelpMessage = "Suffix for the storage end point, e.g. core.windows.net")]
[ValidateNotNullOrEmpty]
public string StorageEndpointSuffix { get; set; }
/// <summary>
/// By default Publish-AzureRmVMDscConfiguration will not overwrite any existing blobs.
/// Use -Force to overwrite them.
/// </summary>
[Parameter(HelpMessage = "By default Publish-AzureRmVMDscConfiguration will not overwrite any existing blobs")]
public SwitchParameter Force { get; set; }
/// <summary>
/// Excludes DSC resource dependencies from the configuration archive
/// </summary>
[Parameter(HelpMessage = "Excludes DSC resource dependencies from the configuration archive")]
public SwitchParameter SkipDependencyDetection { get; set; }
/// <summary>
///Path to a .psd1 file that specifies the data for the Configuration. This
/// file must contain a hashtable with the items described in
/// http://technet.microsoft.com/en-us/library/dn249925.aspx.
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration. This is added to the configuration " +
"archive and then passed to the configuration function. It gets overwritten by the configuration data path " +
"provided through the Set-AzureRmVMDscExtension cmdlet")]
[ValidateNotNullOrEmpty]
public string ConfigurationDataPath { get; set; }
/// <summary>
/// Path to a file or a directory to include in the configuration archive
/// </summary>
[Parameter(
ValueFromPipelineByPropertyName = true,
HelpMessage = "Path to a file or a directory to include in the configuration archive. It gets downloaded to the " +
"VM along with the configuration")]
[ValidateNotNullOrEmpty]
public String[] AdditionalPath { get; set; }
//Private Variables
/// <summary>
/// Credentials used to access Azure Storage
/// </summary>
private StorageCredentials _storageCredentials;
protected override void ProcessRecord()
{
base.ProcessRecord();
try
{
ValidatePsVersion();
//validate cmdlet params
ConfigurationPath = GetUnresolvedProviderPathFromPSPath(ConfigurationPath);
ValidateConfigurationPath(ConfigurationPath, ParameterSetName);
if (ConfigurationDataPath != null)
{
ConfigurationDataPath = GetUnresolvedProviderPathFromPSPath(ConfigurationDataPath);
ValidateConfigurationDataPath(ConfigurationDataPath);
}
if (AdditionalPath != null && AdditionalPath.Length > 0)
{
for (var count = 0; count < AdditionalPath.Length; count++)
{
AdditionalPath[count] = GetUnresolvedProviderPathFromPSPath(AdditionalPath[count]);
}
}
switch (ParameterSetName)
{
case CreateArchiveParameterSetName:
OutputArchivePath = GetUnresolvedProviderPathFromPSPath(OutputArchivePath);
break;
case UploadArchiveParameterSetName:
_storageCredentials = this.GetStorageCredentials(ResourceGroupName,StorageAccountName);
if (ContainerName == null)
{
ContainerName = DscExtensionCmdletConstants.DefaultContainerName;
}
if (StorageEndpointSuffix == null)
{
StorageEndpointSuffix =
DefaultProfile.Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix);
}
break;
}
PublishConfiguration(
ConfigurationPath,
ConfigurationDataPath,
AdditionalPath,
OutputArchivePath,
StorageEndpointSuffix,
ContainerName,
ParameterSetName,
Force.IsPresent,
SkipDependencyDetection.IsPresent,
_storageCredentials);
}
finally
{
DeleteTemporaryFiles();
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="WebServiceHandler.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web.Services.Protocols {
using System.Diagnostics;
using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;
using System.Collections;
using System.Web;
using System.Web.SessionState;
using System.Web.Services.Interop;
using System.Configuration;
using Microsoft.Win32;
using System.Threading;
using System.Text;
using System.Web.UI;
using System.Web.Util;
using System.Web.UI.WebControls;
using System.ComponentModel; // for CompModSwitches
using System.EnterpriseServices;
using System.Runtime.Remoting.Messaging;
using System.Web.Services.Diagnostics;
internal class WebServiceHandler {
ServerProtocol protocol;
Exception exception;
AsyncCallback asyncCallback;
ManualResetEvent asyncBeginComplete;
int asyncCallbackCalls;
bool wroteException;
object[] parameters = null;
internal WebServiceHandler(ServerProtocol protocol) {
this.protocol = protocol;
}
// Flush the trace file after each request so that the trace output makes it to the disk.
static void TraceFlush() {
Debug.Flush();
}
void PrepareContext() {
this.exception = null;
this.wroteException = false;
this.asyncCallback = null;
this.asyncBeginComplete = new ManualResetEvent(false);
this.asyncCallbackCalls = 0;
if (protocol.IsOneWay)
return;
HttpContext context = protocol.Context;
if (context == null) return; // context is null in non-network case
// we want the default to be no caching on the client
int cacheDuration = protocol.MethodAttribute.CacheDuration;
if (cacheDuration > 0) {
context.Response.Cache.SetCacheability(HttpCacheability.Server);
context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(cacheDuration));
context.Response.Cache.SetSlidingExpiration(false);
// with soap 1.2 the action is a param in the content-type
context.Response.Cache.VaryByHeaders["Content-type"] = true;
context.Response.Cache.VaryByHeaders["SOAPAction"] = true;
context.Response.Cache.VaryByParams["*"] = true;
}
else {
context.Response.Cache.SetNoServerCaching();
context.Response.Cache.SetMaxAge(TimeSpan.Zero);
}
context.Response.BufferOutput = protocol.MethodAttribute.BufferResponse;
context.Response.ContentType = null;
}
void WriteException(Exception e) {
if (this.wroteException) return;
if (CompModSwitches.Remote.TraceVerbose) Debug.WriteLine("Server Exception: " + e.ToString());
if (e is TargetInvocationException) {
if (CompModSwitches.Remote.TraceVerbose) Debug.WriteLine("TargetInvocationException caught.");
e = e.InnerException;
}
this.wroteException = protocol.WriteException(e, protocol.Response.OutputStream);
if (!this.wroteException)
throw e;
}
void Invoke() {
PrepareContext();
protocol.CreateServerInstance();
string stringBuffer;
RemoteDebugger debugger = null;
if (!protocol.IsOneWay && RemoteDebugger.IsServerCallInEnabled(protocol, out stringBuffer)) {
debugger = new RemoteDebugger();
debugger.NotifyServerCallEnter(protocol, stringBuffer);
}
try {
TraceMethod caller = Tracing.On ? new TraceMethod(this, "Invoke") : null;
TraceMethod userMethod = Tracing.On ? new TraceMethod(protocol.Target, protocol.MethodInfo.Name, this.parameters) : null;
if (Tracing.On) Tracing.Enter(protocol.MethodInfo.ToString(), caller, userMethod);
object[] returnValues = protocol.MethodInfo.Invoke(protocol.Target, this.parameters);
if (Tracing.On) Tracing.Exit(protocol.MethodInfo.ToString(), caller);
WriteReturns(returnValues);
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "Invoke", e);
if (!protocol.IsOneWay) {
WriteException(e);
throw;
}
}
finally {
protocol.DisposeServerInstance();
if (debugger != null)
debugger.NotifyServerCallExit(protocol.Response);
}
}
// By keeping this in a separate method we avoid jitting system.enterpriseservices.dll in cases
// where transactions are not used.
void InvokeTransacted() {
Transactions.InvokeTransacted(new TransactedCallback(this.Invoke), protocol.MethodAttribute.TransactionOption);
}
void ThrowInitException() {
HandleOneWayException(new Exception(Res.GetString(Res.WebConfigExtensionError), protocol.OnewayInitException), "ThrowInitException");
}
void HandleOneWayException(Exception e, string method) {
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, string.IsNullOrEmpty(method) ? "HandleOneWayException" : method, e);
// exceptions for one-way calls are dropped because the response is already written
}
protected void CoreProcessRequest() {
try {
bool transacted = protocol.MethodAttribute.TransactionEnabled;
if (protocol.IsOneWay) {
WorkItemCallback callback = null;
TraceMethod callbackMethod = null;
if (protocol.OnewayInitException != null) {
callback = new WorkItemCallback(this.ThrowInitException);
callbackMethod = Tracing.On ? new TraceMethod(this, "ThrowInitException") : null;
}
else {
parameters = protocol.ReadParameters();
callback = transacted ? new WorkItemCallback(this.OneWayInvokeTransacted) : new WorkItemCallback(this.OneWayInvoke);
callbackMethod = Tracing.On ? transacted ? new TraceMethod(this, "OneWayInvokeTransacted") : new TraceMethod(this, "OneWayInvoke") : null;
}
if (Tracing.On) Tracing.Information(Res.TracePostWorkItemIn, callbackMethod);
WorkItem.Post(callback);
if (Tracing.On) Tracing.Information(Res.TracePostWorkItemOut, callbackMethod);
protocol.WriteOneWayResponse();
}
else if (transacted) {
parameters = protocol.ReadParameters();
InvokeTransacted();
}
else {
parameters = protocol.ReadParameters();
Invoke();
}
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "CoreProcessRequest", e);
if (!protocol.IsOneWay)
WriteException(e);
}
TraceFlush();
}
private HttpContext SwitchContext(HttpContext context) {
PartialTrustHelpers.FailIfInPartialTrustOutsideAspNet();
HttpContext oldContext = HttpContext.Current;
HttpContext.Current = context;
return oldContext;
}
private void OneWayInvoke() {
HttpContext oldContext = null;
if (protocol.Context != null)
oldContext = SwitchContext(protocol.Context);
try {
Invoke();
}
catch (Exception e) {
HandleOneWayException(e, "OneWayInvoke");
}
finally {
if (oldContext != null)
SwitchContext(oldContext);
}
}
private void OneWayInvokeTransacted() {
HttpContext oldContext = null;
if (protocol.Context != null)
oldContext = SwitchContext(protocol.Context);
try {
InvokeTransacted();
}
catch (Exception e) {
HandleOneWayException(e, "OneWayInvokeTransacted");
}
finally {
if (oldContext != null)
SwitchContext(oldContext);
}
}
private void Callback(IAsyncResult result) {
if (!result.CompletedSynchronously)
this.asyncBeginComplete.WaitOne();
DoCallback(result);
}
private void DoCallback(IAsyncResult result) {
if (this.asyncCallback != null) {
if (System.Threading.Interlocked.Increment(ref this.asyncCallbackCalls) == 1) {
this.asyncCallback(result);
}
}
}
protected IAsyncResult BeginCoreProcessRequest(AsyncCallback callback, object asyncState) {
IAsyncResult asyncResult;
if (protocol.MethodAttribute.TransactionEnabled)
throw new InvalidOperationException(Res.GetString(Res.WebAsyncTransaction));
parameters = protocol.ReadParameters();
if (protocol.IsOneWay) {
TraceMethod callbackMethod = Tracing.On ? new TraceMethod(this, "OneWayAsyncInvoke") : null;
if (Tracing.On) Tracing.Information(Res.TracePostWorkItemIn, callbackMethod);
WorkItem.Post(new WorkItemCallback(this.OneWayAsyncInvoke));
if (Tracing.On) Tracing.Information(Res.TracePostWorkItemOut, callbackMethod);
asyncResult = new CompletedAsyncResult(asyncState, true);
if (callback != null)
callback(asyncResult);
}
else
asyncResult = BeginInvoke(callback, asyncState);
return asyncResult;
}
private void OneWayAsyncInvoke() {
if (protocol.OnewayInitException != null)
HandleOneWayException(new Exception(Res.GetString(Res.WebConfigExtensionError), protocol.OnewayInitException), "OneWayAsyncInvoke");
else {
HttpContext oldContext = null;
if (protocol.Context != null)
oldContext = SwitchContext(protocol.Context);
try {
BeginInvoke(new AsyncCallback(this.OneWayCallback), null);
}
catch (Exception e) {
HandleOneWayException(e, "OneWayAsyncInvoke");
}
finally {
if (oldContext != null)
SwitchContext(oldContext);
}
}
}
private IAsyncResult BeginInvoke(AsyncCallback callback, object asyncState) {
IAsyncResult asyncResult;
try {
PrepareContext();
protocol.CreateServerInstance();
this.asyncCallback = callback;
TraceMethod caller = Tracing.On ? new TraceMethod(this, "BeginInvoke") : null;
TraceMethod userMethod = Tracing.On ? new TraceMethod(protocol.Target, protocol.MethodInfo.Name, this.parameters) : null;
if (Tracing.On) Tracing.Enter(protocol.MethodInfo.ToString(), caller, userMethod);
asyncResult = protocol.MethodInfo.BeginInvoke(protocol.Target, this.parameters, new AsyncCallback(this.Callback), asyncState);
if (Tracing.On) Tracing.Enter(protocol.MethodInfo.ToString(), caller);
if (asyncResult == null) throw new InvalidOperationException(Res.GetString(Res.WebNullAsyncResultInBegin));
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "BeginInvoke", e);
// save off the exception and throw it in EndCoreProcessRequest
exception = e;
asyncResult = new CompletedAsyncResult(asyncState, true);
this.asyncCallback = callback;
this.DoCallback(asyncResult);
}
this.asyncBeginComplete.Set();
TraceFlush();
return asyncResult;
}
private void OneWayCallback(IAsyncResult asyncResult) {
EndInvoke(asyncResult);
}
protected void EndCoreProcessRequest(IAsyncResult asyncResult) {
if (asyncResult == null) return;
if (protocol.IsOneWay)
protocol.WriteOneWayResponse();
else
EndInvoke(asyncResult);
}
private void EndInvoke(IAsyncResult asyncResult) {
try {
if (exception != null)
throw (exception);
object[] returnValues = protocol.MethodInfo.EndInvoke(protocol.Target, asyncResult);
WriteReturns(returnValues);
}
catch (Exception e) {
if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
throw;
}
if (Tracing.On) Tracing.ExceptionCatch(TraceEventType.Error, this, "EndInvoke", e);
if (!protocol.IsOneWay)
WriteException(e);
}
finally {
protocol.DisposeServerInstance();
}
TraceFlush();
}
void WriteReturns(object[] returnValues) {
if (protocol.IsOneWay) return;
// By default ASP.NET will fully buffer the response. If BufferResponse=false
// then we still want to do partial buffering since each write is a named
// pipe call over to inetinfo.
bool fullyBuffered = protocol.MethodAttribute.BufferResponse;
Stream outputStream = protocol.Response.OutputStream;
if (!fullyBuffered) {
outputStream = new BufferedResponseStream(outputStream, 16 * 1024);
//#if DEBUG
((BufferedResponseStream)outputStream).FlushEnabled = false;
//#endif
}
protocol.WriteReturns(returnValues, outputStream);
// This will flush the buffered stream and the underlying stream. Its important
// that it flushes the Response.OutputStream because we always want BufferResponse=false
// to mean we are writing back a chunked response. This gives a consistent
// behavior to the client, independent of the size of the partial buffering.
if (!fullyBuffered) {
//#if DEBUG
((BufferedResponseStream)outputStream).FlushEnabled = true;
//#endif
outputStream.Flush();
}
}
}
internal class SyncSessionlessHandler : WebServiceHandler, IHttpHandler {
internal SyncSessionlessHandler(ServerProtocol protocol) : base(protocol) { }
public bool IsReusable {
get { return false; }
}
public void ProcessRequest(HttpContext context) {
TraceMethod method = Tracing.On ? new TraceMethod(this, "ProcessRequest") : null;
if (Tracing.On) Tracing.Enter("IHttpHandler.ProcessRequest", method, Tracing.Details(context.Request));
CoreProcessRequest();
if (Tracing.On) Tracing.Exit("IHttpHandler.ProcessRequest", method);
}
}
internal class SyncSessionHandler : SyncSessionlessHandler, IRequiresSessionState {
internal SyncSessionHandler(ServerProtocol protocol) : base(protocol) { }
}
internal class AsyncSessionlessHandler : SyncSessionlessHandler, IHttpAsyncHandler {
internal AsyncSessionlessHandler(ServerProtocol protocol) : base(protocol) { }
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback callback, object asyncState) {
TraceMethod method = Tracing.On ? new TraceMethod(this, "BeginProcessRequest") : null;
if (Tracing.On) Tracing.Enter("IHttpAsyncHandler.BeginProcessRequest", method, Tracing.Details(context.Request));
IAsyncResult result = BeginCoreProcessRequest(callback, asyncState);
if (Tracing.On) Tracing.Exit("IHttpAsyncHandler.BeginProcessRequest", method);
return result;
}
public void EndProcessRequest(IAsyncResult asyncResult) {
TraceMethod method = Tracing.On ? new TraceMethod(this, "EndProcessRequest") : null;
if (Tracing.On) Tracing.Enter("IHttpAsyncHandler.EndProcessRequest", method);
EndCoreProcessRequest(asyncResult);
if (Tracing.On) Tracing.Exit("IHttpAsyncHandler.EndProcessRequest", method);
}
}
internal class AsyncSessionHandler : AsyncSessionlessHandler, IRequiresSessionState {
internal AsyncSessionHandler(ServerProtocol protocol) : base(protocol) { }
}
class CompletedAsyncResult : IAsyncResult {
object asyncState;
bool completedSynchronously;
internal CompletedAsyncResult(object asyncState, bool completedSynchronously) {
this.asyncState = asyncState;
this.completedSynchronously = completedSynchronously;
}
public object AsyncState { get { return asyncState; } }
public bool CompletedSynchronously { get { return completedSynchronously; } }
public bool IsCompleted { get { return true; } }
public WaitHandle AsyncWaitHandle { get { return null; } }
}
}
| |
// Copyright 2022 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.AIPlatform.V1.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedIndexEndpointServiceClientTest
{
[xunit::FactAttribute]
public void GetIndexEndpointRequestObject()
{
moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexEndpointRequest request = new GetIndexEndpointRequest
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
};
IndexEndpoint expectedResponse = new IndexEndpoint
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedIndexes =
{
new DeployedIndex(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Network = "networkd22ce091",
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.GetIndexEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null);
IndexEndpoint response = client.GetIndexEndpoint(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIndexEndpointRequestObjectAsync()
{
moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexEndpointRequest request = new GetIndexEndpointRequest
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
};
IndexEndpoint expectedResponse = new IndexEndpoint
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedIndexes =
{
new DeployedIndex(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Network = "networkd22ce091",
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.GetIndexEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IndexEndpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null);
IndexEndpoint responseCallSettings = await client.GetIndexEndpointAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
IndexEndpoint responseCancellationToken = await client.GetIndexEndpointAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIndexEndpoint()
{
moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexEndpointRequest request = new GetIndexEndpointRequest
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
};
IndexEndpoint expectedResponse = new IndexEndpoint
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedIndexes =
{
new DeployedIndex(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Network = "networkd22ce091",
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.GetIndexEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null);
IndexEndpoint response = client.GetIndexEndpoint(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIndexEndpointAsync()
{
moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexEndpointRequest request = new GetIndexEndpointRequest
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
};
IndexEndpoint expectedResponse = new IndexEndpoint
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedIndexes =
{
new DeployedIndex(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Network = "networkd22ce091",
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.GetIndexEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IndexEndpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null);
IndexEndpoint responseCallSettings = await client.GetIndexEndpointAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
IndexEndpoint responseCancellationToken = await client.GetIndexEndpointAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetIndexEndpointResourceNames()
{
moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexEndpointRequest request = new GetIndexEndpointRequest
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
};
IndexEndpoint expectedResponse = new IndexEndpoint
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedIndexes =
{
new DeployedIndex(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Network = "networkd22ce091",
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.GetIndexEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null);
IndexEndpoint response = client.GetIndexEndpoint(request.IndexEndpointName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetIndexEndpointResourceNamesAsync()
{
moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetIndexEndpointRequest request = new GetIndexEndpointRequest
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
};
IndexEndpoint expectedResponse = new IndexEndpoint
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedIndexes =
{
new DeployedIndex(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Network = "networkd22ce091",
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.GetIndexEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IndexEndpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null);
IndexEndpoint responseCallSettings = await client.GetIndexEndpointAsync(request.IndexEndpointName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
IndexEndpoint responseCancellationToken = await client.GetIndexEndpointAsync(request.IndexEndpointName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateIndexEndpointRequestObject()
{
moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateIndexEndpointRequest request = new UpdateIndexEndpointRequest
{
IndexEndpoint = new IndexEndpoint(),
UpdateMask = new wkt::FieldMask(),
};
IndexEndpoint expectedResponse = new IndexEndpoint
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedIndexes =
{
new DeployedIndex(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Network = "networkd22ce091",
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.UpdateIndexEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null);
IndexEndpoint response = client.UpdateIndexEndpoint(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateIndexEndpointRequestObjectAsync()
{
moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateIndexEndpointRequest request = new UpdateIndexEndpointRequest
{
IndexEndpoint = new IndexEndpoint(),
UpdateMask = new wkt::FieldMask(),
};
IndexEndpoint expectedResponse = new IndexEndpoint
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedIndexes =
{
new DeployedIndex(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Network = "networkd22ce091",
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.UpdateIndexEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IndexEndpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null);
IndexEndpoint responseCallSettings = await client.UpdateIndexEndpointAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
IndexEndpoint responseCancellationToken = await client.UpdateIndexEndpointAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void UpdateIndexEndpoint()
{
moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateIndexEndpointRequest request = new UpdateIndexEndpointRequest
{
IndexEndpoint = new IndexEndpoint(),
UpdateMask = new wkt::FieldMask(),
};
IndexEndpoint expectedResponse = new IndexEndpoint
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedIndexes =
{
new DeployedIndex(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Network = "networkd22ce091",
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.UpdateIndexEndpoint(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null);
IndexEndpoint response = client.UpdateIndexEndpoint(request.IndexEndpoint, request.UpdateMask);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task UpdateIndexEndpointAsync()
{
moq::Mock<IndexEndpointService.IndexEndpointServiceClient> mockGrpcClient = new moq::Mock<IndexEndpointService.IndexEndpointServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
UpdateIndexEndpointRequest request = new UpdateIndexEndpointRequest
{
IndexEndpoint = new IndexEndpoint(),
UpdateMask = new wkt::FieldMask(),
};
IndexEndpoint expectedResponse = new IndexEndpoint
{
IndexEndpointName = IndexEndpointName.FromProjectLocationIndexEndpoint("[PROJECT]", "[LOCATION]", "[INDEX_ENDPOINT]"),
DisplayName = "display_name137f65c2",
Description = "description2cf9da67",
DeployedIndexes =
{
new DeployedIndex(),
},
Etag = "etage8ad7218",
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Network = "networkd22ce091",
EnablePrivateServiceConnect = false,
};
mockGrpcClient.Setup(x => x.UpdateIndexEndpointAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<IndexEndpoint>(stt::Task.FromResult(expectedResponse), null, null, null, null));
IndexEndpointServiceClient client = new IndexEndpointServiceClientImpl(mockGrpcClient.Object, null);
IndexEndpoint responseCallSettings = await client.UpdateIndexEndpointAsync(request.IndexEndpoint, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
IndexEndpoint responseCancellationToken = await client.UpdateIndexEndpointAsync(request.IndexEndpoint, request.UpdateMask, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// 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.
namespace Castle.DynamicProxy.Generators
{
using System;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
#if !SILVERLIGHT
using System.Xml.Serialization;
#endif
using Castle.Core.Internal;
using Castle.DynamicProxy.Contributors;
using Castle.DynamicProxy.Generators.Emitters;
using Castle.DynamicProxy.Generators.Emitters.SimpleAST;
using Castle.DynamicProxy.Tokens;
using System.Collections.Generic;
public class MethodWithInvocationGenerator : MethodGenerator
{
private readonly IInvocationCreationContributor contributor;
private readonly GetTargetExpressionDelegate getTargetExpression;
private readonly Reference interceptors;
private readonly Type invocation;
public MethodWithInvocationGenerator(MetaMethod method, Reference interceptors, Type invocation,
GetTargetExpressionDelegate getTargetExpression,
OverrideMethodDelegate createMethod, IInvocationCreationContributor contributor)
: base(method, createMethod)
{
this.invocation = invocation;
this.getTargetExpression = getTargetExpression;
this.interceptors = interceptors;
this.contributor = contributor;
}
protected FieldReference BuildMethodInterceptorsField(ClassEmitter @class, MethodInfo method, INamingScope namingScope)
{
var methodInterceptors = @class.CreateField(
namingScope.GetUniqueName(string.Format("interceptors_{0}", method.Name)),
typeof(IInterceptor[]),
false);
#if !SILVERLIGHT
@class.DefineCustomAttributeFor<XmlIgnoreAttribute>(methodInterceptors);
#endif
return methodInterceptors;
}
protected override MethodEmitter BuildProxiedMethodBody(MethodEmitter emitter, ClassEmitter @class,
ProxyGenerationOptions options, INamingScope namingScope)
{
var invocationType = invocation;
Trace.Assert(MethodToOverride.IsGenericMethod == invocationType.IsGenericTypeDefinition());
var genericArguments = TypeExtender.EmptyTypes;
var constructor = invocation.GetConstructors()[0];
Expression proxiedMethodTokenExpression;
if (MethodToOverride.IsGenericMethod)
{
// bind generic method arguments to invocation's type arguments
genericArguments = emitter.MethodBuilder.GetGenericArguments();
invocationType = invocationType.MakeGenericType(genericArguments);
constructor = TypeBuilder.GetConstructor(invocationType, constructor);
// Not in the cache: generic method
proxiedMethodTokenExpression = new MethodTokenExpression(MethodToOverride.MakeGenericMethod(genericArguments));
}
else
{
var proxiedMethodToken = @class.CreateStaticField(namingScope.GetUniqueName("token_" + MethodToOverride.Name),
typeof(MethodInfo));
@class.ClassConstructor.CodeBuilder.AddStatement(new AssignStatement(proxiedMethodToken,
new MethodTokenExpression(MethodToOverride)));
proxiedMethodTokenExpression = proxiedMethodToken.ToExpression();
}
var dereferencedArguments = IndirectReference.WrapIfByRef(emitter.Arguments);
var hasByRefArguments = HasByRefArguments(emitter.Arguments);
var arguments = GetCtorArguments(@class, namingScope, proxiedMethodTokenExpression,
dereferencedArguments);
var ctorArguments = ModifyArguments(@class, arguments);
var invocationLocal = emitter.CodeBuilder.DeclareLocal(invocationType);
emitter.CodeBuilder.AddStatement(new AssignStatement(invocationLocal,
new NewInstanceExpression(constructor, ctorArguments)));
if (MethodToOverride.ContainsGenericParameters)
{
EmitLoadGenricMethodArguments(emitter, MethodToOverride.MakeGenericMethod(genericArguments), invocationLocal);
}
if (hasByRefArguments)
{
emitter.CodeBuilder.AddStatement(new TryStatement());
}
var proceed = new ExpressionStatement(new MethodInvocationExpression(invocationLocal, InvocationMethods.Proceed));
emitter.CodeBuilder.AddStatement(proceed);
if (hasByRefArguments)
{
emitter.CodeBuilder.AddStatement(new FinallyStatement());
}
GeneratorUtil.CopyOutAndRefParameters(dereferencedArguments, invocationLocal, MethodToOverride, emitter);
if (hasByRefArguments)
{
emitter.CodeBuilder.AddStatement(new EndExceptionBlockStatement());
}
if (MethodToOverride.ReturnType != typeof(void))
{
// Emit code to return with cast from ReturnValue
// @mbrit - 2012-05-31 - see the note associated with the GetReturnValueForWinRt declaration
// for more information on this...
var useWinRtGenericHandler = false;
#if NETFX_CORE
if (emitter.ReturnType == typeof(int) || emitter.ReturnType == typeof(bool))
useWinRtGenericHandler = true;
#endif
if(!(useWinRtGenericHandler))
{
var getRetVal = new MethodInvocationExpression(invocationLocal, InvocationMethods.GetReturnValue);
emitter.CodeBuilder.AddStatement(new ReturnStatement(new ConvertExpression(emitter.ReturnType, getRetVal)));
}
else
{
#if NETFX_CORE
var grvArgs = new Type[] { emitter.ReturnType };
var grvCall = InvocationMethods.GetReturnValueForWinRt.MakeGenericMethod(grvArgs);
var getRetVal = new MethodInvocationExpression(invocationLocal, grvCall);
emitter.CodeBuilder.AddStatement(new ReturnStatement(getRetVal));
#endif
}
}
else
{
emitter.CodeBuilder.AddStatement(new ReturnStatement());
}
return emitter;
}
private void EmitLoadGenricMethodArguments(MethodEmitter methodEmitter, MethodInfo method, Reference invocationLocal)
{
var genericParameters = new List<Type>(method.GetGenericArguments()).FindAll(t => t.IsGenericParameter);
var genericParamsArrayLocal = methodEmitter.CodeBuilder.DeclareLocal(typeof(Type[]));
methodEmitter.CodeBuilder.AddStatement(
new AssignStatement(genericParamsArrayLocal, new NewArrayExpression(genericParameters.Count, typeof(Type))));
for (var i = 0; i < genericParameters.Count; ++i)
{
methodEmitter.CodeBuilder.AddStatement(
new AssignArrayStatement(genericParamsArrayLocal, i, new TypeTokenExpression(genericParameters[i])));
}
methodEmitter.CodeBuilder.AddStatement(new ExpressionStatement(
new MethodInvocationExpression(invocationLocal,
InvocationMethods.SetGenericMethodArguments,
new ReferenceExpression(
genericParamsArrayLocal))));
}
private Expression[] GetCtorArguments(ClassEmitter @class, INamingScope namingScope,
Expression proxiedMethodTokenExpression, TypeReference[] dereferencedArguments)
{
var selector = @class.GetField("__selector");
if (selector != null)
{
return new[]
{
getTargetExpression(@class, MethodToOverride),
SelfReference.Self.ToExpression(),
interceptors.ToExpression(),
proxiedMethodTokenExpression,
new ReferencesToObjectArrayExpression(dereferencedArguments),
selector.ToExpression(),
new AddressOfReferenceExpression(BuildMethodInterceptorsField(@class, MethodToOverride, namingScope))
};
}
return new[]
{
getTargetExpression(@class, MethodToOverride),
SelfReference.Self.ToExpression(),
interceptors.ToExpression(),
proxiedMethodTokenExpression,
new ReferencesToObjectArrayExpression(dereferencedArguments)
};
}
private Expression[] ModifyArguments(ClassEmitter @class, Expression[] arguments)
{
if (contributor == null)
{
return arguments;
}
return contributor.GetConstructorInvocationArguments(arguments, @class);
}
private bool HasByRefArguments(ArgumentReference[] arguments)
{
for (int i = 0; i < arguments.Length; i++ )
{
if (arguments[i].Type.IsByRef)
{
return true;
}
}
return false;
}
}
}
| |
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Diagnostics;
using System.Threading;
using Mono.Collections.Generic;
namespace Mono.Cecil {
public enum SecurityAction : ushort {
Request = 1,
Demand = 2,
Assert = 3,
Deny = 4,
PermitOnly = 5,
LinkDemand = 6,
InheritDemand = 7,
RequestMinimum = 8,
RequestOptional = 9,
RequestRefuse = 10,
PreJitGrant = 11,
PreJitDeny = 12,
NonCasDemand = 13,
NonCasLinkDemand = 14,
NonCasInheritance = 15
}
public interface ISecurityDeclarationProvider : IMetadataTokenProvider {
bool HasSecurityDeclarations { get; }
Collection<SecurityDeclaration> SecurityDeclarations { get; }
}
[DebuggerDisplay ("{AttributeType}")]
public sealed class SecurityAttribute : ICustomAttribute {
TypeReference attribute_type;
internal Collection<CustomAttributeNamedArgument> fields;
internal Collection<CustomAttributeNamedArgument> properties;
public TypeReference AttributeType {
get { return attribute_type; }
set { attribute_type = value; }
}
public bool HasFields {
get { return !fields.IsNullOrEmpty (); }
}
public Collection<CustomAttributeNamedArgument> Fields {
get {
if (fields == null)
Interlocked.CompareExchange (ref fields, new Collection<CustomAttributeNamedArgument> (), null);
return fields;
}
}
public bool HasProperties {
get { return !properties.IsNullOrEmpty (); }
}
public Collection<CustomAttributeNamedArgument> Properties {
get {
if (properties == null)
Interlocked.CompareExchange (ref properties, new Collection<CustomAttributeNamedArgument> (), null);
return properties;
}
}
public SecurityAttribute (TypeReference attributeType)
{
this.attribute_type = attributeType;
}
bool ICustomAttribute.HasConstructorArguments {
get { return false; }
}
Collection<CustomAttributeArgument> ICustomAttribute.ConstructorArguments {
get { throw new NotSupportedException (); }
}
}
public sealed class SecurityDeclaration {
readonly internal uint signature;
byte [] blob;
readonly ModuleDefinition module;
internal bool resolved;
SecurityAction action;
internal Collection<SecurityAttribute> security_attributes;
public SecurityAction Action {
get { return action; }
set { action = value; }
}
public bool HasSecurityAttributes {
get {
Resolve ();
return !security_attributes.IsNullOrEmpty ();
}
}
public Collection<SecurityAttribute> SecurityAttributes {
get {
Resolve ();
if (security_attributes == null)
Interlocked.CompareExchange (ref security_attributes, new Collection<SecurityAttribute> (), null);
return security_attributes;
}
}
internal bool HasImage {
get { return module != null && module.HasImage; }
}
internal SecurityDeclaration (SecurityAction action, uint signature, ModuleDefinition module)
{
this.action = action;
this.signature = signature;
this.module = module;
}
public SecurityDeclaration (SecurityAction action)
{
this.action = action;
this.resolved = true;
}
public SecurityDeclaration (SecurityAction action, byte [] blob)
{
this.action = action;
this.resolved = false;
this.blob = blob;
}
public byte [] GetBlob ()
{
if (blob != null)
return blob;
if (!HasImage || signature == 0)
throw new NotSupportedException ();
return module.Read (ref blob, this, (declaration, reader) => reader.ReadSecurityDeclarationBlob (declaration.signature));
}
void Resolve ()
{
if (resolved || !HasImage)
return;
lock (module.SyncRoot) {
if (resolved)
return;
module.Read (this, (declaration, reader) => reader.ReadSecurityDeclarationSignature (declaration));
resolved = true;
}
}
}
static partial class Mixin {
public static bool GetHasSecurityDeclarations (
this ISecurityDeclarationProvider self,
ModuleDefinition module)
{
return module.HasImage () && module.Read (self, (provider, reader) => reader.HasSecurityDeclarations (provider));
}
public static Collection<SecurityDeclaration> GetSecurityDeclarations (
this ISecurityDeclarationProvider self,
ref Collection<SecurityDeclaration> variable,
ModuleDefinition module)
{
if (module.HasImage)
return module.Read (ref variable, self, (provider, reader) => reader.ReadSecurityDeclarations (provider));
Interlocked.CompareExchange (ref variable, new Collection<SecurityDeclaration> (), null);
return variable;
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.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 Aurora-Sim 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;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Text;
using log4net;
using Nini.Config;
using Aurora.Simulation.Base;
using OpenSim.Services.Interfaces;
using Aurora.Framework;
using Aurora.Framework.Servers.HttpServer;
using Aurora.DataManager;
using Aurora.Framework;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using System.Collections.Specialized;
namespace OpenSim.Services
{
/// <summary>
/// Reference:
/// http://wiki.secondlife.com/wiki/Registration_API_Reference
/// http://wiki.secondlife.com/wiki/Registration_API
/// </summary>
public class RegAPIHandler : IService
{
public IHttpServer m_server = null;
public string Name
{
get { return GetType().Name; }
}
public void Initialize(IConfigSource config, IRegistryCore registry)
{
}
public void Start(IConfigSource config, IRegistryCore registry)
{
IConfig handlerConfig = config.Configs["Handlers"];
if (handlerConfig.GetString("RegApiHandler", "") != Name)
return;
m_server = registry.RequestModuleInterface<ISimulationBase>().GetHttpServer(handlerConfig.GetUInt("WireduxHandlerPort"));
//This handler allows sims to post CAPS for their sims on the CAPS server.
m_server.AddStreamHandler(new RegApiHTTPHandler(registry, m_server));
}
public void FinishedStartup()
{
}
}
public class RegApiHTTPHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected IRegistryCore m_registry;
protected IHttpServer m_server;
public const int RegApiAllowed = 512;
public const int RegApiAddToGroup = 1024;
public const int RegApiCheckName = 2048;
public const int RegApiCreateUser = 4096;
public const int RegApiGetErrorCodes = 8192;
public const int RegApiGetLastNames = 16384;
public Dictionary<int, string> m_lastNameRegistry = new Dictionary<int, string>();
public RegApiHTTPHandler(IRegistryCore reg, IHttpServer s) :
base("POST", "/get_reg_capabilities")
{
m_registry = reg;
m_server = s;
}
public override byte[] Handle(string path, Stream requestData,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
//m_log.DebugFormat("[XXX]: query String: {0}", body);
try
{
OSDMap map = (OSDMap)OSDParser.DeserializeLLSDXml(body);
//Make sure that the person who is calling can access the web service
if (map["submit"] == "Get Capabilities")
{
}
}
catch (Exception)
{
}
OSDMap resp = new OSDMap();
resp.Add("response", OSD.FromString("Failed"));
string xmlString = OSDParser.SerializeLLSDXmlString(resp);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
private byte[] ProcessLogin(OSDMap map)
{
bool Verified = false;
string FirstName = map["first_name"].AsString();
string LastName = map["last_name"].AsString();
string Password = map["password"].AsString();
ILoginService loginService = m_registry.RequestModuleInterface<ILoginService>();
Verified = loginService.VerifyClient(UUID.Zero, FirstName + " " + LastName, "UserAccount", Password, UUID.Zero);
OSDMap resp = new OSDMap();
if (Verified)
{
UserAccount account = m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccount(UUID.Zero, FirstName, LastName);
if (Verified)
{
AddCapsUrls(resp, account);
}
}
string xmlString = OSDParser.SerializeLLSDXmlString(resp);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(xmlString);
}
private void AddCapsUrls(OSDMap resp, UserAccount account)
{
//Check whether they can use the Api
if ((account.UserFlags & RegApiAllowed) == RegApiAllowed)
{
if ((account.UserFlags & RegApiAddToGroup) == RegApiAddToGroup)
resp["add_to_group"] = AddSpecificUrl("add_to_group");
if ((account.UserFlags & RegApiCheckName) == RegApiCheckName)
resp["check_name"] = AddSpecificUrl("check_name");
if ((account.UserFlags & RegApiCreateUser) == RegApiCreateUser)
resp["create_user"] = AddSpecificUrl("create_user");
if ((account.UserFlags & RegApiGetErrorCodes) == RegApiGetErrorCodes)
resp["get_error_codes"] = AddSpecificUrl("get_error_codes");
if ((account.UserFlags & RegApiGetLastNames) == RegApiGetLastNames)
resp["get_last_names"] = AddSpecificUrl("get_last_names");
}
}
/// <summary>
/// Creates a cap for the given type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
private string AddSpecificUrl(string type)
{
string capPath = "/cap/"+UUID.Random()+"/"+type;
m_server.AddHTTPHandler(capPath, delegate(Hashtable request)
{
Hashtable responsedata = new Hashtable();
responsedata["content_type"] = "text/html";
responsedata["keepalive"] = false;
OSD resp = new OSD();
try
{
OSDMap r = (OSDMap)OSDParser.DeserializeLLSDXml((string)request["requestbody"]);
if (type == "add_to_group")
resp = AddUserToGroup(r);
if (type == "check_name")
resp = CheckName(r);
if (type == "create_user")
resp = CreateUser(r);
if (type == "get_error_codes")
resp = GetErrorCode(r);
if (type == "get_last_names")
resp = GetLastNames(r);
}
catch
{
}
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = OSDParser.SerializeLLSDXmlString(resp);
return responsedata;
});
ICapsService capsService = m_registry.RequestModuleInterface<ICapsService>();
if (capsService != null)
{
capPath = capsService.HostUri + capPath;
return capPath;
}
return "";
}
private OSD AddUserToGroup(OSDMap map)
{
bool finished = false;
IGroupsServiceConnector groupsService = Aurora.DataManager.DataManager.RequestPlugin<IGroupsServiceConnector>();
if (groupsService != null)
{
string first = map["first"];
string last = map["last"];
string group_name = map["group_name"];
GroupRecord record = groupsService.GetGroupRecord(UUID.Zero, UUID.Zero, group_name);
if (record != null)
{
UserAccount user = m_registry.RequestModuleInterface<IUserAccountService>().GetUserAccount(UUID.Zero, first, last);
if (user != null)
{
groupsService.AddAgentToGroup(UUID.Zero, user.PrincipalID, record.GroupID, UUID.Zero);
finished = true;
}
}
}
return finished;
}
private OSD CheckName(OSDMap map)
{
string userName = map["username"];
int last_name_id = map["last_name_id"];
bool found = false;
if (m_lastNameRegistry.ContainsKey(last_name_id))
{
string lastName = m_lastNameRegistry[last_name_id];
IUserAccountService accountService = m_registry.RequestModuleInterface<IUserAccountService>();
UserAccount user = accountService.GetUserAccount(UUID.Zero, userName, lastName);
if (user != null)
found = true;
}
return found;
}
/// <summary>
/// Creates a user
/// TODO: Does not implement the restrict to estate option
/// </summary>
/// <param name="map"></param>
/// <returns></returns>
private OSD CreateUser(OSDMap map)
{
//Required params
string username = map["username"];
int last_name_id = map["last_name_id"];
string email = map["email"];
string password = map["password"];
string dob = map["dob"];
//Optional params
int limited_to_estate = map["limited_to_estate"];
string start_region_name = map["start_region_name"];
float start_local_x = map["start_local_x"];
float start_local_y = map["start_local_y"];
float start_local_z = map["start_local_z"];
float start_look_at_x = map["start_look_at_x"];
float start_look_at_y = map["start_look_at_y"];
float start_look_at_z = map["start_look_at_z"];
OSD resp = null;
if (username != "" && last_name_id != 0 && email != "" &&
password != "" && dob != "")
{
IUserAccountService accountService = m_registry.RequestModuleInterface<IUserAccountService>();
if (m_lastNameRegistry.ContainsKey(last_name_id))
{
string lastName = m_lastNameRegistry[last_name_id];
UserAccount user = accountService.GetUserAccount(UUID.Zero, username, lastName);
if (user == null)
{
//The pass is in plain text... so put it in and create the account
accountService.CreateUser(username + " " + lastName, password, email);
DateTime time = DateTime.ParseExact(dob, "YYYY-MM-DD", System.Globalization.CultureInfo.InvariantCulture);
user = accountService.GetUserAccount(UUID.Zero, username, lastName);
//Update the dob
user.Created = Util.ToUnixTime(time);
accountService.StoreUserAccount(user);
IAgentConnector agentConnector = Aurora.DataManager.DataManager.RequestPlugin<IAgentConnector>();
if (agentConnector != null)
{
agentConnector.CreateNewAgent(user.PrincipalID);
if (map.ContainsKey("limited_to_estate"))
{
IAgentInfo agentInfo = agentConnector.GetAgent(user.PrincipalID);
agentInfo.OtherAgentInformation["LimitedToEstate"] = limited_to_estate;
agentConnector.UpdateAgent(agentInfo);
}
}
m_log.Info("[RegApi]: Created new user " + user.Name);
try
{
if (start_region_name != "")
{
IAgentInfoService agentInfoService = m_registry.RequestModuleInterface<IAgentInfoService>();
if (agentInfoService != null)
{
agentInfoService.SetHomePosition(user.PrincipalID.ToString(),
m_registry.RequestModuleInterface<IGridService>().GetRegionByName
(UUID.Zero, start_region_name).RegionID,
new Vector3(start_local_x,
start_local_y,
start_local_z),
new Vector3(start_look_at_x,
start_look_at_y,
start_look_at_z));
}
}
}
catch
{
m_log.Warn("[RegApi]: Encountered an error when setting the home position of a new user");
}
OSDMap r = new OSDMap();
r["agent_id"] = user.PrincipalID;
resp = r;
}
else //Already exists
resp = false;
}
else //Could not find last name
resp = false;
}
else //Not enough params
resp = false;
return resp;
}
private OSD GetErrorCode(OSDMap map)
{
string userName = map["username"];
int last_name_id = map["last_name_id"];
bool found = false;
if (m_lastNameRegistry.ContainsKey(last_name_id))
{
string lastName = m_lastNameRegistry[last_name_id];
IUserAccountService accountService = m_registry.RequestModuleInterface<IUserAccountService>();
UserAccount user = accountService.GetUserAccount(UUID.Zero, userName, lastName);
if (user != null)
found = true;
}
return found;
}
private OSD GetLastNames(OSDMap map)
{
OSDMap resp = new OSDMap();
//Add all the last names
foreach (KeyValuePair<int, string> kvp in m_lastNameRegistry)
{
resp[kvp.Key.ToString()] = kvp.Value;
}
return resp;
}
}
}
| |
using System;
using System.Collections.Generic;
using Content.Server.Administration.Logs;
using Content.Server.NodeContainer;
using Content.Server.NodeContainer.EntitySystems;
using Content.Server.NodeContainer.NodeGroups;
using Content.Server.NodeContainer.Nodes;
using Content.Server.Power.Components;
using Content.Server.Power.EntitySystems;
using Content.Server.Power.NodeGroups;
using Content.Shared.Damage;
using Content.Shared.Damage.Prototypes;
using Content.Shared.Database;
using Content.Shared.Electrocution;
using Content.Shared.Interaction;
using Content.Shared.Jittering;
using Content.Shared.Maps;
using Content.Shared.Popups;
using Content.Shared.Pulling.Components;
using Content.Shared.Speech.EntitySystems;
using Content.Shared.StatusEffect;
using Content.Shared.Stunnable;
using Content.Shared.Tag;
using Content.Shared.Weapons.Melee;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using Robust.Shared.Physics.Dynamics;
using Robust.Shared.Player;
using Robust.Shared.Prototypes;
using Robust.Shared.Random;
using Robust.Shared.Utility;
namespace Content.Server.Electrocution
{
public sealed class ElectrocutionSystem : SharedElectrocutionSystem
{
[Dependency] private readonly EntityLookupSystem _entityLookup = default!;
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly IPrototypeManager _prototypeManager = default!;
[Dependency] private readonly StatusEffectsSystem _statusEffectsSystem = default!;
[Dependency] private readonly SharedJitteringSystem _jitteringSystem = default!;
[Dependency] private readonly SharedStunSystem _stunSystem = default!;
[Dependency] private readonly SharedStutteringSystem _stutteringSystem = default!;
[Dependency] private readonly SharedPopupSystem _popupSystem = default!;
[Dependency] private readonly DamageableSystem _damageableSystem = default!;
[Dependency] private readonly NodeGroupSystem _nodeGroupSystem = default!;
[Dependency] private readonly AdminLogSystem _logSystem = default!;
[Dependency] private readonly TagSystem _tagSystem = default!;
private const string StatusEffectKey = "Electrocution";
private const string DamageType = "Shock";
// Yes, this is absurdly small for a reason.
private const float ElectrifiedDamagePerWatt = 0.0015f;
private const float RecursiveDamageMultiplier = 0.75f;
private const float RecursiveTimeMultiplier = 0.8f;
private const float ParalyzeTimeMultiplier = 1f;
private const float StutteringTimeMultiplier = 1.5f;
private const float JitterTimeMultiplier = 0.75f;
private const float JitterAmplitude = 80f;
private const float JitterFrequency = 8f;
public override void Initialize()
{
base.Initialize();
SubscribeLocalEvent<ElectrifiedComponent, StartCollideEvent>(OnElectrifiedStartCollide);
SubscribeLocalEvent<ElectrifiedComponent, AttackedEvent>(OnElectrifiedAttacked);
SubscribeLocalEvent<ElectrifiedComponent, InteractHandEvent>(OnElectrifiedHandInteract);
SubscribeLocalEvent<ElectrifiedComponent, InteractUsingEvent>(OnElectrifiedInteractUsing);
SubscribeLocalEvent<RandomInsulationComponent, MapInitEvent>(OnRandomInsulationMapInit);
UpdatesAfter.Add(typeof(PowerNetSystem));
}
public override void Update(float frameTime)
{
// Update "in progress" electrocutions
RemQueue<ElectrocutionComponent> finishedElectrocutionsQueue = new();
foreach (var (electrocution, consumer) in EntityManager
.EntityQuery<ElectrocutionComponent, PowerConsumerComponent>())
{
var ftAdjusted = Math.Min(frameTime, electrocution.TimeLeft);
electrocution.TimeLeft -= ftAdjusted;
electrocution.AccumulatedDamage += consumer.ReceivedPower * ElectrifiedDamagePerWatt * ftAdjusted;
if (MathHelper.CloseTo(electrocution.TimeLeft, 0))
finishedElectrocutionsQueue.Add(electrocution);
}
foreach (var finished in finishedElectrocutionsQueue)
{
var uid = finished.Owner;
if (EntityManager.EntityExists(finished.Electrocuting))
{
// TODO: damage should be scaled by shock damage multiplier
// TODO: better paralyze/jitter timing
var damage = new DamageSpecifier(
_prototypeManager.Index<DamageTypePrototype>(DamageType),
(int) finished.AccumulatedDamage);
var actual = _damageableSystem.TryChangeDamage(finished.Electrocuting, damage);
if (actual != null)
{
_logSystem.Add(LogType.Electrocution,
$"{ToPrettyString(finished.Owner):entity} received {actual.Total:damage} powered electrocution damage");
}
}
EntityManager.DeleteEntity(uid);
}
}
private void OnElectrifiedStartCollide(EntityUid uid, ElectrifiedComponent electrified, StartCollideEvent args)
{
if (!electrified.OnBump)
return;
TryDoElectrifiedAct(uid, args.OtherFixture.Body.Owner, 1, electrified);
}
private void OnElectrifiedAttacked(EntityUid uid, ElectrifiedComponent electrified, AttackedEvent args)
{
if (!electrified.OnAttacked)
return;
TryDoElectrifiedAct(uid, args.User, 1, electrified);
}
private void OnElectrifiedHandInteract(EntityUid uid, ElectrifiedComponent electrified, InteractHandEvent args)
{
if (!electrified.OnHandInteract)
return;
TryDoElectrifiedAct(uid, args.User, 1, electrified);
}
private void OnElectrifiedInteractUsing(EntityUid uid, ElectrifiedComponent electrified, InteractUsingEvent args)
{
if (!electrified.OnInteractUsing)
return;
var siemens = TryComp(args.Used, out InsulatedComponent? insulation)
? insulation.SiemensCoefficient
: 1;
TryDoElectrifiedAct(uid, args.User, siemens, electrified);
}
public bool TryDoElectrifiedAct(EntityUid uid, EntityUid targetUid,
float siemens = 1,
ElectrifiedComponent? electrified = null,
NodeContainerComponent? nodeContainer = null,
TransformComponent? transform = null)
{
if (!Resolve(uid, ref electrified, ref transform, false))
return false;
if (!electrified.Enabled)
return false;
if (electrified.NoWindowInTile)
{
foreach (var entity in transform.Coordinates.GetEntitiesInTile(
LookupFlags.Approximate | LookupFlags.IncludeAnchored, _entityLookup))
{
if (_tagSystem.HasTag(entity, "Window"))
return false;
}
}
siemens *= electrified.SiemensCoefficient;
if (!DoCommonElectrocutionAttempt(targetUid, uid, ref siemens) || siemens <= 0)
return false; // If electrocution would fail, do nothing.
var targets = new List<(EntityUid entity, int depth)>();
GetChainedElectrocutionTargets(targetUid, targets);
if (!electrified.RequirePower)
{
var lastRet = true;
for (var i = targets.Count - 1; i >= 0; i--)
{
var (entity, depth) = targets[i];
lastRet = TryDoElectrocution(
entity,
uid,
(int) (electrified.ShockDamage * MathF.Pow(RecursiveDamageMultiplier, depth)),
TimeSpan.FromSeconds(electrified.ShockTime * MathF.Pow(RecursiveTimeMultiplier, depth)), true,
electrified.SiemensCoefficient);
}
return lastRet;
}
if (!Resolve(uid, ref nodeContainer, false))
return false;
var node = TryNode(electrified.HighVoltageNode) ??
TryNode(electrified.MediumVoltageNode) ??
TryNode(electrified.LowVoltageNode);
if (node == null)
return false;
var (damageMult, timeMult) = node.NodeGroupID switch
{
NodeGroupID.HVPower => (electrified.HighVoltageDamageMultiplier, electrified.HighVoltageTimeMultiplier),
NodeGroupID.MVPower => (electrified.MediumVoltageDamageMultiplier,
electrified.MediumVoltageTimeMultiplier),
_ => (1f, 1f)
};
{
var lastRet = true;
for (var i = targets.Count - 1; i >= 0; i--)
{
var (entity, depth) = targets[i];
lastRet = TryDoElectrocutionPowered(
entity,
uid,
node,
(int) (electrified.ShockDamage * MathF.Pow(RecursiveDamageMultiplier, depth) * damageMult),
TimeSpan.FromSeconds(electrified.ShockTime * MathF.Pow(RecursiveTimeMultiplier, depth) *
timeMult), true,
electrified.SiemensCoefficient);
}
return lastRet;
}
Node? TryNode(string? id)
{
if (id != null && nodeContainer.TryGetNode<Node>(id, out var tryNode)
&& tryNode.NodeGroup is IBasePowerNet { NetworkNode: { LastAvailableSupplySum: >0 } })
{
return tryNode;
}
return null;
}
}
/// <returns>Whether the entity <see cref="uid"/> was stunned by the shock.</returns>
public bool TryDoElectrocution(
EntityUid uid, EntityUid? sourceUid, int shockDamage, TimeSpan time, bool refresh, float siemensCoefficient = 1f,
StatusEffectsComponent? statusEffects = null)
{
if (!DoCommonElectrocutionAttempt(uid, sourceUid, ref siemensCoefficient)
|| !DoCommonElectrocution(uid, sourceUid, shockDamage, time, refresh, siemensCoefficient, statusEffects))
return false;
RaiseLocalEvent(uid, new ElectrocutedEvent(uid, sourceUid, siemensCoefficient));
return true;
}
private bool TryDoElectrocutionPowered(
EntityUid uid,
EntityUid sourceUid,
Node node,
int shockDamage,
TimeSpan time,
bool refresh,
float siemensCoefficient = 1f,
StatusEffectsComponent? statusEffects = null,
TransformComponent? sourceTransform = null)
{
if (!DoCommonElectrocutionAttempt(uid, sourceUid, ref siemensCoefficient))
return false;
// Coefficient needs to be higher than this to do a powered electrocution!
if(siemensCoefficient <= 0.5f)
return DoCommonElectrocution(uid, sourceUid, shockDamage, time, refresh, siemensCoefficient, statusEffects);
if (!DoCommonElectrocution(uid, sourceUid, null, time, refresh, siemensCoefficient, statusEffects))
return false;
if (!Resolve(sourceUid, ref sourceTransform)) // This shouldn't really happen, but just in case...
return true;
var electrocutionEntity = EntityManager.SpawnEntity(
$"VirtualElectrocutionLoad{node.NodeGroupID}", sourceTransform.Coordinates);
var electrocutionNode = EntityManager.GetComponent<NodeContainerComponent>(electrocutionEntity)
.GetNode<ElectrocutionNode>("electrocution");
var electrocutionComponent = EntityManager.GetComponent<ElectrocutionComponent>(electrocutionEntity);
electrocutionNode.CableEntity = sourceUid;
electrocutionNode.NodeName = node.Name;
_nodeGroupSystem.QueueReflood(electrocutionNode);
electrocutionComponent.TimeLeft = 1f;
electrocutionComponent.Electrocuting = uid;
RaiseLocalEvent(uid, new ElectrocutedEvent(uid, sourceUid, siemensCoefficient));
return true;
}
private bool DoCommonElectrocutionAttempt(EntityUid uid, EntityUid? sourceUid, ref float siemensCoefficient)
{
var attemptEvent = new ElectrocutionAttemptEvent(uid, sourceUid, siemensCoefficient);
RaiseLocalEvent(uid, attemptEvent);
// Cancel the electrocution early, so we don't recursively electrocute anything.
if (attemptEvent.Cancelled)
return false;
siemensCoefficient = attemptEvent.SiemensCoefficient;
return true;
}
private bool DoCommonElectrocution(EntityUid uid, EntityUid? sourceUid,
int? shockDamage, TimeSpan time, bool refresh, float siemensCoefficient = 1f,
StatusEffectsComponent? statusEffects = null)
{
if (siemensCoefficient <= 0)
return false;
if (shockDamage != null)
{
shockDamage = (int) (shockDamage * siemensCoefficient);
if (shockDamage.Value <= 0)
return false;
}
if (!Resolve(uid, ref statusEffects, false) ||
!_statusEffectsSystem.CanApplyEffect(uid, StatusEffectKey, statusEffects))
return false;
if (!_statusEffectsSystem.TryAddStatusEffect<ElectrocutedComponent>(uid, StatusEffectKey, time, refresh,
statusEffects))
return false;
var shouldStun = siemensCoefficient > 0.5f;
if (shouldStun)
_stunSystem.TryParalyze(uid, time * ParalyzeTimeMultiplier, refresh, statusEffects);
// TODO: Sparks here.
if(shockDamage is {} dmg)
{
var actual = _damageableSystem.TryChangeDamage(uid,
new DamageSpecifier(_prototypeManager.Index<DamageTypePrototype>(DamageType), dmg));
if (actual != null)
{
_logSystem.Add(LogType.Electrocution,
$"{ToPrettyString(statusEffects.Owner):entity} received {actual.Total:damage} powered electrocution damage");
}
}
_stutteringSystem.DoStutter(uid, time * StutteringTimeMultiplier, refresh, statusEffects);
_jitteringSystem.DoJitter(uid, time * JitterTimeMultiplier, refresh, JitterAmplitude, JitterFrequency, true,
statusEffects);
_popupSystem.PopupEntity(Loc.GetString("electrocuted-component-mob-shocked-popup-player"), uid,
Filter.Entities(uid).Unpredicted());
var filter = Filter.Pvs(uid, 2f, EntityManager).RemoveWhereAttachedEntity(puid => puid == uid)
.Unpredicted();
// TODO: Allow being able to pass EntityUid to Loc...
if (sourceUid != null)
{
_popupSystem.PopupEntity(Loc.GetString("electrocuted-component-mob-shocked-by-source-popup-others",
("mob", uid), ("source", (sourceUid.Value))), uid, filter);
}
else
{
_popupSystem.PopupEntity(Loc.GetString("electrocuted-component-mob-shocked-popup-others",
("mob", uid)), uid, filter);
}
return true;
}
private void GetChainedElectrocutionTargets(EntityUid source, List<(EntityUid entity, int depth)> all)
{
var visited = new HashSet<EntityUid>();
GetChainedElectrocutionTargetsRecurse(source, 1, visited, all);
}
private void GetChainedElectrocutionTargetsRecurse(
EntityUid entity,
int depth,
HashSet<EntityUid> visited,
List<(EntityUid entity, int depth)> all)
{
all.Add((entity, depth));
visited.Add(entity);
if (EntityManager.TryGetComponent(entity, out SharedPullableComponent? pullable)
&& pullable.Puller is {Valid: true} pullerId
&& !visited.Contains(pullerId))
{
GetChainedElectrocutionTargetsRecurse(pullerId, depth + 1, visited, all);
}
if (EntityManager.TryGetComponent(entity, out SharedPullerComponent? puller)
&& puller.Pulling is {Valid: true} pullingId
&& !visited.Contains(pullingId))
{
GetChainedElectrocutionTargetsRecurse(pullingId, depth + 1, visited, all);
}
}
private void OnRandomInsulationMapInit(EntityUid uid, RandomInsulationComponent randomInsulation,
MapInitEvent args)
{
if (!EntityManager.TryGetComponent(uid, out InsulatedComponent? insulated))
return;
if (randomInsulation.List.Length == 0)
return;
SetInsulatedSiemensCoefficient(uid, _random.Pick(randomInsulation.List), insulated);
}
}
}
| |
// 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.Data.Common;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace System.Data.SqlTypes
{
/// <summary>
/// Represents a floating-point number within the range of -1.79E
/// +308 through 1.79E +308 to be stored in or retrieved from a database.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
[XmlSchemaProvider("GetXsdType")]
public struct SqlDouble : INullable, IComparable, IXmlSerializable
{
private bool _fNotNull; // false if null
private double _value;
// constructor
// construct a Null
private SqlDouble(bool fNull)
{
_fNotNull = false;
_value = 0.0;
}
public SqlDouble(double value)
{
if (double.IsInfinity(value) || double.IsNaN(value))
throw new OverflowException(SQLResource.ArithOverflowMessage);
else
{
_value = value;
_fNotNull = true;
}
}
// INullable
public bool IsNull
{
get { return !_fNotNull; }
}
// property: Value
public double Value
{
get
{
if (_fNotNull)
return _value;
else
throw new SqlNullValueException();
}
}
// Implicit conversion from double to SqlDouble
public static implicit operator SqlDouble(double x)
{
return new SqlDouble(x);
}
// Explicit conversion from SqlDouble to double. Throw exception if x is Null.
public static explicit operator double (SqlDouble x)
{
return x.Value;
}
public override string ToString()
{
return IsNull ? SQLResource.NullString : _value.ToString((IFormatProvider)null);
}
public static SqlDouble Parse(string s)
{
if (s == SQLResource.NullString)
return SqlDouble.Null;
else
return new SqlDouble(double.Parse(s, CultureInfo.InvariantCulture));
}
// Unary operators
public static SqlDouble operator -(SqlDouble x)
{
return x.IsNull ? Null : new SqlDouble(-x._value);
}
// Binary operators
// Arithmetic operators
public static SqlDouble operator +(SqlDouble x, SqlDouble y)
{
if (x.IsNull || y.IsNull)
return Null;
double value = x._value + y._value;
if (double.IsInfinity(value))
throw new OverflowException(SQLResource.ArithOverflowMessage);
return new SqlDouble(value);
}
public static SqlDouble operator -(SqlDouble x, SqlDouble y)
{
if (x.IsNull || y.IsNull)
return Null;
double value = x._value - y._value;
if (double.IsInfinity(value))
throw new OverflowException(SQLResource.ArithOverflowMessage);
return new SqlDouble(value);
}
public static SqlDouble operator *(SqlDouble x, SqlDouble y)
{
if (x.IsNull || y.IsNull)
return Null;
double value = x._value * y._value;
if (double.IsInfinity(value))
throw new OverflowException(SQLResource.ArithOverflowMessage);
return new SqlDouble(value);
}
public static SqlDouble operator /(SqlDouble x, SqlDouble y)
{
if (x.IsNull || y.IsNull)
return Null;
if (y._value == 0.0)
throw new DivideByZeroException(SQLResource.DivideByZeroMessage);
double value = x._value / y._value;
if (double.IsInfinity(value))
throw new OverflowException(SQLResource.ArithOverflowMessage);
return new SqlDouble(value);
}
// Implicit conversions
// Implicit conversion from SqlBoolean to SqlDouble
public static explicit operator SqlDouble(SqlBoolean x)
{
return x.IsNull ? Null : new SqlDouble(x.ByteValue);
}
// Implicit conversion from SqlByte to SqlDouble
public static implicit operator SqlDouble(SqlByte x)
{
return x.IsNull ? Null : new SqlDouble(x.Value);
}
// Implicit conversion from SqlInt16 to SqlDouble
public static implicit operator SqlDouble(SqlInt16 x)
{
return x.IsNull ? Null : new SqlDouble(x.Value);
}
// Implicit conversion from SqlInt32 to SqlDouble
public static implicit operator SqlDouble(SqlInt32 x)
{
return x.IsNull ? Null : new SqlDouble(x.Value);
}
// Implicit conversion from SqlInt64 to SqlDouble
public static implicit operator SqlDouble(SqlInt64 x)
{
return x.IsNull ? Null : new SqlDouble(x.Value);
}
// Implicit conversion from SqlSingle to SqlDouble
public static implicit operator SqlDouble(SqlSingle x)
{
return x.IsNull ? Null : new SqlDouble(x.Value);
}
// Implicit conversion from SqlMoney to SqlDouble
public static implicit operator SqlDouble(SqlMoney x)
{
return x.IsNull ? Null : new SqlDouble(x.ToDouble());
}
// Implicit conversion from SqlDecimal to SqlDouble
public static implicit operator SqlDouble(SqlDecimal x)
{
return x.IsNull ? Null : new SqlDouble(x.ToDouble());
}
// Explicit conversions
// Explicit conversion from SqlString to SqlDouble
// Throws FormatException or OverflowException if necessary.
public static explicit operator SqlDouble(SqlString x)
{
if (x.IsNull)
return SqlDouble.Null;
return Parse(x.Value);
}
// Overloading comparison operators
public static SqlBoolean operator ==(SqlDouble x, SqlDouble y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value == y._value);
}
public static SqlBoolean operator !=(SqlDouble x, SqlDouble y)
{
return !(x == y);
}
public static SqlBoolean operator <(SqlDouble x, SqlDouble y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value < y._value);
}
public static SqlBoolean operator >(SqlDouble x, SqlDouble y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value > y._value);
}
public static SqlBoolean operator <=(SqlDouble x, SqlDouble y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value <= y._value);
}
public static SqlBoolean operator >=(SqlDouble x, SqlDouble y)
{
return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value >= y._value);
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator +
public static SqlDouble Add(SqlDouble x, SqlDouble y)
{
return x + y;
}
// Alternative method for operator -
public static SqlDouble Subtract(SqlDouble x, SqlDouble y)
{
return x - y;
}
// Alternative method for operator *
public static SqlDouble Multiply(SqlDouble x, SqlDouble y)
{
return x * y;
}
// Alternative method for operator /
public static SqlDouble Divide(SqlDouble x, SqlDouble y)
{
return x / y;
}
// Alternative method for operator ==
public static SqlBoolean Equals(SqlDouble x, SqlDouble y)
{
return (x == y);
}
// Alternative method for operator !=
public static SqlBoolean NotEquals(SqlDouble x, SqlDouble y)
{
return (x != y);
}
// Alternative method for operator <
public static SqlBoolean LessThan(SqlDouble x, SqlDouble y)
{
return (x < y);
}
// Alternative method for operator >
public static SqlBoolean GreaterThan(SqlDouble x, SqlDouble y)
{
return (x > y);
}
// Alternative method for operator <=
public static SqlBoolean LessThanOrEqual(SqlDouble x, SqlDouble y)
{
return (x <= y);
}
// Alternative method for operator >=
public static SqlBoolean GreaterThanOrEqual(SqlDouble x, SqlDouble y)
{
return (x >= y);
}
// Alternative method for conversions.
public SqlBoolean ToSqlBoolean()
{
return (SqlBoolean)this;
}
public SqlByte ToSqlByte()
{
return (SqlByte)this;
}
public SqlInt16 ToSqlInt16()
{
return (SqlInt16)this;
}
public SqlInt32 ToSqlInt32()
{
return (SqlInt32)this;
}
public SqlInt64 ToSqlInt64()
{
return (SqlInt64)this;
}
public SqlMoney ToSqlMoney()
{
return (SqlMoney)this;
}
public SqlDecimal ToSqlDecimal()
{
return (SqlDecimal)this;
}
public SqlSingle ToSqlSingle()
{
return (SqlSingle)this;
}
public SqlString ToSqlString()
{
return (SqlString)this;
}
// IComparable
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this < object, zero if this = object,
// or a value greater than zero if this > object.
// null is considered to be less than any instance.
// If object is not of same type, this method throws an ArgumentException.
public int CompareTo(object value)
{
if (value is SqlDouble)
{
SqlDouble i = (SqlDouble)value;
return CompareTo(i);
}
throw ADP.WrongType(value.GetType(), typeof(SqlDouble));
}
public int CompareTo(SqlDouble value)
{
// If both Null, consider them equal.
// Otherwise, Null is less than anything.
if (IsNull)
return value.IsNull ? 0 : -1;
else if (value.IsNull)
return 1;
if (this < value) return -1;
if (this > value) return 1;
return 0;
}
// Compares this instance with a specified object
public override bool Equals(object value)
{
if (!(value is SqlDouble))
{
return false;
}
SqlDouble i = (SqlDouble)value;
if (i.IsNull || IsNull)
return (i.IsNull && IsNull);
else
return (this == i).Value;
}
// For hashing purpose
public override int GetHashCode()
{
return IsNull ? 0 : Value.GetHashCode();
}
XmlSchema IXmlSerializable.GetSchema() { return null; }
void IXmlSerializable.ReadXml(XmlReader reader)
{
string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace);
if (isNull != null && XmlConvert.ToBoolean(isNull))
{
// Read the next value.
reader.ReadElementString();
_fNotNull = false;
}
else
{
_value = XmlConvert.ToDouble(reader.ReadElementString());
_fNotNull = true;
}
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (IsNull)
{
writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
}
else
{
writer.WriteString(XmlConvert.ToString(_value));
}
}
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet)
{
return new XmlQualifiedName("double", XmlSchema.Namespace);
}
public static readonly SqlDouble Null = new SqlDouble(true);
public static readonly SqlDouble Zero = new SqlDouble(0.0);
public static readonly SqlDouble MinValue = new SqlDouble(double.MinValue);
public static readonly SqlDouble MaxValue = new SqlDouble(double.MaxValue);
} // SqlDouble
} // namespace System.Data.SqlTypes
| |
/*
* Copyright 2021 Google LLC All Rights Reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file or at
* https://developers.google.com/open-source/licenses/bsd
*/
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/api/documentation.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Api {
/// <summary>Holder for reflection information generated from google/api/documentation.proto</summary>
public static partial class DocumentationReflection {
#region Descriptor
/// <summary>File descriptor for google/api/documentation.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static DocumentationReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Ch5nb29nbGUvYXBpL2RvY3VtZW50YXRpb24ucHJvdG8SCmdvb2dsZS5hcGki",
"uwEKDURvY3VtZW50YXRpb24SDwoHc3VtbWFyeRgBIAEoCRIfCgVwYWdlcxgF",
"IAMoCzIQLmdvb2dsZS5hcGkuUGFnZRIsCgVydWxlcxgDIAMoCzIdLmdvb2ds",
"ZS5hcGkuRG9jdW1lbnRhdGlvblJ1bGUSHgoWZG9jdW1lbnRhdGlvbl9yb290",
"X3VybBgEIAEoCRIYChBzZXJ2aWNlX3Jvb3RfdXJsGAYgASgJEhAKCG92ZXJ2",
"aWV3GAIgASgJIlsKEURvY3VtZW50YXRpb25SdWxlEhAKCHNlbGVjdG9yGAEg",
"ASgJEhMKC2Rlc2NyaXB0aW9uGAIgASgJEh8KF2RlcHJlY2F0aW9uX2Rlc2Ny",
"aXB0aW9uGAMgASgJIkkKBFBhZ2USDAoEbmFtZRgBIAEoCRIPCgdjb250ZW50",
"GAIgASgJEiIKCHN1YnBhZ2VzGAMgAygLMhAuZ29vZ2xlLmFwaS5QYWdlQnQK",
"DmNvbS5nb29nbGUuYXBpQhJEb2N1bWVudGF0aW9uUHJvdG9QAVpFZ29vZ2xl",
"LmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9hcGkvc2VydmljZWNv",
"bmZpZztzZXJ2aWNlY29uZmlnogIER0FQSWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Documentation), global::Google.Api.Documentation.Parser, new[]{ "Summary", "Pages", "Rules", "DocumentationRootUrl", "ServiceRootUrl", "Overview" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.DocumentationRule), global::Google.Api.DocumentationRule.Parser, new[]{ "Selector", "Description", "DeprecationDescription" }, null, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.Page), global::Google.Api.Page.Parser, new[]{ "Name", "Content", "Subpages" }, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// `Documentation` provides the information for describing a service.
///
/// Example:
/// <pre><code>documentation:
/// summary: >
/// The Google Calendar API gives access
/// to most calendar features.
/// pages:
/// - name: Overview
/// content: &#40;== include google/foo/overview.md ==&#41;
/// - name: Tutorial
/// content: &#40;== include google/foo/tutorial.md ==&#41;
/// subpages;
/// - name: Java
/// content: &#40;== include google/foo/tutorial_java.md ==&#41;
/// rules:
/// - selector: google.calendar.Calendar.Get
/// description: >
/// ...
/// - selector: google.calendar.Calendar.Put
/// description: >
/// ...
/// </code></pre>
/// Documentation is provided in markdown syntax. In addition to
/// standard markdown features, definition lists, tables and fenced
/// code blocks are supported. Section headers can be provided and are
/// interpreted relative to the section nesting of the context where
/// a documentation fragment is embedded.
///
/// Documentation from the IDL is merged with documentation defined
/// via the config at normalization time, where documentation provided
/// by config rules overrides IDL provided.
///
/// A number of constructs specific to the API platform are supported
/// in documentation text.
///
/// In order to reference a proto element, the following
/// notation can be used:
/// <pre><code>&#91;fully.qualified.proto.name]&#91;]</code></pre>
/// To override the display text used for the link, this can be used:
/// <pre><code>&#91;display text]&#91;fully.qualified.proto.name]</code></pre>
/// Text can be excluded from doc using the following notation:
/// <pre><code>&#40;-- internal comment --&#41;</code></pre>
///
/// A few directives are available in documentation. Note that
/// directives must appear on a single line to be properly
/// identified. The `include` directive includes a markdown file from
/// an external source:
/// <pre><code>&#40;== include path/to/file ==&#41;</code></pre>
/// The `resource_for` directive marks a message to be the resource of
/// a collection in REST view. If it is not specified, tools attempt
/// to infer the resource from the operations in a collection:
/// <pre><code>&#40;== resource_for v1.shelves.books ==&#41;</code></pre>
/// The directive `suppress_warning` does not directly affect documentation
/// and is documented together with service config validation.
/// </summary>
public sealed partial class Documentation : pb::IMessage<Documentation>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Documentation> _parser = new pb::MessageParser<Documentation>(() => new Documentation());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<Documentation> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.DocumentationReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Documentation() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Documentation(Documentation other) : this() {
summary_ = other.summary_;
pages_ = other.pages_.Clone();
rules_ = other.rules_.Clone();
documentationRootUrl_ = other.documentationRootUrl_;
serviceRootUrl_ = other.serviceRootUrl_;
overview_ = other.overview_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Documentation Clone() {
return new Documentation(this);
}
/// <summary>Field number for the "summary" field.</summary>
public const int SummaryFieldNumber = 1;
private string summary_ = "";
/// <summary>
/// A short summary of what the service does. Can only be provided by
/// plain text.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Summary {
get { return summary_; }
set {
summary_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "pages" field.</summary>
public const int PagesFieldNumber = 5;
private static readonly pb::FieldCodec<global::Google.Api.Page> _repeated_pages_codec
= pb::FieldCodec.ForMessage(42, global::Google.Api.Page.Parser);
private readonly pbc::RepeatedField<global::Google.Api.Page> pages_ = new pbc::RepeatedField<global::Google.Api.Page>();
/// <summary>
/// The top level pages for the documentation set.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::RepeatedField<global::Google.Api.Page> Pages {
get { return pages_; }
}
/// <summary>Field number for the "rules" field.</summary>
public const int RulesFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Api.DocumentationRule> _repeated_rules_codec
= pb::FieldCodec.ForMessage(26, global::Google.Api.DocumentationRule.Parser);
private readonly pbc::RepeatedField<global::Google.Api.DocumentationRule> rules_ = new pbc::RepeatedField<global::Google.Api.DocumentationRule>();
/// <summary>
/// A list of documentation rules that apply to individual API elements.
///
/// **NOTE:** All service configuration rules follow "last one wins" order.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::RepeatedField<global::Google.Api.DocumentationRule> Rules {
get { return rules_; }
}
/// <summary>Field number for the "documentation_root_url" field.</summary>
public const int DocumentationRootUrlFieldNumber = 4;
private string documentationRootUrl_ = "";
/// <summary>
/// The URL to the root of documentation.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string DocumentationRootUrl {
get { return documentationRootUrl_; }
set {
documentationRootUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "service_root_url" field.</summary>
public const int ServiceRootUrlFieldNumber = 6;
private string serviceRootUrl_ = "";
/// <summary>
/// Specifies the service root url if the default one (the service name
/// from the yaml file) is not suitable. This can be seen in any fully
/// specified service urls as well as sections that show a base that other
/// urls are relative to.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string ServiceRootUrl {
get { return serviceRootUrl_; }
set {
serviceRootUrl_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "overview" field.</summary>
public const int OverviewFieldNumber = 2;
private string overview_ = "";
/// <summary>
/// Declares a single overview page. For example:
/// <pre><code>documentation:
/// summary: ...
/// overview: &#40;== include overview.md ==&#41;
/// </code></pre>
/// This is a shortcut for the following declaration (using pages style):
/// <pre><code>documentation:
/// summary: ...
/// pages:
/// - name: Overview
/// content: &#40;== include overview.md ==&#41;
/// </code></pre>
/// Note: you cannot specify both `overview` field and `pages` field.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Overview {
get { return overview_; }
set {
overview_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as Documentation);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(Documentation other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Summary != other.Summary) return false;
if(!pages_.Equals(other.pages_)) return false;
if(!rules_.Equals(other.rules_)) return false;
if (DocumentationRootUrl != other.DocumentationRootUrl) return false;
if (ServiceRootUrl != other.ServiceRootUrl) return false;
if (Overview != other.Overview) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Summary.Length != 0) hash ^= Summary.GetHashCode();
hash ^= pages_.GetHashCode();
hash ^= rules_.GetHashCode();
if (DocumentationRootUrl.Length != 0) hash ^= DocumentationRootUrl.GetHashCode();
if (ServiceRootUrl.Length != 0) hash ^= ServiceRootUrl.GetHashCode();
if (Overview.Length != 0) hash ^= Overview.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Summary.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Summary);
}
if (Overview.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Overview);
}
rules_.WriteTo(output, _repeated_rules_codec);
if (DocumentationRootUrl.Length != 0) {
output.WriteRawTag(34);
output.WriteString(DocumentationRootUrl);
}
pages_.WriteTo(output, _repeated_pages_codec);
if (ServiceRootUrl.Length != 0) {
output.WriteRawTag(50);
output.WriteString(ServiceRootUrl);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Summary.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Summary);
}
if (Overview.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Overview);
}
rules_.WriteTo(ref output, _repeated_rules_codec);
if (DocumentationRootUrl.Length != 0) {
output.WriteRawTag(34);
output.WriteString(DocumentationRootUrl);
}
pages_.WriteTo(ref output, _repeated_pages_codec);
if (ServiceRootUrl.Length != 0) {
output.WriteRawTag(50);
output.WriteString(ServiceRootUrl);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Summary.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Summary);
}
size += pages_.CalculateSize(_repeated_pages_codec);
size += rules_.CalculateSize(_repeated_rules_codec);
if (DocumentationRootUrl.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DocumentationRootUrl);
}
if (ServiceRootUrl.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(ServiceRootUrl);
}
if (Overview.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Overview);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(Documentation other) {
if (other == null) {
return;
}
if (other.Summary.Length != 0) {
Summary = other.Summary;
}
pages_.Add(other.pages_);
rules_.Add(other.rules_);
if (other.DocumentationRootUrl.Length != 0) {
DocumentationRootUrl = other.DocumentationRootUrl;
}
if (other.ServiceRootUrl.Length != 0) {
ServiceRootUrl = other.ServiceRootUrl;
}
if (other.Overview.Length != 0) {
Overview = other.Overview;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Summary = input.ReadString();
break;
}
case 18: {
Overview = input.ReadString();
break;
}
case 26: {
rules_.AddEntriesFrom(input, _repeated_rules_codec);
break;
}
case 34: {
DocumentationRootUrl = input.ReadString();
break;
}
case 42: {
pages_.AddEntriesFrom(input, _repeated_pages_codec);
break;
}
case 50: {
ServiceRootUrl = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Summary = input.ReadString();
break;
}
case 18: {
Overview = input.ReadString();
break;
}
case 26: {
rules_.AddEntriesFrom(ref input, _repeated_rules_codec);
break;
}
case 34: {
DocumentationRootUrl = input.ReadString();
break;
}
case 42: {
pages_.AddEntriesFrom(ref input, _repeated_pages_codec);
break;
}
case 50: {
ServiceRootUrl = input.ReadString();
break;
}
}
}
}
#endif
}
/// <summary>
/// A documentation rule provides information about individual API elements.
/// </summary>
public sealed partial class DocumentationRule : pb::IMessage<DocumentationRule>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<DocumentationRule> _parser = new pb::MessageParser<DocumentationRule>(() => new DocumentationRule());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<DocumentationRule> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.DocumentationReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public DocumentationRule() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public DocumentationRule(DocumentationRule other) : this() {
selector_ = other.selector_;
description_ = other.description_;
deprecationDescription_ = other.deprecationDescription_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public DocumentationRule Clone() {
return new DocumentationRule(this);
}
/// <summary>Field number for the "selector" field.</summary>
public const int SelectorFieldNumber = 1;
private string selector_ = "";
/// <summary>
/// The selector is a comma-separated list of patterns. Each pattern is a
/// qualified name of the element which may end in "*", indicating a wildcard.
/// Wildcards are only allowed at the end and for a whole component of the
/// qualified name, i.e. "foo.*" is ok, but not "foo.b*" or "foo.*.bar". A
/// wildcard will match one or more components. To specify a default for all
/// applicable elements, the whole pattern "*" is used.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Selector {
get { return selector_; }
set {
selector_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "description" field.</summary>
public const int DescriptionFieldNumber = 2;
private string description_ = "";
/// <summary>
/// Description of the selected API(s).
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Description {
get { return description_; }
set {
description_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "deprecation_description" field.</summary>
public const int DeprecationDescriptionFieldNumber = 3;
private string deprecationDescription_ = "";
/// <summary>
/// Deprecation description of the selected element(s). It can be provided if
/// an element is marked as `deprecated`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string DeprecationDescription {
get { return deprecationDescription_; }
set {
deprecationDescription_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as DocumentationRule);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(DocumentationRule other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Selector != other.Selector) return false;
if (Description != other.Description) return false;
if (DeprecationDescription != other.DeprecationDescription) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Selector.Length != 0) hash ^= Selector.GetHashCode();
if (Description.Length != 0) hash ^= Description.GetHashCode();
if (DeprecationDescription.Length != 0) hash ^= DeprecationDescription.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Selector.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Selector);
}
if (Description.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Description);
}
if (DeprecationDescription.Length != 0) {
output.WriteRawTag(26);
output.WriteString(DeprecationDescription);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Selector.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Selector);
}
if (Description.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Description);
}
if (DeprecationDescription.Length != 0) {
output.WriteRawTag(26);
output.WriteString(DeprecationDescription);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Selector.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Selector);
}
if (Description.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Description);
}
if (DeprecationDescription.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DeprecationDescription);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(DocumentationRule other) {
if (other == null) {
return;
}
if (other.Selector.Length != 0) {
Selector = other.Selector;
}
if (other.Description.Length != 0) {
Description = other.Description;
}
if (other.DeprecationDescription.Length != 0) {
DeprecationDescription = other.DeprecationDescription;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Selector = input.ReadString();
break;
}
case 18: {
Description = input.ReadString();
break;
}
case 26: {
DeprecationDescription = input.ReadString();
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Selector = input.ReadString();
break;
}
case 18: {
Description = input.ReadString();
break;
}
case 26: {
DeprecationDescription = input.ReadString();
break;
}
}
}
}
#endif
}
/// <summary>
/// Represents a documentation page. A page can contain subpages to represent
/// nested documentation set structure.
/// </summary>
public sealed partial class Page : pb::IMessage<Page>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<Page> _parser = new pb::MessageParser<Page>(() => new Page());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pb::MessageParser<Page> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Api.DocumentationReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Page() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Page(Page other) : this() {
name_ = other.name_;
content_ = other.content_;
subpages_ = other.subpages_.Clone();
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public Page Clone() {
return new Page(this);
}
/// <summary>Field number for the "name" field.</summary>
public const int NameFieldNumber = 1;
private string name_ = "";
/// <summary>
/// The name of the page. It will be used as an identity of the page to
/// generate URI of the page, text of the link to this page in navigation,
/// etc. The full page name (start from the root page name to this page
/// concatenated with `.`) can be used as reference to the page in your
/// documentation. For example:
/// <pre><code>pages:
/// - name: Tutorial
/// content: &#40;== include tutorial.md ==&#41;
/// subpages:
/// - name: Java
/// content: &#40;== include tutorial_java.md ==&#41;
/// </code></pre>
/// You can reference `Java` page using Markdown reference link syntax:
/// `[Java][Tutorial.Java]`.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Name {
get { return name_; }
set {
name_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "content" field.</summary>
public const int ContentFieldNumber = 2;
private string content_ = "";
/// <summary>
/// The Markdown content of the page. You can use <code>&#40;== include {path}
/// ==&#41;</code> to include content from a Markdown file.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public string Content {
get { return content_; }
set {
content_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "subpages" field.</summary>
public const int SubpagesFieldNumber = 3;
private static readonly pb::FieldCodec<global::Google.Api.Page> _repeated_subpages_codec
= pb::FieldCodec.ForMessage(26, global::Google.Api.Page.Parser);
private readonly pbc::RepeatedField<global::Google.Api.Page> subpages_ = new pbc::RepeatedField<global::Google.Api.Page>();
/// <summary>
/// Subpages of this page. The order of subpages specified here will be
/// honored in the generated docset.
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public pbc::RepeatedField<global::Google.Api.Page> Subpages {
get { return subpages_; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override bool Equals(object other) {
return Equals(other as Page);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public bool Equals(Page other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Name != other.Name) return false;
if (Content != other.Content) return false;
if(!subpages_.Equals(other.subpages_)) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override int GetHashCode() {
int hash = 1;
if (Name.Length != 0) hash ^= Name.GetHashCode();
if (Content.Length != 0) hash ^= Content.GetHashCode();
hash ^= subpages_.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Content.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Content);
}
subpages_.WriteTo(output, _repeated_subpages_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (Name.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Name);
}
if (Content.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Content);
}
subpages_.WriteTo(ref output, _repeated_subpages_codec);
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public int CalculateSize() {
int size = 0;
if (Name.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Name);
}
if (Content.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Content);
}
size += subpages_.CalculateSize(_repeated_subpages_codec);
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(Page other) {
if (other == null) {
return;
}
if (other.Name.Length != 0) {
Name = other.Name;
}
if (other.Content.Length != 0) {
Content = other.Content;
}
subpages_.Add(other.subpages_);
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
Content = input.ReadString();
break;
}
case 26: {
subpages_.AddEntriesFrom(input, _repeated_subpages_codec);
break;
}
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
case 10: {
Name = input.ReadString();
break;
}
case 18: {
Content = input.ReadString();
break;
}
case 26: {
subpages_.AddEntriesFrom(ref input, _repeated_subpages_codec);
break;
}
}
}
}
#endif
}
#endregion
}
#endregion Designer generated code
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.